2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2007, 2010
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
8 @section Debugging Infrastructure
11 In order to understand Guile's debugging facilities, you first need to
12 understand a little about how Guile represent the Scheme control stack.
13 With that in place we explain the low level trap calls that the virtual
14 machine can be configured to make, and the trap and breakpoint
15 infrastructure that builds on top of those calls.
18 * Evaluation Model:: Evaluation and the Scheme stack.
19 * Programmatic Error Handling:: Debugging when an error occurs.
21 * Debugging Examples::
24 @node Evaluation Model
25 @subsection Evaluation and the Scheme Stack
27 The idea of the Scheme stack is central to a lot of debugging. The
28 Scheme stack is a reified representation of the pending function returns
29 in an expression's continuation. As Guile implements function calls
30 using a stack, this reification takes the form of a number of nested
31 stack frames, each of which corresponds to the application of a
32 procedure to a set of arguments.
34 A Scheme stack always exists implicitly, and can be summoned into
35 concrete existence as a first-class Scheme value by the
36 @code{make-stack} call, so that an introspective Scheme program -- such
37 as a debugger -- can present it in some way and allow the user to query
38 its details. The first thing to understand, therefore, is how Guile's
39 function call convention creates the stack.
41 Broadly speaking, Guile represents all control flow on a stack. Calling
42 a function involves pushing an empty frame on the stack, then evaluating
43 the procedure and its arguments, then fixing up the new frame so that it
44 points to the old one. Frames on the stack are thus linked together. A
45 tail call is the same, except it reuses the existing frame instead of
48 In this way, the only frames that are on the stack are ``active''
49 frames, frames which need to do some work before the computation is
50 complete. On the other hand, a function that has tail-called another
51 function will not be on the stack, as it has no work left to do.
53 Therefore, when an error occurs in a running program, or the program
54 hits a breakpoint, or in fact at any point that the programmer chooses,
55 its state at that point can be represented by a @dfn{stack} of all the
56 procedure applications that are logically in progress at that time, each
57 of which is known as a @dfn{frame}. The programmer can learn more about
58 the program's state at that point by inspecting the stack and its
62 * Capturing the Stack or Innermost Stack Frame::
63 * Examining the Stack::
64 * Examining Stack Frames::
65 * Source Properties:: Remembering the source of an expression.
66 * Starting a New Stack::
69 @node Capturing the Stack or Innermost Stack Frame
70 @subsubsection Capturing the Stack or Innermost Stack Frame
72 A Scheme program can use the @code{make-stack} primitive anywhere in its
73 code, with first arg @code{#t}, to construct a Scheme value that
74 describes the Scheme stack at that point.
82 @deffn {Scheme Procedure} make-stack obj . args
83 @deffnx {C Function} scm_make_stack (obj, args)
84 Create a new stack. If @var{obj} is @code{#t}, the current
85 evaluation stack is used for creating the stack frames,
86 otherwise the frames are taken from @var{obj} (which must be
87 a continuation or a frame object).
89 @var{args} should be a list containing any combination of
90 integer, procedure, prompt tag and @code{#t} values.
92 These values specify various ways of cutting away uninteresting
93 stack frames from the top and bottom of the stack that
94 @code{make-stack} returns. They come in pairs like this:
95 @code{(@var{inner_cut_1} @var{outer_cut_1} @var{inner_cut_2}
96 @var{outer_cut_2} @dots{})}.
98 Each @var{inner_cut_N} can be @code{#t}, an integer, a prompt
99 tag, or a procedure. @code{#t} means to cut away all frames up
100 to but excluding the first user module frame. An integer means
101 to cut away exactly that number of frames. A prompt tag means
102 to cut away all frames that are inside a prompt with the given
103 tag. A procedure means to cut away all frames up to but
104 excluding the application frame whose procedure matches the
107 Each @var{outer_cut_N} can be an integer, a prompt tag, or a
108 procedure. An integer means to cut away that number of frames.
109 A prompt tag means to cut away all frames that are outside a
110 prompt with the given tag. A procedure means to cut away
111 frames down to but excluding the application frame whose
112 procedure matches the specified one.
114 If the @var{outer_cut_N} of the last pair is missing, it is
119 @node Examining the Stack
120 @subsubsection Examining the Stack
122 @deffn {Scheme Procedure} stack? obj
123 @deffnx {C Function} scm_stack_p (obj)
124 Return @code{#t} if @var{obj} is a calling stack.
127 @deffn {Scheme Procedure} stack-id stack
128 @deffnx {C Function} scm_stack_id (stack)
129 Return the identifier given to @var{stack} by @code{start-stack}.
132 @deffn {Scheme Procedure} stack-length stack
133 @deffnx {C Function} scm_stack_length (stack)
134 Return the length of @var{stack}.
137 @deffn {Scheme Procedure} stack-ref stack index
138 @deffnx {C Function} scm_stack_ref (stack, index)
139 Return the @var{index}'th frame from @var{stack}.
142 @deffn {Scheme Procedure} display-backtrace stack port [first [depth [highlights]]]
143 @deffnx {C Function} scm_display_backtrace_with_highlights (stack, port, first, depth, highlights)
144 @deffnx {C Function} scm_display_backtrace (stack, port, first, depth)
145 Display a backtrace to the output port @var{port}. @var{stack}
146 is the stack to take the backtrace from, @var{first} specifies
147 where in the stack to start and @var{depth} how many frames
148 to display. @var{first} and @var{depth} can be @code{#f},
149 which means that default values will be used.
150 If @var{highlights} is given it should be a list; the elements
151 of this list will be highlighted wherever they appear in the
156 @node Examining Stack Frames
157 @subsubsection Examining Stack Frames
159 @deffn {Scheme Procedure} frame? obj
160 @deffnx {C Function} scm_frame_p (obj)
161 Return @code{#t} if @var{obj} is a stack frame.
164 @deffn {Scheme Procedure} frame-previous frame
165 @deffnx {C Function} scm_frame_previous (frame)
166 Return the previous frame of @var{frame}, or @code{#f} if
167 @var{frame} is the first frame in its stack.
170 @deffn {Scheme Procedure} frame-procedure frame
171 @deffnx {C Function} scm_frame_procedure (frame)
172 Return the procedure for @var{frame}, or @code{#f} if no
173 procedure is associated with @var{frame}.
176 @deffn {Scheme Procedure} frame-arguments frame
177 @deffnx {C Function} scm_frame_arguments (frame)
178 Return the arguments of @var{frame}.
181 @deffn {Scheme Procedure} display-application frame [port [indent]]
182 @deffnx {C Function} scm_display_application (frame, port, indent)
183 Display a procedure application @var{frame} to the output port
184 @var{port}. @var{indent} specifies the indentation of the
189 @node Source Properties
190 @subsubsection Source Properties
192 @cindex source properties
193 As Guile reads in Scheme code from file or from standard input, it
194 remembers the file name, line number and column number where each
195 expression begins. These pieces of information are known as the
196 @dfn{source properties} of the expression. Syntax expanders and the
197 compiler propagate these source properties to compiled procedures, so
198 that, if an error occurs when evaluating the transformed expression,
199 Guile's debugger can point back to the file and location where the
200 expression originated.
202 The way that source properties are stored means that Guile can only
203 associate source properties with parenthesized expressions, and not, for
204 example, with individual symbols, numbers or strings. The difference
205 can be seen by typing @code{(xxx)} and @code{xxx} at the Guile prompt
206 (where the variable @code{xxx} has not been defined):
209 scheme@@(guile-user)> (xxx)
210 <unnamed port>:4:1: In procedure module-lookup:
211 <unnamed port>:4:1: Unbound variable: xxx
213 scheme@@(guile-user)> xxx
214 ERROR: In procedure module-lookup:
215 ERROR: Unbound variable: xxx
219 In the latter case, no source properties were stored, so the error
220 doesn't have any source information.
222 The recording of source properties is controlled by the read option
223 named ``positions'' (@pxref{Scheme Read}). This option is switched
224 @emph{on} by default.
226 The following procedures can be used to access and set the source
227 properties of read expressions.
229 @deffn {Scheme Procedure} set-source-properties! obj alist
230 @deffnx {C Function} scm_set_source_properties_x (obj, alist)
231 Install the association list @var{alist} as the source property
235 @deffn {Scheme Procedure} set-source-property! obj key datum
236 @deffnx {C Function} scm_set_source_property_x (obj, key, datum)
237 Set the source property of object @var{obj}, which is specified by
238 @var{key} to @var{datum}. Normally, the key will be a symbol.
241 @deffn {Scheme Procedure} source-properties obj
242 @deffnx {C Function} scm_source_properties (obj)
243 Return the source property association list of @var{obj}.
246 @deffn {Scheme Procedure} source-property obj key
247 @deffnx {C Function} scm_source_property (obj, key)
248 Return the property specified by @var{key} from @var{obj}'s source
252 If the @code{positions} reader option is enabled, each parenthesized
253 expression will have values set for the @code{filename}, @code{line} and
254 @code{column} properties.
256 If you're stuck with defmacros (@pxref{Defmacros}), and want to preserve
257 source information, the following helper function might be useful to
260 @deffn {Scheme Procedure} cons-source xorig x y
261 @deffnx {C Function} scm_cons_source (xorig, x, y)
262 Create and return a new pair whose car and cdr are @var{x} and @var{y}.
263 Any source properties associated with @var{xorig} are also associated
268 @node Starting a New Stack
269 @subsubsection Starting a New Stack
271 @deffn {Scheme Syntax} start-stack id exp
272 Evaluate @var{exp} on a new calling stack with identity @var{id}. If
273 @var{exp} is interrupted during evaluation, backtraces will not display
274 frames farther back than @var{exp}'s top-level form. This macro is a
275 way of artificially limiting backtraces and stack procedures, largely as
276 a convenience to the user.
280 @node Programmatic Error Handling
281 @subsection Programmatic Error Handling
283 For better or for worse, all programs have bugs, and dealing with bugs
284 is part of programming. This section deals with that class of bugs that
285 causes an exception to be raised -- from your own code, from within a
286 library, or from Guile itself.
289 * Catching Exceptions:: Handling errors after the stack is unwound.
290 * Capturing Stacks:: Capturing the stack at the time of error.
291 * Pre-Unwind Debugging:: Debugging before the exception is thrown.
292 * Debug Options:: A historical interface to debugging.
295 @node Catching Exceptions
296 @subsubsection Catching Exceptions
298 A common requirement is to be able to show as much useful context as
299 possible when a Scheme program hits an error. The most immediate
300 information about an error is the kind of error that it is -- such as
301 ``division by zero'' -- and any parameters that the code which signalled
302 the error chose explicitly to provide. This information originates with
303 the @code{error} or @code{throw} call (or their C code equivalents, if
304 the error is detected by C code) that signals the error, and is passed
305 automatically to the handler procedure of the innermost applicable
306 @code{catch} or @code{with-throw-handler} expression.
308 Therefore, to catch errors that occur within a chunk of Scheme code, and
309 to intercept basic information about those errors, you need to execute
310 that code inside the dynamic context of a @code{catch} or
311 @code{with-throw-handler} expression, or the equivalent in C. In Scheme,
312 this means you need something like this:
317 ;; Execute the code in which
318 ;; you want to catch errors here.
320 (lambda (key . parameters)
321 ;; Put the code which you want
322 ;; to handle an error here.
327 The @code{catch} here can also be @code{with-throw-handler}; see
328 @ref{Throw Handlers} for information on the when you might want to use
329 @code{with-throw-handler} instead of @code{catch}.
331 For example, to print out a message and return #f when an error occurs,
335 (define (catch-all thunk)
338 (lambda (key . parameters)
339 (format (current-error-port)
340 "Uncaught throw to '~a: ~a\n" key parameters)
344 (lambda () (error "Not a vegetable: tomato")))
345 =| Uncaught throw to 'misc-error: (#f ~A (Not a vegetable: tomato) #f)
349 The @code{#t} means that the catch is applicable to all kinds of error.
350 If you want to restrict your catch to just one kind of error, you can
351 put the symbol for that kind of error instead of @code{#t}. The
352 equivalent to this in C would be something like this:
355 SCM my_body_proc (void *body_data)
357 /* Execute the code in which
358 you want to catch errors here. */
362 SCM my_handler_proc (void *handler_data,
366 /* Put the code which you want
367 to handle an error here. */
373 scm_c_catch (SCM_BOOL_T,
374 my_body_proc, body_data,
375 my_handler_proc, handler_data,
382 Again, as with the Scheme version, @code{scm_c_catch} could be replaced
383 by @code{scm_c_with_throw_handler}, and @code{SCM_BOOL_T} could instead
384 be the symbol for a particular kind of error.
386 @node Capturing Stacks
387 @subsubsection Capturing the full error stack
389 The other interesting information about an error is the full Scheme
390 stack at the point where the error occurred; in other words what
391 innermost expression was being evaluated, what was the expression that
392 called that one, and so on. If you want to write your code so that it
393 captures and can display this information as well, there are a couple
394 important things to understand.
396 Firstly, the stack at the point of the error needs to be explicitly
397 captured by a @code{make-stack} call (or the C equivalent
398 @code{scm_make_stack}). The Guile library does not do this
399 ``automatically'' for you, so you will need to write code with a
400 @code{make-stack} or @code{scm_make_stack} call yourself. (We emphasise
401 this point because some people are misled by the fact that the Guile
402 interactive REPL code @emph{does} capture and display the stack
403 automatically. But the Guile interactive REPL is itself a Scheme
404 program@footnote{In effect, it is the default program which is run when
405 no commands or script file are specified on the Guile command line.}
406 running on top of the Guile library, and which uses @code{catch} and
407 @code{make-stack} in the way we are about to describe to capture the
408 stack when an error occurs.)
410 And secondly, in order to capture the stack effectively at the point
411 where the error occurred, the @code{make-stack} call must be made before
412 Guile unwinds the stack back to the location of the prevailing catch
413 expression. This means that the @code{make-stack} call must be made
414 within the handler of a @code{with-throw-handler} expression, or the
415 optional "pre-unwind" handler of a @code{catch}. (For the full story of
416 how these alternatives differ from each other, see @ref{Exceptions}. The
417 main difference is that @code{catch} terminates the error, whereas
418 @code{with-throw-handler} only intercepts it temporarily and then allow
419 it to continue propagating up to the next innermost handler.)
421 So, here are some examples of how to do all this in Scheme and in C.
422 For the purpose of these examples we assume that the captured stack
423 should be stored in a variable, so that it can be displayed or
424 arbitrarily processed later on. In Scheme:
427 (let ((captured-stack #f))
430 ;; Execute the code in which
431 ;; you want to catch errors here.
433 (lambda (key . parameters)
434 ;; Put the code which you want
435 ;; to handle an error after the
436 ;; stack has been unwound here.
438 (lambda (key . parameters)
439 ;; Capture the stack here:
440 (set! captured-stack (make-stack #t))))
444 ;; Display or process the captured stack.
453 SCM my_body_proc (void *body_data)
455 /* Execute the code in which
456 you want to catch errors here. */
460 SCM my_handler_proc (void *handler_data,
464 /* Put the code which you want
465 to handle an error after the
466 stack has been unwound here. */
470 SCM my_preunwind_proc (void *handler_data,
474 /* Capture the stack here: */
475 *(SCM *)handler_data = scm_make_stack (SCM_BOOL_T, SCM_EOL);
479 SCM captured_stack = SCM_BOOL_F;
481 scm_c_catch (SCM_BOOL_T,
482 my_body_proc, body_data,
483 my_handler_proc, handler_data,
484 my_preunwind_proc, &captured_stack);
486 if (captured_stack != SCM_BOOL_F)
488 /* Display or process the captured stack. */
495 Once you have a captured stack, you can interrogate and display its
496 details in any way that you want, using the @code{stack-@dots{}} and
497 @code{frame-@dots{}} API described in @ref{Examining the Stack} and
498 @ref{Examining Stack Frames}.
500 If you want to print out a backtrace in the same format that the Guile
501 REPL does, you can use the @code{display-backtrace} procedure to do so.
502 You can also use @code{display-application} to display an individual
503 frame in the Guile REPL format.
505 @node Pre-Unwind Debugging
506 @subsubsection Pre-Unwind Debugging
508 Instead of saving a stack away and waiting for the @code{catch} to
509 return, you can handle errors directly, from within the pre-unwind
512 For example, to show a backtrace when an error is thrown, you might want
513 to use a procedure like this:
516 (define (with-backtrace thunk)
517 (with-throw-handler #t
519 (lambda args (backtrace))))
520 (with-backtrace (lambda () (error "Not a vegetable: tomato")))
523 Since we used @code{with-throw-handler} here, we didn't actually catch
524 the error. @xref{Throw Handlers}, for more information. However, we did
525 print out a context at the time of the error, using the built-in
526 procedure, @code{backtrace}.
528 @deffn {Scheme Procedure} backtrace [highlights]
529 @deffnx {C Function} scm_backtrace_with_highlights (highlights)
530 @deffnx {C Function} scm_backtrace ()
531 Display a backtrace of the current stack to the current output port. If
532 @var{highlights} is given it should be a list; the elements of this list
533 will be highlighted wherever they appear in the backtrace.
536 The Guile REPL code (in @file{system/repl/repl.scm} and related files)
537 uses a @code{catch} with a pre-unwind handler to capture the stack when
538 an error occurs in an expression that was typed into the REPL, and debug
539 that stack interactively in the context of the error.
541 These procedures are available for use by user programs, in the
542 @code{(system repl error-handling)} module.
545 (use-modules (system repl error-handling))
548 @deffn {Scheme Procedure} call-with-error-handling thunk @
549 [#:on-error on-error='debug] [#:post-error post-error='catch] @
550 [#:pass-keys pass-keys='(quit)] [#:trap-handler trap-handler='debug]
551 Call a thunk in a context in which errors are handled.
553 There are four keyword arguments:
557 Specifies what to do before the stack is unwound.
559 Valid options are @code{debug} (the default), which will enter a
560 debugger; @code{pass}, in which case nothing is done, and the exception
561 is rethrown; or a procedure, which will be the pre-unwind handler.
564 Specifies what to do after the stack is unwound.
566 Valid options are @code{catch} (the default), which will silently catch
567 errors, returning the unspecified value; @code{report}, which prints out
568 a description of the error (via @code{display-error}), and then returns
569 the unspecified value; or a procedure, which will be the catch handler.
572 Specifies a trap handler: what to do when a breakpoint is hit.
574 Valid options are @code{debug}, which will enter the debugger;
575 @code{pass}, which does nothing; or @code{disabled}, which disables
576 traps entirely. @xref{Traps}, for more information.
579 A set of keys to ignore, as a list.
584 @subsubsection Debug options
586 The behavior when an error is the @code{backtrace} procedure and of the
587 default error handler can be parameterized via the debug options.
589 @cindex options - debug
590 @cindex debug options
591 @deffn {Scheme Procedure} debug-options [setting]
592 Display the current settings of the debug options. If @var{setting} is
593 omitted, only a short form of the current read options is printed.
594 Otherwise if @var{setting} is the symbol @code{help}, a complete options
595 description is displayed.
598 The set of available options, and their default values, may be had by
599 invoking @code{debug-options} at the prompt.
602 scheme@@(guile-user)>
603 backwards no Display backtrace in anti-chronological order.
604 width 79 Maximal width of backtrace.
605 depth 20 Maximal length of printed backtrace.
606 backtrace yes Show backtrace on error.
607 stack 1048576 Stack size limit (measured in words;
609 show-file-name #t Show file names and line numbers in backtraces
610 when not `#f'. A value of `base' displays only
611 base names, while `#t' displays full names.
612 warn-deprecated no Warn when deprecated features are used.
615 The boolean options may be toggled with @code{debug-enable} and
616 @code{debug-disable}. The non-boolean @code{keywords} option must be set
617 using @code{debug-set!}.
619 @deffn {Scheme Procedure} debug-enable option-name
620 @deffnx {Scheme Procedure} debug-disable option-name
621 @deffnx {Scheme Procedure} debug-set! option-name value
622 Modify the debug options. @code{debug-enable} should be used with boolean
623 options and switches them on, @code{debug-disable} switches them off.
624 @code{debug-set!} can be used to set an option to a specific value.
627 @subsubheading Stack overflow
629 @cindex overflow, stack
630 @cindex stack overflow
631 Stack overflow errors are caused by a computation trying to use more
632 stack space than has been enabled by the @code{stack} option. They are
636 (non-tail-recursive-factorial 500)
638 ERROR: Stack overflow
639 ABORT: (stack-overflow)
642 If you get an error like this, you can either try rewriting your code to
643 use less stack space, or increase the maximum stack size. To increase
644 the maximum stack size, use @code{debug-set!}, for example:
647 (debug-set! stack 200000)
649 (show-file-name #t stack 200000 debug backtrace depth 20
650 maxdepth 1000 frames 3 indent 10 width 79 procnames cheap)
652 (non-tail-recursive-factorial 500)
654 122013682599111006870123878542304692625357434@dots{}
657 If you prefer to try rewriting your code, you may be able to save stack
658 space by making some of your procedures @dfn{tail recursive}
659 (@pxref{Tail Calls}).
666 @cindex Evaluator trap calls
670 @cindex Code coverage
672 Guile's virtual machine can be configured to call out at key points to
673 arbitrary user-specified procedures. For more information on these
674 hooks, and the circumstances under which the VM calls them, see @ref{VM
677 In principle, these hooks allow Scheme code to implement any model it
678 chooses for examining the evaluation stack as program execution
679 proceeds, and for suspending execution to be resumed later. Possible
680 applications of this feature include breakpoints, runtime tracing, code
681 coverage, and profiling.
685 Based on these low level trap calls, Guile provides a higher level,
686 object-oriented interface for the manipulation of traps. Different
687 kinds of trap are represented as GOOPS classes; for example, the
688 @code{<procedure-trap>} class describes traps that are triggered by
689 invocation of a specified procedure. A particular instance of a trap
690 class --- or @dfn{trap object} --- describes the condition under which
691 a single trap will be triggered, and what will happen then; for
692 example, an instance of @code{<procedure-trap>} whose @code{procedure}
693 and @code{behaviour} slots contain @code{my-factorial} and
694 @code{debug-trap} would be a trap that enters the command line
695 debugger when the @code{my-factorial} procedure is invoked.
697 The following subsections describe all this in detail, for both the
698 user wanting to use traps, and the developer interested in
699 understanding how the interface hangs together.
702 @subsubsection Actually, this section is bitrotten
704 Dear reader: the following sections have some great ideas, and some code
705 that just needs a few days of massaging to get it to work with the VM
706 (as opposed to the old interpreter). Want to help? Yes? Yes!
707 @code{guile-devel@@gnu.org}, that's where.
710 @subsubsection A Quick Note on Terminology
712 @cindex Trap terminology
713 It feels natural to use the word ``trap'' in some form for all levels
714 of the structure just described, so we need to be clear on the
715 terminology we use to describe each particular level. The terminology
716 used in this subsection is as follows.
720 @cindex Evaluator trap calls
721 @cindex Low level trap calls
722 ``Low level trap calls'', or ``low level traps'', are the calls made
723 directly from the C code of the Guile evaluator.
727 ``Trap classes'' are self-explanatory.
731 ``Trap objects'', ``trap instances'', or just ``traps'', are instances
732 of a trap class, and each describe a single logical trap condition
733 plus behaviour as specified by the user of this interface.
736 A good example of when it is important to be clear, is when we talk
737 below of behaviours that should only happen once per low level trap.
738 A single low level trap call will typically map onto the processing of
739 several trap objects, so ``once per low level trap'' is significantly
740 different from ``once per trap''.
744 * How to Set a Trap::
745 * Specifying Trap Behaviour::
748 * Tracing Configuration::
749 * Tracing and (ice-9 debug)::
750 * Traps Installing More Traps::
751 * Common Trap Options::
764 @node How to Set a Trap
765 @subsubsection How to Set a Trap
767 @cindex Setting traps
768 @cindex Installing and uninstalling traps
769 Setting a trap is done in two parts. First the trap is defined by
770 creating an instance of the appropriate trap class, with slot values
771 specifying the condition under which the trap will fire and the action
772 to take when it fires. Secondly the trap object thus created must be
775 To make this immediately concrete, here is an example that sets a trap
776 to fire on the next application of the @code{facti} procedure, and to
777 handle the trap by entering the command line debugger.
780 (install-trap (make <procedure-trap>
783 #:behaviour debug-trap))
787 Briefly, the elements of this incantation are as follows. (All of
788 these are described more fully in the following subsubsections.)
792 @code{<procedure-trap>} is the trap class for trapping on invocation
793 of a specific procedure.
796 @code{#:procedure facti} says that the specific procedure to trap on for this
797 trap object is @code{facti}.
800 @code{#:single-shot #t} says that this trap should only fire on the
801 @emph{next} invocation of @code{facti}, not on all future invocations
802 (which is the default if the @code{#:single-shot} option is not
806 @code{#:behaviour debug-trap} says that the trap infrastructure should
807 call the procedure @code{debug-trap} when this trap fires.
810 Finally, the @code{install-trap} call installs the trap immediately.
814 It is of course possible for the user to define more convenient
815 shorthands for setting common kinds of traps. @xref{Trap Shorthands},
818 The ability to install, uninstall and reinstall a trap without losing
819 its definition is Guile's equivalent of the disable/enable commands
820 provided by debuggers like GDB.
822 @deffn {Generic Function} install-trap trap
823 Install the trap object @var{trap}, so that its behaviour will be
824 executed when the conditions for the trap firing are met.
827 @deffn {Generic Function} uninstall-trap trap
828 Uninstall the trap object @var{trap}, so that its behaviour will
829 @emph{not} be executed even if the conditions for the trap firing are
834 @node Specifying Trap Behaviour
835 @subsubsection Specifying Trap Behaviour
837 @cindex Trap behaviour
838 Guile provides several ``out-of-the-box'' behaviours for common needs.
839 All of the following can be used directly as the value of the
840 @code{#:behaviour} option when creating a trap object.
842 @deffn {Procedure} debug-trap trap-context
843 Enter Guile's command line debugger to explore the stack at
844 @var{trap-context}, and to single-step or continue program execution
848 @deffn {Procedure} gds-debug-trap trap-context
849 Use the GDS debugging interface, which displays the stack and
850 corresponding source code via Emacs, to explore the stack at
851 @var{trap-context} and to single-step or continue program execution
857 @deffn {Procedure} trace-trap trap-context
858 Display trace information to summarize the current @var{trap-context}.
861 @deffn {Procedure} trace-at-exit trap-context
862 Install a further trap to cause the return value of the application or
863 evaluation just starting (as described by @var{trap-context}) to be
864 traced using @code{trace-trap}, when this application or evaluation
865 completes. The extra trap is automatically uninstalled after the
866 return value has been traced.
869 @deffn {Procedure} trace-until-exit trap-context
870 Install a further trap so that every step that the evaluator performs
871 as part of the application or evaluation just starting (as described
872 by @var{trap-context}) is traced using @code{trace-trap}. The extra
873 trap is automatically uninstalled when the application or evaluation
874 is complete. @code{trace-until-exit} can be very useful as a first
875 step when all you know is that there is a bug ``somewhere in XXX or in
876 something that XXX calls''.
880 @code{debug-trap} and @code{gds-debug-trap} are provided by the modules
881 @code{(ice-9 debugger)} and @code{(ice-9 gds-client)} respectively, and
882 their behaviours are fairly self-explanatory. For more information on
883 the operation of the GDS interface via Emacs, see @ref{Using Guile in
884 Emacs}. The tracing behaviours are explained more fully below.
887 More generally, the @dfn{behaviour} specified for a trap can be any
888 procedure that expects to be called with one @dfn{trap context}
889 argument. A trivial example would be:
892 (define (report-stack-depth trap-context)
893 (display "Stack depth at the trap is: ")
894 (display (tc:depth trap-context))
900 @subsubsection Trap Context
902 The @dfn{trap context} is an object that caches information about the
903 low level trap call and the stack at the point of the trap, and is
904 passed as the only argument to all behaviour procedures. The
905 information in the trap context can be accessed through the procedures
906 beginning @code{tc:} that are exported by the @code{(ice-9 debugging
907 traps)} module@footnote{Plus of course any procedures that build on
908 these, such as the @code{trace/@dots{}} procedures exported by
909 @code{(ice-9 debugging trace)} (@pxref{Tracing Configuration}).}; the
910 most useful of these are as follows.
912 @deffn {Generic Function} tc:type trap-context
913 Indicates the type of the low level trap by returning one of the
914 keywords @code{#:application}, @code{#:evaluation}, @code{#:return} or
918 @deffn {Generic Function} tc:return-value trap-context
919 When @code{tc:type} gives @code{#:return}, this provides the value
920 that is being returned.
923 @deffn {Generic Function} tc:stack trap-context
924 Provides the stack at the point of the trap (as computed by
925 @code{make-stack}, but cached so that the lengthy @code{make-stack}
926 operation is not performed more than once for the same low level
930 @deffn {Generic Function} tc:frame trap-context
931 The innermost frame of the stack at the point of the trap.
934 @deffn {Generic Function} tc:depth trap-context
935 The number of frames (including tail recursive non-real frames) in the
936 stack at the point of the trap.
939 @deffn {Generic Function} tc:real-depth trap-context
940 The number of real frames (that is, excluding the non-real frames that
941 describe tail recursive calls) in the stack at the point of the trap.
945 @node Tracing Examples
946 @subsubsection Tracing Examples
948 The following examples show what tracing is and the kind of output that
949 it generates. In the first example, we define a recursive function for
950 reversing a list, then watch the effect of the recursive calls by
951 tracing each call and return value.
954 guile> (define (rev ls)
957 (append (rev (cdr ls))
959 guile> (use-modules (ice-9 debugging traps) (ice-9 debugging trace))
960 guile> (define t1 (make <procedure-trap>
962 #:behaviour (list trace-trap
964 guile> (install-trap t1)
965 guile> (rev '(a b c))
978 The number before the colon in this output (which follows @code{(ice-9
979 debugging trace)}'s default output format) is the number of real frames
980 on the stack. The fact that this number increases for each recursive
981 call confirms that the implementation above of @code{rev} is not
984 In the next example, we probe the @emph{internal} workings of
985 @code{rev} in more detail by using the @code{trace-until-exit}
989 guile> (uninstall-trap t1)
990 guile> (define t2 (make <procedure-trap>
992 #:behaviour (list trace-trap
994 guile> (install-trap t2)
997 | 2: (if (null? ls) ls (append (rev (cdr ls)) (list (car ls))))
1001 | 2: (append (rev (cdr ls)) (list (car ls)))
1007 | 3: (if (null? ls) ls (append (rev (cdr ls)) (list (car ls))))
1011 | 3: (append (rev (cdr ls)) (list (car ls)))
1017 | 4: (if (null? ls) ls (append (rev (cdr ls)) (list (car ls))))
1021 | 4: (list (car ls))
1027 | 3: [append () (b)]
1029 | 3: (list (car ls))
1035 | 2: [append (b) (a)]
1041 The output in this case shows every step that the evaluator performs
1042 in evaluating @code{(rev '(a b))}.
1045 @node Tracing Configuration
1046 @subsubsection Tracing Configuration
1048 The detail of what gets printed in each trace line, and the port to
1049 which tracing is written, can be configured by the procedures
1050 @code{set-trace-layout} and @code{trace-port}, both exported by the
1051 @code{(ice-9 debugging trace)} module.
1053 @deffn {Procedure with Setter} trace-port
1054 Get or set the port to which tracing is printed. The default is the
1055 value of @code{(current-output-port)} when the @code{(ice-9 debugging
1056 trace)} module is first loaded.
1059 @deffn {Procedure} set-trace-layout format-string . arg-procs
1060 Layout each trace line using @var{format-string} and @var{arg-procs}.
1061 For each trace line, the list of values to be printed is obtained by
1062 calling all the @var{arg-procs}, passing the trap context as the only
1063 parameter to each one. This list of values is then formatted using
1064 the specified @var{format-string}.
1068 The @code{(ice-9 debugging trace)} module exports a set of arg-proc
1069 procedures to cover most common needs, with names beginning
1070 @code{trace/}. These are all implemented on top of the @code{tc:} trap
1071 context accessor procedures documented in @ref{Trap Context}, and if any
1072 trace output not provided by the following is needed, it should be
1073 possible to implement based on a combination of the @code{tc:}
1076 @deffn {Procedure} trace/pid trap-context
1077 An arg-proc that returns the current process ID.
1080 @deffn {Procedure} trace/stack-id trap-context
1081 An arg-proc that returns the stack ID of the stack in which the
1082 current trap occurred.
1085 @deffn {Procedure} trace/stack-depth trap-context
1086 An arg-proc that returns the length (including non-real frames) of the
1087 stack at the point of the current trap.
1090 @deffn {Procedure} trace/stack-real-depth trap-context
1091 An arg-proc that returns the length excluding non-real frames of the
1092 stack at the point of the current trap.
1095 @deffn {Procedure} trace/stack trap-context
1096 An arg-proc that returns a string summarizing stack information. This
1097 string includes the stack ID, real depth, and count of additional
1098 non-real frames, with the format @code{"~a:~a+~a"}.
1101 @deffn {Procedure} trace/source-file-name trap-context
1102 An arg-proc that returns the name of the source file for the innermost
1103 stack frame, or an empty string if source is not available for the
1107 @deffn {Procedure} trace/source-line trap-context
1108 An arg-proc that returns the line number of the source code for the
1109 innermost stack frame, or zero if source is not available for the
1113 @deffn {Procedure} trace/source-column trap-context
1114 An arg-proc that returns the column number of the start of the source
1115 code for the innermost stack frame, or zero if source is not available
1116 for the innermost frame.
1119 @deffn {Procedure} trace/source trap-context
1120 An arg-proc that returns the source location for the innermost stack
1121 frame. This is a string composed of file name, line and column number
1122 with the format @code{"~a:~a:~a"}, or an empty string if source is not
1123 available for the innermost frame.
1126 @deffn {Procedure} trace/type trap-context
1127 An arg-proc that returns a three letter abbreviation indicating the
1128 type of the current trap: @code{"APP"} for an application frame,
1129 @code{"EVA"} for an evaluation, @code{"RET"} for an exit trap, or
1130 @code{"ERR"} for an error (pseudo-)trap.
1133 @deffn {Procedure} trace/real? trap-context
1134 An arg-proc that returns @code{" "} if the innermost stack frame is a
1135 real frame, or @code{"t"} if it is not.
1138 @deffn {Procedure} trace/info trap-context
1139 An arg-proc that returns a string describing the expression being
1140 evaluated, application being performed, or return value, according to
1141 the current trap type.
1145 @code{trace/stack-depth} and @code{trace/stack-real-depth} are identical
1146 to the trap context methods @code{tc:depth} and @code{tc:real-depth}
1147 described before (@pxref{Trap Context}), but renamed here for
1150 The default trace layout, as exhibited by the examples of the previous
1151 subsubsubsection, is set by this line of code from the @code{(ice-9 debugging
1155 (set-trace-layout "|~3@@a: ~a\n" trace/stack-real-depth trace/info)
1159 If we rerun the first of those examples, but with trace layout
1160 configured to show source location and trap type in addition, the
1161 output looks like this:
1164 guile> (set-trace-layout "| ~25a ~3@@a: ~a ~a\n"
1166 trace/stack-real-depth
1169 guile> (rev '(a b c))
1170 | standard input:29:0 2: APP [rev (a b c)]
1171 | standard input:4:21 3: APP [rev (b c)]
1172 | standard input:4:21 4: APP [rev (c)]
1173 | standard input:4:21 5: APP [rev ()]
1174 | standard input:2:9 5: RET =>()
1175 | standard input:4:13 4: RET =>(c)
1176 | standard input:4:13 3: RET =>(c b)
1177 | standard input:4:13 2: RET =>(c b a)
1182 @node Tracing and (ice-9 debug)
1183 @subsubsection Tracing and (ice-9 debug)
1185 The @code{(ice-9 debug)} module provides a tracing facility
1186 (@pxref{Tracing}) that is roughly similar to that described here, but
1187 there are important differences.
1191 The @code{(ice-9 debug)} trace gives a nice pictorial view of changes
1192 in stack depth, by using indentation like this:
1207 However its output can @emph{only} show the information seen here,
1208 which corresponds to @code{(ice-9 debugging trace)}'s
1209 @code{trace/info} procedure; it cannot be configured to show other
1210 pieces of information about the trap context in the way that the
1211 @code{(ice-9 debugging trace)} implementation can.
1214 The @code{(ice-9 debug)} trace only allows the tracing of procedure
1215 applications and their return values, whereas the @code{(ice-9 debugging
1216 trace)} implementation allows any kind of trap to be traced.
1218 It's interesting to note that @code{(ice-9 debug)}'s restriction here,
1219 which might initially appear to be just a straightforward consequence
1220 of its implementation, is also somewhat dictated by its pictorial
1221 display. The use of indentation in the output relies on hooking into
1222 the low level trap calls in such a way that the trapped application
1223 entries and exits exactly balance each other. The @code{ice-9
1224 debugging trace} implementation allows traps to be installed such that
1225 entry and exit traps don't necessarily balance, which means that, in
1226 general, indentation diagrams like the one above don't work.
1229 It isn't currently possible to use both @code{(ice-9 debug)} trace and
1230 @code{(ice-9 debugging trace)} in the same Guile session, because
1231 their settings of the low level trap options conflict with each other.
1234 @node Traps Installing More Traps
1235 @subsubsection Traps Installing More Traps
1237 Sometimes it is desirable for the behaviour at one trap to install
1238 further traps. In other words, the behaviour is something like
1239 ``Don't do much right now, but set things up to stop after two or
1240 three more steps'', or ``@dots{} when this frame completes''. This is
1241 absolutely fine. For example, it is easy to code a generic ``do
1242 so-and-so when the current frame exits'' procedure, which can be used
1243 wherever a trap context is available, as follows.
1246 (define (at-exit trap-context behaviour)
1247 (install-trap (make <exit-trap>
1248 #:depth (tc:depth trap-context)
1250 #:behaviour behaviour)))
1253 To continue and pin down the example, this could then be used as part
1254 of a behaviour whose purpose was to measure the accumulated time spent
1255 in and below a specified procedure.
1261 (define accumulate-time
1262 (lambda (trap-context)
1263 (set! calls (+ calls 1))
1264 (let ((entry (current-time)))
1265 (at-exit trap-context
1268 (+ total (- (current-time)
1271 (install-trap (make <procedure-trap>
1273 #:behaviour accumulate-time))
1277 @node Common Trap Options
1278 @subsubsection Common Trap Options
1280 When creating any kind of trap object, settings for the trap being
1281 created are specified as options on the @code{make} call using syntax
1285 (make <@var{trap-class}>
1286 #:@var{option-keyword} @var{setting}
1290 The following common options are provided by the base class
1291 @code{<trap>}, and so can be specified for any kind of trap.
1293 @deffn {Class} <trap>
1294 Base class for trap objects.
1297 @deffn {Trap Option} #:condition thunk
1298 If not @code{#f}, this is a thunk which is called when the trap fires,
1299 to determine whether trap processing should proceed any further. If
1300 the thunk returns @code{#f}, the trap is basically suppressed.
1301 Otherwise processing continues normally. (Default value @code{#f}.)
1304 @deffn {Trap Option} #:skip-count count
1305 A count of valid (after @code{#:condition} processing) firings of this
1306 trap to skip. (Default value 0.)
1309 @deffn {Trap Option} #:single-shot boolean
1310 If not @code{#f}, this indicates that the trap should be automatically
1311 uninstalled after it has successfully fired (after @code{#:condition}
1312 and @code{#:skip-count} processing) for the first time. (Default
1316 @deffn {Trap Option} #:behaviour behaviour-proc
1317 A trap behaviour procedure --- as discussed in the preceding subsubsection
1318 --- or a list of such procedures, in which case each procedure is
1319 called in turn when the trap fires. (Default value @code{'()}.)
1322 @deffn {Trap Option} #:repeat-identical-behaviour boolean
1323 Normally, if multiple trap objects are triggered by the same low level
1324 trap, and they request the same behaviour, it's only actually useful
1325 to do that behaviour once (per low level trap); so by default multiple
1326 requests for the same behaviour are coalesced. If this option is set
1327 other than @code{#f}, the contents of the @code{#:behaviour} option
1328 are uniquified so that they avoid being coalesced in this way.
1329 (Default value @code{#f}.)
1333 @node Procedure Traps
1334 @subsubsection Procedure Traps
1336 The @code{<procedure-trap>} class implements traps that are triggered
1337 upon application of a specified procedure. Instances of this class
1338 should use the @code{#:procedure} option to specify the procedure to
1341 @deffn {Class} <procedure-trap>
1342 Class for traps triggered by application of a specified procedure.
1345 @deffn {Trap Option} #:procedure procedure
1346 Specifies the procedure to trap on.
1353 (install-trap (make <procedure-trap>
1355 #:behaviour (list trace-trap
1361 @subsubsection Exit Traps
1363 The @code{<exit-trap>} class implements traps that are triggered upon
1364 stack frame exit past a specified stack depth. Instances of this
1365 class should use the @code{#:depth} option to specify the target stack
1368 @deffn {Class} <exit-trap>
1369 Class for traps triggered by exit past a specified stack depth.
1372 @deffn {Trap Option} #:depth depth
1373 Specifies the reference depth for the trap.
1380 (define (trace-at-exit trap-context)
1381 (install-trap (make <exit-trap>
1382 #:depth (tc:depth trap-context)
1384 #:behaviour trace-trap)))
1388 (This is the actual definition of the @code{trace-at-exit} behaviour.)
1392 @subsubsection Entry Traps
1394 The @code{<entry-trap>} class implements traps that are triggered upon
1395 any stack frame entry. No further parameters are needed to specify an
1396 instance of this class, so there are no class-specific trap options.
1397 Note that it remains possible to use the common trap options
1398 (@pxref{Common Trap Options}), for example to set a trap for the
1399 @var{n}th next frame entry.
1401 @deffn {Class} <entry-trap>
1402 Class for traps triggered by any stack frame entry.
1409 (install-trap (make <entry-trap>
1411 #:behaviour gds-debug-trap))
1416 @subsubsection Apply Traps
1418 The @code{<apply-trap>} class implements traps that are triggered upon
1419 any procedure application. No further parameters are needed to
1420 specify an instance of this class, so there are no class-specific trap
1421 options. Note that it remains possible to use the common trap options
1422 (@pxref{Common Trap Options}), for example to set a trap for the next
1423 application where some condition is true.
1425 @deffn {Class} <apply-trap>
1426 Class for traps triggered by any procedure application.
1433 (install-trap (make <apply-trap>
1434 #:condition my-condition
1435 #:behaviour gds-debug-trap))
1440 @subsubsection Step Traps
1442 The @code{<step-trap>} class implements traps that do single-stepping
1443 through a program's execution. They come in two flavours, with and
1444 without a specified file name. If a file name is specified, the trap
1445 is triggered by the next evaluation, application or frame exit
1446 pertaining to source code from the specified file. If a file name is
1447 not specified, the trap is triggered by the next evaluation,
1448 application or frame exit from any file (or for code whose source
1449 location was not recorded), in other words by the next evaluator step
1452 The design goal of the @code{<step-trap>} class is to match what a
1453 user would intuitively think of as single-stepping through their code,
1454 either through code in general (roughly corresponding to GDB's
1455 @code{step} command, for example), or through code from a particular
1456 source file (roughly corresponding to GDB's @code{next}). Therefore
1457 if you are using a step trap to single-step through code and finding
1458 its behaviour counter-intuitive, please report that so we can improve
1461 The implementation and options of the @code{<step-trap>} class are
1462 complicated by the fact that it is unreliable to determine whether a
1463 low level frame exit trap is applicable to a specified file by
1464 examining the details of the reported frame. This is a consequence of
1465 tail recursion, which has the effect that many frames can be removed
1466 from the stack at once, with only the outermost frame being reported
1467 by the low level trap call. The effects of this on the
1468 @code{<step-trap>} class are such as to require the introduction of
1469 the strange-looking @code{#:exit-depth} option, for the following
1474 When stopped at the start of an application or evaluation frame, and
1475 it is desired to continue execution until the next ``step'' in the same
1476 source file, that next step could be the start of a nested application
1477 or evaluation frame, or --- if the procedure definition is in a
1478 different file, for example --- it could be the exit from the current
1482 Because of the effects of tail recursion noted above, the current
1483 frame exit possibility must be expressed as frame exit past a
1484 specified stack depth. When an instance of the @code{<step-trap>}
1485 class is installed from the context of an application or evaluation
1486 frame entry, the @code{#:exit-depth} option should be used to specify
1490 When stopped at a frame exit, on the other hand, we know that the next
1491 step must be an application or evaluation frame entry. In this
1492 context the @code{#:exit-depth} option is not needed and should be
1493 omitted or set to @code{#f}.
1497 When a step trap is installed without @code{#:single-shot #t}, such
1498 that it keeps firing, the @code{<step-trap>} code automatically
1499 updates its idea of the @code{#:exit-depth} setting each time, so that
1500 the trap always fires correctly for the following step.
1502 @deffn {Class} <step-trap>
1503 Class for single-stepping traps.
1506 @deffn {Trap Option} #:file-name name
1507 If not @code{#f}, this is a string containing the name of a source
1508 file, and restricts the step trap to evaluation steps within that
1509 source file. (Default value @code{#f}.)
1512 @deffn {Trap Option} #:exit-depth depth
1513 If not @code{#f}, this is a positive integer implying that the next
1514 step may be frame exit past the stack depth @var{depth}. See the
1515 discussion above for more details. (Default value @code{#f}.)
1522 (install-trap (make <step-trap>
1523 #:file-name (frame-file-name
1524 (stack-ref stack index))
1525 #:exit-depth (- (stack-length stack)
1526 (stack-ref stack index))
1528 #:behaviour debug-trap))
1533 @subsubsection Source Traps
1535 The @code{<source-trap>} class implements traps that are attached to a
1536 precise source code expression, as read by the reader, and which fire
1537 each time that that expression is evaluated. These traps use a low
1538 level Guile feature which can mark individual expressions for
1539 trapping, and are relatively efficient. But it can be tricky to get
1540 at the source expression in the first place, and these traps are
1541 liable to become irrelevant if the procedure containing the expression
1542 is reevaluated; these issues are discussed further below.
1544 @deffn {Class} <source-trap>
1545 Class for traps triggered by evaluation of a specific Scheme
1549 @deffn {Trap Option} #:expression expr
1550 Specifies the Scheme expression to trap on.
1557 (display "Enter an expression: ")
1559 (install-trap (make <source-trap>
1561 #:behaviour (list trace-trap
1565 Enter an expression: (+ 1 2 3 4 5 6)
1566 | 3: (+ 1 2 3 4 5 6)
1571 The key point here is that the expression specified by the
1572 @code{#:expression} option must be @emph{exactly} (i.e. @code{eq?} to)
1573 what is going to be evaluated later. It doesn't work, for example, to
1574 say @code{#:expression '(+ x 3)}, with the expectation that the trap
1575 will fire whenever evaluating any expression @code{(+ x 3)}.
1577 The @code{trap-here} macro can be used in source code to create and
1578 install a source trap correctly. Take for example the factorial
1579 function defined in the @code{(ice-9 debugging example-fns)} module:
1585 (* n (fact1 (- n 1)))))
1589 To set a source trap on a particular expression --- let's say the
1590 expression @code{(= n 0)} --- edit the code so that the expression is
1591 enclosed in a @code{trap-here} macro call like this:
1595 (if (trap-here (= n 0) #:behaviour debug-trap)
1597 (* n (fact1 (- n 1)))))
1600 @deffn {Macro} trap-here expression . trap-options
1601 Install a source trap with options @var{trap-options} on
1602 @var{expression}, then return with the whole call transformed to
1603 @code{(begin @var{expression})}.
1606 Note that if the @code{trap-here} incantation is removed, and
1607 @code{fact1} then redefined by reloading its source file, the effect
1608 of the source trap is lost, because the text ``(= n 0)'' is read again
1609 from scratch and becomes a new expression @code{(= n 0)} which does
1610 not have the ``trap here'' mark on it.
1612 If the semantics and setting of source traps seem unwieldy, location
1613 traps may meet your need more closely; these are described in the
1614 following subsubsection.
1617 @node Location Traps
1618 @subsubsection Location Traps
1620 The @code{<location-trap>} class implements traps that are triggered
1621 by evaluation of code at a specific source location. When compared
1622 with source traps, they are easier to set, and do not become
1623 irrelevant when the relevant code is reloaded; but unfortunately they
1624 are a lot less efficient, as they require running some ``are we in the
1625 right place for a trap'' code on every low level frame entry trap
1628 @deffn {Class} <location-trap>
1629 Class for traps triggered by evaluation of code at a specific source
1633 @deffn {Trap Option} #:file-regexp regexp
1634 A regular expression specifying the filenames that will match this
1635 trap. This option must be specified when creating a location trap.
1638 @deffn {Trap Option} #:line line
1639 The line number (0-based) of the source location at which the trap
1640 should be triggered. This option must be specified when creating a
1644 @deffn {Trap Option} #:column column
1645 The column number (0-based) of the source location at which the trap
1646 should be triggered. This option must be specified when creating a
1651 Here is an example, which matches the @code{(facti (- n 1) (* a n))}
1652 expression in @file{ice-9/debugging/example-fns.scm}:
1655 (install-trap (make <location-trap>
1656 #:file-regexp "example-fns.scm"
1659 #:behaviour gds-debug-trap))
1663 @node Trap Shorthands
1664 @subsubsection Trap Shorthands
1666 If the code described in the preceding subsubsections for creating and
1667 manipulating traps seems a little long-winded, it is of course
1668 possible to define more convenient shorthand forms for typical usage
1669 patterns. Here are some examples.
1672 (define (break! proc)
1673 (install-trap (make <procedure-trap>
1675 #:behaviour gds-debug-trap)))
1677 (define (trace! proc)
1678 (install-trap (make <procedure-trap>
1680 #:behaviour (list trace-trap
1683 (define (trace-subtree! proc)
1684 (install-trap (make <procedure-trap>
1686 #:behaviour (list trace-trap
1687 trace-until-exit))))
1690 Definitions like these are not provided out-of-the-box by Guile,
1691 because different users will have different ideas about what their
1692 default debugger should be, or, for example, which of the common trap
1693 options (@pxref{Common Trap Options}) it might be useful to expose
1694 through such shorthand procedures.
1697 @node Trap Utilities
1698 @subsubsection Trap Utilities
1700 @code{list-traps} can be used to print a description of all known trap
1701 objects. This uses a weak value hash table, keyed by a trap index
1702 number. Each trap object has its index number assigned, and is added
1703 to the hash table, when it is created by a @code{make @var{trap-class}
1704 @dots{}} call. When a trap object is GC'd, it is automatically
1705 removed from the hash table, and so no longer appears in the output
1706 from @code{list-traps}.
1708 @deffn {Variable} all-traps
1709 Weak value hash table containing all known trap objects.
1712 @deffn {Procedure} list-traps
1713 Print a description of all known trap objects.
1716 The following example shows a single trap that traces applications of
1717 the procedure @code{facti}.
1721 #<<procedure-trap> 100d2e30> is an instance of class <procedure-trap>
1728 behaviour = (#<procedure trace-trap (trap-context)>)
1729 repeat-identical-behaviour = #f
1730 procedure = #<procedure facti (n a)>
1733 When @code{all-traps} or @code{list-traps} reveals a trap that you
1734 want to modify but no longer have a reference to, you can retrieve the
1735 trap object by calling @code{get-trap} with the trap's number. For
1736 example, here's how you could change the behaviour of the trap listed
1740 (slot-set! (get-trap 1) 'behaviour (list debug-trap))
1743 @deffn {Procedure} get-trap number
1744 Return the trap object with the specified @var{number}, or @code{#f}
1749 @node Debugging Examples
1750 @subsection Debugging Examples
1752 Here we present some examples of what you can do with the debugging
1753 facilities just described.
1756 * Single Stepping through a Procedure's Code::
1757 * Profiling or Tracing a Procedure's Code::
1761 @node Single Stepping through a Procedure's Code
1762 @subsubsection Single Stepping through a Procedure's Code
1764 A good way to explore in detail what a Scheme procedure does is to set
1765 a trap on it and then single step through what it does. To do this,
1766 make and install a @code{<procedure-trap>} with the @code{debug-trap}
1767 behaviour from @code{(ice-9 debugger)}.
1769 The following sample session illustrates this. It assumes that the
1770 file @file{matrix.scm} defines a procedure @code{mkmatrix}, which is
1771 the one we want to explore, and another procedure @code{do-main} which
1772 calls @code{mkmatrix}.
1776 guile> (use-modules (ice-9 debugger)
1777 (ice-9 debugging traps))
1778 guile> (load "matrix.scm")
1779 guile> (install-trap (make <procedure-trap>
1780 #:procedure mkmatrix
1781 #:behaviour debug-trap))
1783 This is the Guile debugger -- for help, type `help'.
1784 There are 3 frames on the stack.
1786 Frame 2 at matrix.scm:8:3
1789 Frame 3 at matrix.scm:4:3
1790 (let ((x 1)) (quote hi!))
1793 This frame is an evaluation.
1794 The expression being evaluated is:
1796 (let ((x 1)) (quote hi!))
1798 Frame 3 at matrix.scm:5:21
1802 ?: 0* [primitive-eval (do-main 4)]
1814 Or you can use Guile's Emacs interface (GDS), by using the module
1815 @code{(ice-9 gds-client)} instead of @code{(ice-9 debugger)} and
1816 changing @code{debug-trap} to @code{gds-debug-trap}. Then the stack and
1817 corresponding source locations are displayed in Emacs instead of on the
1821 @node Profiling or Tracing a Procedure's Code
1822 @subsubsection Profiling or Tracing a Procedure's Code
1824 What if you wanted to get a trace of everything that the Guile
1825 evaluator does within a given procedure, but without Guile stopping
1826 and waiting for your input at every step? For this requirement you
1827 can install a trap on the procedure, as in the previous example, but
1828 instead of @code{debug-trap} or @code{gds-debug-trap}, use the
1829 @code{trace-trap} and @code{trace-until-exit} behaviours provided by
1830 the @code{(ice-9 debugging trace)} module.
1833 guile> (use-modules (ice-9 debugging traps) (ice-9 debugging trace))
1834 guile> (load "matrix.scm")
1835 guile> (install-trap (make <procedure-trap>
1836 #:procedure mkmatrix
1837 #:behaviour (list trace-trap trace-until-exit)))
1840 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> define #f]
1841 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> define #f]
1842 | 4: (and (memq sym bindings) (let ...))
1843 | 5: (memq sym bindings)
1844 | 5: [memq define (debug)]
1846 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> define #f]
1847 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> define #f]
1848 | 4: (and (memq sym bindings) (let ...))
1849 | 5: (memq sym bindings)
1850 | 5: [memq define (debug)]
1852 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1853 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1854 | 4: (and (memq sym bindings) (let ...))
1855 | 5: (memq sym bindings)
1856 | 5: [memq let (debug)]
1858 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1859 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1860 | 4: (and (memq sym bindings) (let ...))
1861 | 5: (memq sym bindings)
1862 | 5: [memq let (debug)]
1864 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1865 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1866 | 4: (and (memq sym bindings) (let ...))
1867 | 5: (memq sym bindings)
1868 | 5: [memq let (debug)]
1870 | 2: (letrec ((yy 23)) (let ((x 1)) (quote hi!)))
1871 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1872 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1873 | 4: (and (memq sym bindings) (let ...))
1874 | 5: (memq sym bindings)
1875 | 5: [memq let (debug)]
1877 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1878 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1879 | 4: (and (memq sym bindings) (let ...))
1880 | 5: (memq sym bindings)
1881 | 5: [memq let (debug)]
1883 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1884 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1885 | 4: (and (memq sym bindings) (let ...))
1886 | 5: (memq sym bindings)
1887 | 5: [memq let (debug)]
1889 | 2: (let ((x 1)) (quote hi!))
1890 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1891 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1892 | 4: (and (memq sym bindings) (let ...))
1893 | 5: (memq sym bindings)
1894 | 5: [memq let (debug)]
1896 | 2: [let (let # #) (# # #)]
1897 | 2: [let (let # #) (# # #)]
1898 | 2: =>(#@@let* (x 1) #@@let (quote hi!))
1902 | 2: (letrec ((yy 23)) (let* ((x 1)) (quote hi!)))
1903 | 2: (let* ((x 1)) (quote hi!))
1910 This example shows the default configuration for how each line of trace
1911 output is formatted, which is:
1915 the character @code{|}, a visual clue that the line is a line of trace
1919 a number indicating the real evaluator stack depth (where ``real'' means
1920 not counting tail-calls), followed by
1923 a summary of the expression being evaluated (@code{(@dots{})}), the
1924 procedure being called (@code{[@dots{}]}), or the value being returned
1925 from an evaluation or procedure call (@code{=>@dots{}}).
1929 You can customize @code{(ice-9 debugging trace)} to show different
1930 information in each trace line using the @code{set-trace-layout}
1931 procedure. The next example shows how to get the source location in
1932 each trace line instead of the stack depth.
1935 guile> (set-trace-layout "|~16@@a: ~a\n" trace/source trace/info)
1937 | matrix.scm:7:2: [mkmatrix]
1938 | : (letrec ((yy 23)) (let* ((x 1)) (quote hi!)))
1939 | matrix.scm:3:2: (let* ((x 1)) (quote hi!))
1940 | matrix.scm:4:4: (quote hi!)
1941 | matrix.scm:4:4: =>hi!
1947 @c TeX-master: "guile.texi"