Debian Codegraph @

src/libexc.scm

raw
1 ;;;
2 ;;; libexc.scm - errors and exceptions
3 ;;;
4 ;;; Copyright (c) 2000-2024 Shiro Kawai <[email protected]>
5 ;;;
6 ;;; Redistribution and use in source and binary forms, with or without
7 ;;; modification, are permitted provided that the following conditions
8 ;;; are met:
9 ;;;
10 ;;; 1. Redistributions of source code must retain the above copyright
11 ;;; notice, this list of conditions and the following disclaimer.
12 ;;;
13 ;;; 2. Redistributions in binary form must reproduce the above copyright
14 ;;; notice, this list of conditions and the following disclaimer in the
15 ;;; documentation and/or other materials provided with the distribution.
16 ;;;
17 ;;; 3. Neither the name of the authors nor the names of its contributors
18 ;;; may be used to endorse or promote products derived from this
19 ;;; software without specific prior written permission.
20 ;;;
21 ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27 ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 ;;;
33
34 (select-module gauche)
35 (inline-stub
36 (.include "gauche/priv/configP.h"
37 "gauche/exception.h"))
38
39 (use util.match)
40 (declare (keep-private-macro define-condition-type condition))
41
42 (define <exception> <condition>) ;; backward compatibility
43
44 ;;;
45 ;;; Core procedures
46 ;;;
47
48 (select-module gauche)
49 ;; NB: rewind-before keyword arg is EXPERIMENTAL.
50 (define-cproc with-error-handler
51 (handler thunk :key (rewind-before::<boolean> #f))
52 (unless (SCM_PROCEDURE_TAKE_NARG_P handler 1)
53 (Scm_Error "error handler must take at least 1 argument, but got %S"
54 handler))
55 (unless (SCM_PROCEDURE_THUNK_P thunk)
56 (Scm_Error "thunk required, but got %S" thunk))
57 (if rewind-before
58 (return (Scm_VMWithGuardHandler handler thunk))
59 (return (Scm_VMWithErrorHandler handler thunk))))
60
61 (define-cproc report-error (exception :optional (port (current-error-port)))
62 Scm_ReportError)
63
64 (define-cproc condition-type-name (c) Scm_ConditionTypeName)
65
66 ;; A convenience procedure; safe for non-message condition objects.
67 ;; (cf. error-object-message of r7rs)
68 (define (condition-message e :optional (fallback #f))
69 (if (and (condition? e)
70 (condition-has-type? e <message-condition>))
71 (condition-ref e 'message)
72 fallback))
73
74 (define (print-default-error-heading exc out)
75 (assume-type out <output-port>)
76 (cond [(not (condition? exc))
77 (format out "*** ERROR: unhandled exception: ~s\n" exc)]
78 [(condition-has-type? exc <message-condition>)
79 (format out "*** ~a: ~,,,,200:a\n"
80 (condition-type-name exc) (~ exc'message))]
81 [else
82 (format out "*** ~a\n" (condition-type-name exc))]))
83
84 ;; Additional reporting. We report mixins after main conditions,
85 ;; for mixing give additional context (e.g. "when compiling ...")
86 (define (print-additional-error-heading exc out)
87 (define (additional-condition c)
88 (guard (e [else (warn "Error from (report-additional-condition ~s)\n" c)
89 #f])
90 (report-additional-condition c out)))
91 (assume-type out <output-port>)
92 (when (condition? exc)
93 (receive (mixins mains)
94 (if (is-a? exc <compound-condition>)
95 (partition (cut is-a? <> <mixin-condition>) (~ exc'%conditions))
96 (values '() (list exc)))
97 (for-each additional-condition mains)
98 (for-each additional-condition mixins))))
99
100 (select-module gauche.internal)
101 (define-cproc %type-error (what::<const-cstring>
102 expected-type::<const-cstring>
103 actual-object)
104 ::<void> Scm_TypeError)
105
106 (define-in-module gauche (type-error expr expected-type actual-object)
107 (%type-error (write-to-string expr)
108 (write-to-string expected-type) ;TODO: nicer formatting in future
109 actual-object))
110
111 ;;;
112 ;;; Srfi-18, Srfi-226 primitives
113 ;;;
114
115 (select-module gauche)
116 (define-cproc current-exception-handler () Scm_VMCurrentExceptionHandler)
117 (define-cproc exception-handler-stack () Scm_VMExceptionHandlerStack)
118 (define-cproc with-exception-handler (handler thunk)
119 Scm_VMWithExceptionHandler)
120
121 ;; The optional arg is to support r7rs semantics
122 (select-module gauche.internal)
123 (define-cproc %raise (exception :optional (non-continuable? #f))
124 (let* ([flags::u_long
125 (?: (SCM_FALSEP non-continuable?) 0 SCM_RAISE_NON_CONTINUABLE)])
126 (return (Scm_Raise exception flags))))
127
128 ;; For r7rs compatible guard.
129 ;; %reraise must be called at the tail position of the error handler.
130 ;; It tells the VM that the error handler returns from handling a continuable
131 ;; exception.
132 ;; After this returns, the control gets back to Scm_VMDefaultExceptionHandler,
133 ;; which restores dynamic environment and returns to the original caller
134 ;; of raise-continuable.
135 (define-cproc %reraise ()
136 (return (Scm_VMReraise)))
137
138 ;; SRFI-18 raise
139 (define-in-module gauche (raise c) (%raise c))
140
141 ;; R7RS raise-continuable is effectively same as Gauche's raise
142 (define-in-module gauche (raise-continuable c) (raise c))
143
144 ;;;
145 ;;; Srfi-35
146 ;;;
147
148 (select-module gauche)
149
150 (define-cproc condition? (obj) ::<boolean> SCM_CONDITIONP)
151
152 (define-cproc condition-has-type? (c k) ::<boolean> Scm_ConditionHasType)
153
154 (define-cproc make-compound-condition (:rest conditions)
155 Scm_MakeCompoundCondition)
156
157 (define (make-condition-type name parent field-names)
158 (unless (condition-type? parent)
159 (error "condition-type required as a parent of make-condition-type, but got:" parent))
160 (make <condition-meta>
161 :name name
162 :supers (list parent)
163 :slots field-names))
164
165 (define (condition-type? obj)
166 (is-a? obj <condition-meta>))
167
168 (define (make-condition type . initargs)
169 (unless (condition-type? type)
170 (error "make-condition requires a condition type, but got:" type))
171 (let ((c (make type)))
172 (let loop ((args initargs))
173 (cond ((null? args) c)
174 ((null? (cdr args))
175 (error "make-condition is given non-even initargs:" initargs))
176 ((slot-exists? c (car args))
177 (slot-set! c (car args) (cadr args))
178 (loop (cddr args)))
179 (else
180 (errorf "condition type ~s doesn't have a field ~s"
181 type (car args)))))))
182
183 (define (condition-ref c slot)
184 (slot-ref c slot)) ;; compound condition traps slot-missing
185
186 (define (extract-condition c type)
187 (unless (condition-has-type? c type)
188 (errorf "cannot extract a condition of type ~s from a condition ~s"
189 type c))
190 (let ((cc (make type)))
191 (let loop ((slots (class-slots type)))
192 (if (null? slots)
193 cc
194 (let ((sn (slot-definition-name (car slots))))
195 (when (slot-bound? c sn)
196 (slot-set! cc sn (slot-ref c sn)))
197 (loop (cdr slots)))))))
198
199 ;; SRFI-35/SRFI-36 compatibility
200 (define &condition <condition>)
201 (define &message <message-condition>)
202 (define &serious <serious-condition>)
203 (define &error <error>)
204 (define &i/o-error <io-error>)
205 (define &i/o-port-error <port-error>)
206 (define &i/o-read-error <io-read-error>)
207 (define &i/o-write-error <io-write-error>)
208 (define &i/o-closed-error <io-closed-error>)
209 (define &read-error <read-error>)
210
211 (define (message-condition? obj) (is-a? obj <message-condition>))
212 (define (serious-condition? obj) (is-a? obj <serious-condition>))
213 (define (error? obj) (is-a? obj <error>))
214
215 ;; SRFI-226
216 (define &continuation <continuation-violation>)
217 (define (make-continuation-violation tag)
218 (make <continuation-violation> :prompt-tag tag))
219 (define (continuation-violation? obj)
220 (is-a? obj <continuation-violation>))
221 (define (continuation-violation-prompt-tag condition)
222 (assume-type condition <continuation-violation>)
223 (~ condition 'prompt-tag))
224
225 ;;;
226 ;;; Thread exception classes
227 ;;;
228
229 ;; TODO - set metaclass of those exceptions to <condition-meta>
230
231 (select-module gauche.threads)
232 (inline-stub
233 (define-cfn thread_exception_allocate (klass::ScmClass* _) :static
234 (return (Scm_MakeThreadException klass NULL)))
235
236 (define-cfn thread_exception_print (obj port::ScmPort* _::ScmWriteContext*)
237 ::void :static
238 (let* ([k::ScmClass* (SCM_CLASS_OF obj)]
239 [exc::ScmThreadException* (SCM_THREAD_EXCEPTION obj)]
240 [cname (Scm_ShortClassName k)])
241 (if (SCM_UNDEFINEDP (-> exc data))
242 (Scm_Printf port "#<%A %S>" cname (SCM_OBJ_SAFE (-> exc thread)))
243 (Scm_Printf port "#<%A %S %S>" cname (SCM_OBJ_SAFE (-> exc thread))
244 (-> exc data)))))
245
246 (define-cfn uncaught_exception_print (obj port::ScmPort* _::ScmWriteContext*)
247 ::void :static
248 (let* ([exc::ScmThreadException* (SCM_THREAD_EXCEPTION obj)])
249 (Scm_Printf port "#<uncaught-exception in thread %S: %S>"
250 (SCM_OBJ_SAFE (-> exc thread)) (-> exc data))))
251
252 (define-cfn terminated_thread_print (obj port::ScmPort* _::ScmWriteContext*)
253 ::void :static
254 (let* ([exc::ScmThreadException* (SCM_THREAD_EXCEPTION obj)])
255 (Scm_Printf port "#<terminated-thread-exception: %S terminated by %S>"
256 (SCM_OBJ_SAFE (-> exc thread)) (-> exc data))))
257
258 "static ScmClass *thread_exception_cpa[] = {
259 SCM_CLASS_STATIC_PTR(Scm_ThreadExceptionClass),
260 SCM_CLASS_STATIC_PTR(Scm_ConditionClass),
261 SCM_CLASS_STATIC_PTR(Scm_TopClass),
262 NULL
263 };"
264
265 (define-cclass <thread-exception>
266 "ScmThreadException*" "Scm_ThreadExceptionClass"
267 ("Scm_ConditionClass")
268 ((thread :type <thread>))
269 (allocator (c "thread_exception_allocate"))
270 (printer (c "thread_exception_print")))
271
272 (define-cclass <join-timeout-exception>
273 "ScmThreadException*" "Scm_JoinTimeoutExceptionClass"
274 (c "thread_exception_cpa")
275 ()
276 (allocator (c "thread_exception_allocate"))
277 (printer (c "thread_exception_print"))
278 (unboxer "SCM_THREAD_EXCEPTION"))
279
280 (define-cclass <abandoned-mutex-exception>
281 "ScmThreadException*" "Scm_AbandonedMutexExceptionClass"
282 (c "thread_exception_cpa")
283 ((mutex :c-name "data"))
284 (allocator (c "thread_exception_allocate"))
285 (printer (c "thread_exception_print"))
286 (unboxer "SCM_THREAD_EXCEPTION"))
287
288 (define-cclass <terminated-thread-exception>
289 "ScmThreadException*" "Scm_TerminatedThreadExceptionClass"
290 (c "thread_exception_cpa")
291 ((terminator :c-name "data"))
292 (allocator (c "thread_exception_allocate"))
293 (printer (c "terminated_thread_print"))
294 (unboxer "SCM_THREAD_EXCEPTION"))
295
296 (define-cclass <uncaught-exception>
297 "ScmThreadException*" "Scm_UncaughtExceptionClass"
298 (c "thread_exception_cpa")
299 ((reason :c-name data))
300 (allocator (c "thread_exception_allocate"))
301 (printer (c "uncaught_exception_print"))
302 (unboxer "SCM_THREAD_EXCEPTION"))
303
304 (define-cclass <concurrent-modification-violation>
305 "ScmThreadException*" "Scm_ConcurrentModificationViolationClass"
306 (c "thread_exception_cpa")
307 ()
308 (allocator (c "thread_exception_allocate"))
309 (printer (c "uncaught_exception_print"))
310 (unboxer "SCM_THREAD_EXCEPTION"))
311 )
312
313 ;; SRFI-226
314 (define &thread <thread-exception>)
315 (define (make-thread-condition)
316 (make <thread-exception> :thread (current-thread)))
317 (define (thread-condition? obj) (is-a? obj <thread-exception>))
318
319 (define &uncaught-exception <uncaught-exception>)
320 (define (make-uncaught-exception-condition obj)
321 (make <uncaught-exception> :reason obj))
322 (define (uncaught-exception-condition? obj) (is-a? obj <uncaught-exception>))
323 (define (uncaught-exception-condition-reason obj)
324 (assume-type obj <uncaught-exception>)
325 (slot-ref obj 'reason))
326
327 (define &thread-already-terminated <terminated-thread-exception>)
328 (define (make-thread-already-terminated-condition)
329 (make <terminated-thread-exception>))
330 (define (thread-already-terminated-condition? obj)
331 (is-a? obj <terminated-thread-exception>))
332
333 (define &thread-timeout <join-timeout-exception>)
334 (define (make-thread-timeout-condition)
335 (make <join-timeout-exception>))
336 (define (thread-timeout-condition? obj)
337 (is-a? obj <join-timeout-exception>))
338
339 (define &thread-abandoned-mutex <abandoned-mutex-exception>)
340 (define (make-thread-abandoned-mutex-condition)
341 (make <abandoned-mutex-exception>))
342 (define (thread-abandoned-mutex-condition? obj)
343 (is-a? obj <abandoned-mutex-exception>))
344
345 (define &concurrent-modification <concurrent-modification-violation>)
346 (define (make-concurrent-modification-violation)
347 (make <concurrent-modification-violation>))
348 (define (concurrent-modification-violation? obj)
349 (is-a? obj <concurrent-modification-violation>))
350
351 ;;;
352 ;;; Mixin conditions
353 ;;;
354
355 ;; Mixin condition is compounded to a condition to augment context around
356 ;; the condition. See src/gauche/exception.h for the deails of these
357 ;; mixin conditions.
358
359 ;; TODO - set metaclass of those mixins to <condition-meta>
360
361 (select-module gauche)
362 (inline-stub
363 "static ScmClass *mixin_condition_cpa[] = {
364 SCM_CLASS_STATIC_PTR(Scm_MixinConditionClass),
365 SCM_CLASS_STATIC_PTR(Scm_ConditionClass),
366 SCM_CLASS_STATIC_PTR(Scm_TopClass),
367 NULL
368 };"
369
370 (define-cfn condition-continuation-mixin-allocate (klass::ScmClass* _) :static
371 (let* ([c::ScmConditionContinuationMixin* (SCM_NEW_INSTANCE ScmConditionContinuationMixin klass)])
372 (set! (-> c continuation) SCM_FALSE)
373 (return (SCM_OBJ c))))
374
375 (define-cclass <condition-continuation-mixin>
376 "ScmConditionContinuationMixin*" "Scm_CoditionContinuationMixinClass"
377 (c "mixin_condition_cpa")
378 ((continuation))
379 (allocator (c "condition_continuation_mixin_allocate")))
380
381 (define-cfn load-condition-mixin-allocate (klass::ScmClass* _) :static
382 (let* ([c::ScmLoadConditionMixin* (SCM_NEW_INSTANCE ScmLoadConditionMixin klass)])
383 (set! (-> c history) SCM_FALSE)
384 (set! (-> c port) SCM_FALSE)
385 (return (SCM_OBJ c))))
386
387 (define-cclass <load-condition-mixin>
388 "ScmLoadConditionMixin*" "Scm_LoadConditionMixinClass"
389 (c "mixin_condition_cpa")
390 ((history)
391 (port))
392 (allocator (c "load_condition_mixin_allocate")))
393
394 (define-cfn compile-error-mixin-allocate (klass::ScmClass* _) :static
395 (let* ([c::ScmCompileErrorMixin* (SCM_NEW_INSTANCE ScmCompileErrorMixin klass)])
396 (set! (-> c expr) SCM_FALSE)
397 (return (SCM_OBJ c))))
398
399 (define-cclass <compile-error-mixin>
400 "ScmCompileErrorMixin*" "Scm_CompileErrorMixinClass"
401 (c "mixin_condition_cpa")
402 ((expr))
403 (allocator (c "compile_error_mixin_allocate")))
404
405
406 ;; Filename errors are defined in SRFI-36. Internally most of those filename
407 ;; errors occur as <system-error> first; we compound the following conditions
408 ;; as needed. In C name we use "Mixin", but in Scheme we follow SRFI-36
409 ;; names and drop "-mixin".
410 ;; In C-level all filename mixin classes share one struct definition, and
411 ;; one allocator.
412 (define-cfn filename-error-mixin-allocate (klass::ScmClass* _) :static
413 (let* ([c::ScmFilenameErrorMixin* (SCM_NEW_INSTANCE ScmFilenameErrorMixin klass)])
414 (set! (-> c filename) SCM_FALSE)
415 (return (SCM_OBJ c))))
416
417 "static ScmClass *filename_condition_cpa[] = {
418 SCM_CLASS_STATIC_PTR(Scm_FileProtectionErrorMixinClass),
419 SCM_CLASS_STATIC_PTR(Scm_FilenameErrorMixinClass),
420 SCM_CLASS_STATIC_PTR(Scm_MixinConditionClass),
421 SCM_CLASS_STATIC_PTR(Scm_ConditionClass),
422 SCM_CLASS_STATIC_PTR(Scm_TopClass),
423 NULL
424 };"
425
426 (define-cclass <io-filename-error>
427 "ScmFilenameErrorMixin*" "Scm_FilenameErrorMixinClass"
428 (c "filename_condition_cpa+2")
429 ((filename))
430 (allocator (c "filename_error_mixin_allocate"))
431 (unboxer "SCM_FILENAME_ERROR_MIXIN"))
432
433 (define-cclass <io-malformed-filename-error>
434 "ScmFilenameErrorMixin*" "Scm_MalformedFilenameErrorClass"
435 (c "filename_condition_cpa+1")
436 ((filename))
437 (allocator (c "filename_error_mixin_allocate"))
438 (unboxer "SCM_FILENAME_ERROR_MIXIN"))
439
440 (define-cclass <io-file-protection-error>
441 "ScmFilenameErrorMixin*" "Scm_FileProtectionErrorMixinClass"
442 (c "filename_condition_cpa+1")
443 ((filename))
444 (allocator (c "filename_error_mixin_allocate"))
445 (unboxer "SCM_FILENAME_ERROR_MIXIN"))
446
447 (define-cclass <io-file-is-read-only-error>
448 "ScmFilenameErrorMixin*" "Scm_FileIsReadOnlyErrorMixinClass"
449 (c "filename_condition_cpa")
450 ((filename))
451 (allocator (c "filename_error_mixin_allocate"))
452 (unboxer "SCM_FILENAME_ERROR_MIXIN"))
453
454 (define-cclass <io-file-already-exists-error>
455 "ScmFilenameErrorMixin*" "Scm_FileAlreadyExistsErrorMixinClass"
456 (c "filename_condition_cpa+1")
457 ((filename))
458 (allocator (c "filename_error_mixin_allocate"))
459 (unboxer "SCM_FILENAME_ERROR_MIXIN"))
460
461 (define-cclass <io-no-such-file-error>
462 "ScmFilenameErrorMixin*" "Scm_NoSuchFileErrorMixinClass"
463 (c "filename_condition_cpa+1")
464 ((filename))
465 (allocator (c "filename_error_mixin_allocate"))
466 (unboxer "SCM_FILENAME_ERROR_MIXIN"))
467 )