Improve performance of R6RS records implementation
[bpt/guile.git] / module / rnrs / exceptions.scm
1 ;;; exceptions.scm --- The R6RS exceptions library
2
3 ;; Copyright (C) 2010 Free Software Foundation, Inc.
4 ;;
5 ;; This library is free software; you can redistribute it and/or
6 ;; modify it under the terms of the GNU Lesser General Public
7 ;; License as published by the Free Software Foundation; either
8 ;; version 3 of the License, or (at your option) any later version.
9 ;;
10 ;; This library is distributed in the hope that it will be useful,
11 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ;; Lesser General Public License for more details.
14 ;;
15 ;; You should have received a copy of the GNU Lesser General Public
16 ;; License along with this library; if not, write to the Free Software
17 ;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 \f
19
20 (library (rnrs exceptions (6))
21 (export guard with-exception-handler raise raise-continuable)
22 (import (rnrs base (6))
23 (rnrs conditions (6))
24 (rnrs records procedural (6))
25 (only (guile) with-throw-handler *unspecified* @@))
26
27 (define raise (@@ (rnrs records procedural) r6rs-raise))
28 (define raise-continuable
29 (@@ (rnrs records procedural) r6rs-raise-continuable))
30 (define raise-object-wrapper?
31 (@@ (rnrs records procedural) raise-object-wrapper?))
32 (define raise-object-wrapper-obj
33 (@@ (rnrs records procedural) raise-object-wrapper-obj))
34 (define raise-object-wrapper-continuation
35 (@@ (rnrs records procedural) raise-object-wrapper-continuation))
36
37 (define (with-exception-handler handler thunk)
38 (with-throw-handler 'r6rs:exception
39 thunk
40 (lambda (key . args)
41 (if (and (not (null? args))
42 (raise-object-wrapper? (car args)))
43 (let* ((cargs (car args))
44 (obj (raise-object-wrapper-obj cargs))
45 (continuation (raise-object-wrapper-continuation cargs))
46 (handler-return (handler obj)))
47 (if continuation
48 (continuation handler-return)
49 (raise (make-non-continuable-violation))))
50 *unspecified*))))
51
52 (define-syntax guard0
53 (syntax-rules ()
54 ((_ (variable cond-clause ...) . body)
55 (call/cc (lambda (continuation)
56 (with-exception-handler
57 (lambda (variable)
58 (continuation (cond cond-clause ...)))
59 (lambda () . body)))))))
60
61 (define-syntax guard
62 (syntax-rules (else)
63 ((_ (variable cond-clause ... . ((else else-clause ...))) . body)
64 (guard0 (variable cond-clause ... (else else-clause ...)) . body))
65 ((_ (variable cond-clause ...) . body)
66 (guard0 (variable cond-clause ... (else (raise variable))) . body))))
67 )