1 ;;; Error handling in the REPL
3 ;; Copyright (C) 2001, 2009, 2010 Free Software Foundation, Inc.
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.
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.
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
22 (define-module (system repl error-handling)
23 #:use-module (system base pmatch)
24 #:use-module (system repl debug)
25 #:export (call-with-error-handling
32 ;;; Error handling via repl debugging
35 (define* (call-with-error-handling thunk #:key
36 (on-error 'debug) (post-error 'catch)
38 (let ((in (current-input-port))
39 (out (current-output-port))
40 (err (current-error-port)))
41 (define (with-saved-ports thunk)
42 (with-input-from-port in
44 (with-output-to-port out
46 (with-error-to-port err
50 (lambda () (%start-stack #t thunk))
55 (if (memq key pass-keys)
56 (apply throw key args)
59 ((,subr ,msg ,args . ,rest)
62 (run-hook before-error-hook)
63 (display-error #f err subr msg args rest)
64 (run-hook after-error-hook)
67 (format err "\nERROR: uncaught throw to `~a', args: ~a\n"
71 (if (procedure? post-error)
72 post-error ; a handler proc
73 (error "Unknown post-error strategy" post-error))))
78 (let ((stack (make-stack #t)))
82 ((,subr ,msg ,args . ,rest)
83 (format #t "Throw to key `~a':\n" key)
84 (display-error stack (current-output-port) subr msg args rest))
86 (format #t "Throw to key `~a' with args `~s'." key args)))
87 (format #t "Entering a new prompt. Type `,bt' for a backtrace")
88 (format #t " or `,q' to return to the old prompt.\n")
91 (let ((tag (and (pair? (fluid-ref %stacks))
92 (cdar (fluid-ref %stacks)))))
95 ;; Cut three frames from the top of the stack:
96 ;; make-stack, this one, and the throw handler.
98 ;; Narrow the end of the stack to the most recent
101 ;; And one more frame, because %start-stack invoking
102 ;; the start-stack thunk has its own frame too.
105 ((@ (system repl repl) start-repl) #:debug debug)))))))
108 ;; fall through to rethrow
111 (if (procedure? on-error)
112 on-error ; pre-unwind handler
113 (error "Unknown on-error strategy" on-error)))))))
115 (define-syntax with-error-handling
118 (call-with-error-handling (lambda () form)))))