82efd74cc44065fda4f4ff7440c4e0970de692f0
[bpt/guile.git] / doc / ref / api-debug.texi
1 @c -*-texinfo-*-
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.
6
7 @node Debugging
8 @section Debugging Infrastructure
9
10 @cindex Debugging
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.
16
17 @menu
18 * Evaluation Model:: Evaluation and the Scheme stack.
19 * Programmatic Error Handling:: Debugging when an error occurs.
20 * Traps::
21 * Debugging Examples::
22 @end menu
23
24 @node Evaluation Model
25 @subsection Evaluation and the Scheme Stack
26
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.
33
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.
40
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
46 pushing on a new one.
47
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.
52
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
59 frames.
60
61 @menu
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::
67 @end menu
68
69 @node Capturing the Stack or Innermost Stack Frame
70 @subsubsection Capturing the Stack or Innermost Stack Frame
71
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.
75
76 @lisp
77 (make-stack #t)
78 @result{}
79 #<stack 25205a0>
80 @end lisp
81
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).
88
89 @var{args} should be a list containing any combination of
90 integer, procedure, prompt tag and @code{#t} values.
91
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{})}.
97
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
105 specified one.
106
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.
113
114 If the @var{outer_cut_N} of the last pair is missing, it is
115 taken as 0.
116 @end deffn
117
118
119 @node Examining the Stack
120 @subsubsection Examining the Stack
121
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.
125 @end deffn
126
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}.
130 @end deffn
131
132 @deffn {Scheme Procedure} stack-length stack
133 @deffnx {C Function} scm_stack_length (stack)
134 Return the length of @var{stack}.
135 @end deffn
136
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}.
140 @end deffn
141
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
152 backtrace.
153 @end deffn
154
155
156 @node Examining Stack Frames
157 @subsubsection Examining Stack Frames
158
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.
162 @end deffn
163
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.
168 @end deffn
169
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}.
174 @end deffn
175
176 @deffn {Scheme Procedure} frame-arguments frame
177 @deffnx {C Function} scm_frame_arguments (frame)
178 Return the arguments of @var{frame}.
179 @end deffn
180
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
185 output.
186 @end deffn
187
188
189 @node Source Properties
190 @subsubsection Source Properties
191
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.
201
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):
207
208 @example
209 scheme@@(guile-user)> (xxx)
210 <unnamed port>:4:1: In procedure module-lookup:
211 <unnamed port>:4:1: Unbound variable: xxx
212
213 scheme@@(guile-user)> xxx
214 ERROR: In procedure module-lookup:
215 ERROR: Unbound variable: xxx
216 @end example
217
218 @noindent
219 In the latter case, no source properties were stored, so the error
220 doesn't have any source information.
221
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.
225
226 The following procedures can be used to access and set the source
227 properties of read expressions.
228
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
232 list for @var{obj}.
233 @end deffn
234
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.
239 @end deffn
240
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}.
244 @end deffn
245
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
249 properties.
250 @end deffn
251
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.
255
256 If you're stuck with defmacros (@pxref{Defmacros}), and want to preserve
257 source information, the following helper function might be useful to
258 you:
259
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
264 with the new pair.
265 @end deffn
266
267
268 @node Starting a New Stack
269 @subsubsection Starting a New Stack
270
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.
277 @end deffn
278
279
280 @node Programmatic Error Handling
281 @subsection Programmatic Error Handling
282
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.
287
288 @menu
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.
293 @end menu
294
295 @node Catching Exceptions
296 @subsubsection Catching Exceptions
297
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.
307
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:
313
314 @lisp
315 (catch #t
316 (lambda ()
317 ;; Execute the code in which
318 ;; you want to catch errors here.
319 ...)
320 (lambda (key . parameters)
321 ;; Put the code which you want
322 ;; to handle an error here.
323 ...))
324 @end lisp
325
326 @noindent
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}.
330
331 For example, to print out a message and return #f when an error occurs,
332 you might use:
333
334 @smalllisp
335 (define (catch-all thunk)
336 (catch #t
337 thunk
338 (lambda (key . parameters)
339 (format (current-error-port)
340 "Uncaught throw to '~a: ~a\n" key parameters)
341 #f)))
342
343 (catch-all
344 (lambda () (error "Not a vegetable: tomato")))
345 =| Uncaught throw to 'misc-error: (#f ~A (Not a vegetable: tomato) #f)
346 @result{} #f
347 @end smalllisp
348
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:
353
354 @lisp
355 SCM my_body_proc (void *body_data)
356 @{
357 /* Execute the code in which
358 you want to catch errors here. */
359 ...
360 @}
361
362 SCM my_handler_proc (void *handler_data,
363 SCM key,
364 SCM parameters)
365 @{
366 /* Put the code which you want
367 to handle an error here. */
368 ...
369 @}
370
371 @{
372 ...
373 scm_c_catch (SCM_BOOL_T,
374 my_body_proc, body_data,
375 my_handler_proc, handler_data,
376 NULL, NULL);
377 ...
378 @}
379 @end lisp
380
381 @noindent
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.
385
386 @node Capturing Stacks
387 @subsubsection Capturing the full error stack
388
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.
395
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.)
409
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.)
420
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:
425
426 @lisp
427 (let ((captured-stack #f))
428 (catch #t
429 (lambda ()
430 ;; Execute the code in which
431 ;; you want to catch errors here.
432 ...)
433 (lambda (key . parameters)
434 ;; Put the code which you want
435 ;; to handle an error after the
436 ;; stack has been unwound here.
437 ...)
438 (lambda (key . parameters)
439 ;; Capture the stack here:
440 (set! captured-stack (make-stack #t))))
441 ...
442 (if captured-stack
443 (begin
444 ;; Display or process the captured stack.
445 ...))
446 ...)
447 @end lisp
448
449 @noindent
450 And in C:
451
452 @lisp
453 SCM my_body_proc (void *body_data)
454 @{
455 /* Execute the code in which
456 you want to catch errors here. */
457 ...
458 @}
459
460 SCM my_handler_proc (void *handler_data,
461 SCM key,
462 SCM parameters)
463 @{
464 /* Put the code which you want
465 to handle an error after the
466 stack has been unwound here. */
467 ...
468 @}
469
470 SCM my_preunwind_proc (void *handler_data,
471 SCM key,
472 SCM parameters)
473 @{
474 /* Capture the stack here: */
475 *(SCM *)handler_data = scm_make_stack (SCM_BOOL_T, SCM_EOL);
476 @}
477
478 @{
479 SCM captured_stack = SCM_BOOL_F;
480 ...
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);
485 ...
486 if (captured_stack != SCM_BOOL_F)
487 @{
488 /* Display or process the captured stack. */
489 ...
490 @}
491 ...
492 @}
493 @end lisp
494
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}.
499
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.
504
505 @node Pre-Unwind Debugging
506 @subsubsection Pre-Unwind Debugging
507
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
510 handler.
511
512 For example, to show a backtrace when an error is thrown, you might want
513 to use a procedure like this:
514
515 @lisp
516 (define (with-backtrace thunk)
517 (with-throw-handler #t
518 thunk
519 (lambda args (backtrace))))
520 (with-backtrace (lambda () (error "Not a vegetable: tomato")))
521 @end lisp
522
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}.
527
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.
534 @end deffn
535
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.
540
541 These procedures are available for use by user programs, in the
542 @code{(system repl error-handling)} module.
543
544 @lisp
545 (use-modules (system repl error-handling))
546 @end lisp
547
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.
552
553 There are four keyword arguments:
554
555 @table @var
556 @item on-error
557 Specifies what to do before the stack is unwound.
558
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.
562
563 @item post-error
564 Specifies what to do after the stack is unwound.
565
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.
570
571 @item trap-handler
572 Specifies a trap handler: what to do when a breakpoint is hit.
573
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.
577
578 @item pass-keys
579 A set of keys to ignore, as a list.
580 @end table
581 @end deffn
582
583 @node Debug Options
584 @subsubsection Debug options
585
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.
588
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.
596 @end deffn
597
598 The set of available options, and their default values, may be had by
599 invoking @code{debug-options} at the prompt.
600
601 @smallexample
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;
608 0 = no check).
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.
613 @end smallexample
614
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!}.
618
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.
625 @end deffn
626
627 @subsubheading Stack overflow
628
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
633 reported like this:
634
635 @lisp
636 (non-tail-recursive-factorial 500)
637 @print{}
638 ERROR: Stack overflow
639 ABORT: (stack-overflow)
640 @end lisp
641
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:
645
646 @lisp
647 (debug-set! stack 200000)
648 @result{}
649 (show-file-name #t stack 200000 debug backtrace depth 20
650 maxdepth 1000 frames 3 indent 10 width 79 procnames cheap)
651
652 (non-tail-recursive-factorial 500)
653 @result{}
654 122013682599111006870123878542304692625357434@dots{}
655 @end lisp
656
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}).
660
661
662 @node Traps
663 @subsection Traps
664
665 @cindex Traps
666 @cindex Evaluator trap calls
667 @cindex Breakpoints
668 @cindex Trace
669 @cindex Tracing
670 @cindex Code coverage
671 @cindex Profiling
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
675 Behaviour}.
676
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.
682
683 @cindex Trap classes
684 @cindex Trap objects
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.
696
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.
700
701
702 @subsubsection Actually, this section is bitrotten
703
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.
708
709
710 @subsubsection A Quick Note on Terminology
711
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.
717
718 @itemize @bullet
719 @item
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.
724
725 @item
726 @cindex Trap classes
727 ``Trap classes'' are self-explanatory.
728
729 @item
730 @cindex Trap objects
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.
734 @end itemize
735
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''.
741
742
743 @menu
744 * How to Set a Trap::
745 * Specifying Trap Behaviour::
746 * Trap Context::
747 * Tracing Examples::
748 * Tracing Configuration::
749 * Tracing and (ice-9 debug)::
750 * Traps Installing More Traps::
751 * Common Trap Options::
752 * Procedure Traps::
753 * Exit Traps::
754 * Entry Traps::
755 * Apply Traps::
756 * Step Traps::
757 * Source Traps::
758 * Location Traps::
759 * Trap Shorthands::
760 * Trap Utilities::
761 @end menu
762
763
764 @node How to Set a Trap
765 @subsubsection How to Set a Trap
766
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
773 @dfn{installed}.
774
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.
778
779 @lisp
780 (install-trap (make <procedure-trap>
781 #:procedure facti
782 #:single-shot #t
783 #:behaviour debug-trap))
784 @end lisp
785
786 @noindent
787 Briefly, the elements of this incantation are as follows. (All of
788 these are described more fully in the following subsubsections.)
789
790 @itemize @bullet
791 @item
792 @code{<procedure-trap>} is the trap class for trapping on invocation
793 of a specific procedure.
794
795 @item
796 @code{#:procedure facti} says that the specific procedure to trap on for this
797 trap object is @code{facti}.
798
799 @item
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
803 specified).
804
805 @item
806 @code{#:behaviour debug-trap} says that the trap infrastructure should
807 call the procedure @code{debug-trap} when this trap fires.
808
809 @item
810 Finally, the @code{install-trap} call installs the trap immediately.
811 @end itemize
812
813 @noindent
814 It is of course possible for the user to define more convenient
815 shorthands for setting common kinds of traps. @xref{Trap Shorthands},
816 for some examples.
817
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.
821
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.
825 @end deffn
826
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
830 met.
831 @end deffn
832
833
834 @node Specifying Trap Behaviour
835 @subsubsection Specifying Trap Behaviour
836
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.
841
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
845 from that point.
846 @end deffn
847
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
852 from that point.
853 @end deffn
854
855 @cindex Trace
856 @cindex Tracing
857 @deffn {Procedure} trace-trap trap-context
858 Display trace information to summarize the current @var{trap-context}.
859 @end deffn
860
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.
867 @end deffn
868
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''.
877 @end deffn
878
879 @noindent
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.
885
886 @cindex Trap context
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:
890
891 @lisp
892 (define (report-stack-depth trap-context)
893 (display "Stack depth at the trap is: ")
894 (display (tc:depth trap-context))
895 (newline))
896 @end lisp
897
898
899 @node Trap Context
900 @subsubsection Trap Context
901
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.
911
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
915 @code{#:error}.
916 @end deffn
917
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.
921 @end deffn
922
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
927 trap).
928 @end deffn
929
930 @deffn {Generic Function} tc:frame trap-context
931 The innermost frame of the stack at the point of the trap.
932 @end deffn
933
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.
937 @end deffn
938
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.
942 @end deffn
943
944
945 @node Tracing Examples
946 @subsubsection Tracing Examples
947
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.
952
953 @lisp
954 guile> (define (rev ls)
955 (if (null? ls)
956 ls
957 (append (rev (cdr ls))
958 (list (car ls)))))
959 guile> (use-modules (ice-9 debugging traps) (ice-9 debugging trace))
960 guile> (define t1 (make <procedure-trap>
961 #:procedure rev
962 #:behaviour (list trace-trap
963 trace-at-exit)))
964 guile> (install-trap t1)
965 guile> (rev '(a b c))
966 | 2: [rev (a b c)]
967 | 3: [rev (b c)]
968 | 4: [rev (c)]
969 | 5: [rev ()]
970 | 5: =>()
971 | 4: =>(c)
972 | 3: =>(c b)
973 | 2: =>(c b a)
974 (c b a)
975 @end lisp
976
977 @noindent
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
982 tail-recursive.
983
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}
986 behaviour.
987
988 @lisp
989 guile> (uninstall-trap t1)
990 guile> (define t2 (make <procedure-trap>
991 #:procedure rev
992 #:behaviour (list trace-trap
993 trace-until-exit)))
994 guile> (install-trap t2)
995 guile> (rev '(a b))
996 | 2: [rev (a b)]
997 | 2: (if (null? ls) ls (append (rev (cdr ls)) (list (car ls))))
998 | 3: (null? ls)
999 | 3: [null? (a b)]
1000 | 3: =>#f
1001 | 2: (append (rev (cdr ls)) (list (car ls)))
1002 | 3: (rev (cdr ls))
1003 | 4: (cdr ls)
1004 | 4: [cdr (a b)]
1005 | 4: =>(b)
1006 | 3: [rev (b)]
1007 | 3: (if (null? ls) ls (append (rev (cdr ls)) (list (car ls))))
1008 | 4: (null? ls)
1009 | 4: [null? (b)]
1010 | 4: =>#f
1011 | 3: (append (rev (cdr ls)) (list (car ls)))
1012 | 4: (rev (cdr ls))
1013 | 5: (cdr ls)
1014 | 5: [cdr (b)]
1015 | 5: =>()
1016 | 4: [rev ()]
1017 | 4: (if (null? ls) ls (append (rev (cdr ls)) (list (car ls))))
1018 | 5: (null? ls)
1019 | 5: [null? ()]
1020 | 5: =>#t
1021 | 4: (list (car ls))
1022 | 5: (car ls)
1023 | 5: [car (b)]
1024 | 5: =>b
1025 | 4: [list b]
1026 | 4: =>(b)
1027 | 3: [append () (b)]
1028 | 3: =>(b)
1029 | 3: (list (car ls))
1030 | 4: (car ls)
1031 | 4: [car (a b)]
1032 | 4: =>a
1033 | 3: [list a]
1034 | 3: =>(a)
1035 | 2: [append (b) (a)]
1036 | 2: =>(b a)
1037 (b a)
1038 @end lisp
1039
1040 @noindent
1041 The output in this case shows every step that the evaluator performs
1042 in evaluating @code{(rev '(a b))}.
1043
1044
1045 @node Tracing Configuration
1046 @subsubsection Tracing Configuration
1047
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.
1052
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.
1057 @end deffn
1058
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}.
1065 @end deffn
1066
1067 @noindent
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:}
1074 procedures.
1075
1076 @deffn {Procedure} trace/pid trap-context
1077 An arg-proc that returns the current process ID.
1078 @end deffn
1079
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.
1083 @end deffn
1084
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.
1088 @end deffn
1089
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.
1093 @end deffn
1094
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"}.
1099 @end deffn
1100
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
1104 innermost frame.
1105 @end deffn
1106
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
1110 innermost frame.
1111 @end deffn
1112
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.
1117 @end deffn
1118
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.
1124 @end deffn
1125
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.
1131 @end deffn
1132
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.
1136 @end deffn
1137
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.
1142 @end deffn
1143
1144 @noindent
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
1148 convenience.
1149
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
1152 traps)} module:
1153
1154 @lisp
1155 (set-trace-layout "|~3@@a: ~a\n" trace/stack-real-depth trace/info)
1156 @end lisp
1157
1158 @noindent
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:
1162
1163 @lisp
1164 guile> (set-trace-layout "| ~25a ~3@@a: ~a ~a\n"
1165 trace/source
1166 trace/stack-real-depth
1167 trace/type
1168 trace/info)
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)
1178 (c b a)
1179 @end lisp
1180
1181
1182 @node Tracing and (ice-9 debug)
1183 @subsubsection Tracing and (ice-9 debug)
1184
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.
1188
1189 @itemize @bullet
1190 @item
1191 The @code{(ice-9 debug)} trace gives a nice pictorial view of changes
1192 in stack depth, by using indentation like this:
1193
1194 @lisp
1195 [fact1 4]
1196 | [fact1 3]
1197 | | [fact1 2]
1198 | | | [fact1 1]
1199 | | | | [fact1 0]
1200 | | | | 1
1201 | | | 1
1202 | | 2
1203 | 6
1204 24
1205 @end lisp
1206
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.
1212
1213 @item
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.
1217
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.
1227 @end itemize
1228
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.
1232
1233
1234 @node Traps Installing More Traps
1235 @subsubsection Traps Installing More Traps
1236
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.
1244
1245 @lisp
1246 (define (at-exit trap-context behaviour)
1247 (install-trap (make <exit-trap>
1248 #:depth (tc:depth trap-context)
1249 #:single-shot #t
1250 #:behaviour behaviour)))
1251 @end lisp
1252
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.
1256
1257 @lisp
1258 (define calls 0)
1259 (define total 0)
1260
1261 (define accumulate-time
1262 (lambda (trap-context)
1263 (set! calls (+ calls 1))
1264 (let ((entry (current-time)))
1265 (at-exit trap-context
1266 (lambda (ignored)
1267 (set! total
1268 (+ total (- (current-time)
1269 entry))))))))
1270
1271 (install-trap (make <procedure-trap>
1272 #:procedure my-proc
1273 #:behaviour accumulate-time))
1274 @end lisp
1275
1276
1277 @node Common Trap Options
1278 @subsubsection Common Trap Options
1279
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
1282 like this:
1283
1284 @lisp
1285 (make <@var{trap-class}>
1286 #:@var{option-keyword} @var{setting}
1287 @dots{})
1288 @end lisp
1289
1290 The following common options are provided by the base class
1291 @code{<trap>}, and so can be specified for any kind of trap.
1292
1293 @deffn {Class} <trap>
1294 Base class for trap objects.
1295 @end deffn
1296
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}.)
1302 @end deffn
1303
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.)
1307 @end deffn
1308
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
1313 value @code{#f}.)
1314 @end deffn
1315
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{'()}.)
1320 @end deffn
1321
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}.)
1330 @end deffn
1331
1332
1333 @node Procedure Traps
1334 @subsubsection Procedure Traps
1335
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
1339 trap on.
1340
1341 @deffn {Class} <procedure-trap>
1342 Class for traps triggered by application of a specified procedure.
1343 @end deffn
1344
1345 @deffn {Trap Option} #:procedure procedure
1346 Specifies the procedure to trap on.
1347 @end deffn
1348
1349 @noindent
1350 Example:
1351
1352 @lisp
1353 (install-trap (make <procedure-trap>
1354 #:procedure my-proc
1355 #:behaviour (list trace-trap
1356 trace-until-exit)))
1357 @end lisp
1358
1359
1360 @node Exit Traps
1361 @subsubsection Exit Traps
1362
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
1366 depth.
1367
1368 @deffn {Class} <exit-trap>
1369 Class for traps triggered by exit past a specified stack depth.
1370 @end deffn
1371
1372 @deffn {Trap Option} #:depth depth
1373 Specifies the reference depth for the trap.
1374 @end deffn
1375
1376 @noindent
1377 Example:
1378
1379 @lisp
1380 (define (trace-at-exit trap-context)
1381 (install-trap (make <exit-trap>
1382 #:depth (tc:depth trap-context)
1383 #:single-shot #t
1384 #:behaviour trace-trap)))
1385 @end lisp
1386
1387 @noindent
1388 (This is the actual definition of the @code{trace-at-exit} behaviour.)
1389
1390
1391 @node Entry Traps
1392 @subsubsection Entry Traps
1393
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.
1400
1401 @deffn {Class} <entry-trap>
1402 Class for traps triggered by any stack frame entry.
1403 @end deffn
1404
1405 @noindent
1406 Example:
1407
1408 @lisp
1409 (install-trap (make <entry-trap>
1410 #:skip-count 5
1411 #:behaviour gds-debug-trap))
1412 @end lisp
1413
1414
1415 @node Apply Traps
1416 @subsubsection Apply Traps
1417
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.
1424
1425 @deffn {Class} <apply-trap>
1426 Class for traps triggered by any procedure application.
1427 @end deffn
1428
1429 @noindent
1430 Example:
1431
1432 @lisp
1433 (install-trap (make <apply-trap>
1434 #:condition my-condition
1435 #:behaviour gds-debug-trap))
1436 @end lisp
1437
1438
1439 @node Step Traps
1440 @subsubsection Step Traps
1441
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
1450 of any kind.
1451
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
1459 it.
1460
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
1470 reasons.
1471
1472 @itemize @bullet
1473 @item
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
1479 frame.
1480
1481 @item
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
1487 this stack depth.
1488
1489 @item
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}.
1494 @end itemize
1495
1496 @noindent
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.
1501
1502 @deffn {Class} <step-trap>
1503 Class for single-stepping traps.
1504 @end deffn
1505
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}.)
1510 @end deffn
1511
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}.)
1516 @end deffn
1517
1518 @noindent
1519 Example:
1520
1521 @lisp
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))
1527 #:single-shot #t
1528 #:behaviour debug-trap))
1529 @end lisp
1530
1531
1532 @node Source Traps
1533 @subsubsection Source Traps
1534
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.
1543
1544 @deffn {Class} <source-trap>
1545 Class for traps triggered by evaluation of a specific Scheme
1546 expression.
1547 @end deffn
1548
1549 @deffn {Trap Option} #:expression expr
1550 Specifies the Scheme expression to trap on.
1551 @end deffn
1552
1553 @noindent
1554 Example:
1555
1556 @lisp
1557 (display "Enter an expression: ")
1558 (let ((x (read)))
1559 (install-trap (make <source-trap>
1560 #:expression x
1561 #:behaviour (list trace-trap
1562 trace-at-exit)))
1563 (primitive-eval x))
1564 @print{}
1565 Enter an expression: (+ 1 2 3 4 5 6)
1566 | 3: (+ 1 2 3 4 5 6)
1567 | 3: =>21
1568 21
1569 @end lisp
1570
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)}.
1576
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:
1580
1581 @lisp
1582 (define (fact1 n)
1583 (if (= n 0)
1584 1
1585 (* n (fact1 (- n 1)))))
1586 @end lisp
1587
1588 @noindent
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:
1592
1593 @lisp
1594 (define (fact1 n)
1595 (if (trap-here (= n 0) #:behaviour debug-trap)
1596 1
1597 (* n (fact1 (- n 1)))))
1598 @end lisp
1599
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})}.
1604 @end deffn
1605
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.
1611
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.
1615
1616
1617 @node Location Traps
1618 @subsubsection Location Traps
1619
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
1626 call.
1627
1628 @deffn {Class} <location-trap>
1629 Class for traps triggered by evaluation of code at a specific source
1630 location.
1631 @end deffn
1632
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.
1636 @end deffn
1637
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
1641 location trap.
1642 @end deffn
1643
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
1647 location trap.
1648 @end deffn
1649
1650 @noindent
1651 Here is an example, which matches the @code{(facti (- n 1) (* a n))}
1652 expression in @file{ice-9/debugging/example-fns.scm}:
1653
1654 @lisp
1655 (install-trap (make <location-trap>
1656 #:file-regexp "example-fns.scm"
1657 #:line 11
1658 #:column 6
1659 #:behaviour gds-debug-trap))
1660 @end lisp
1661
1662
1663 @node Trap Shorthands
1664 @subsubsection Trap Shorthands
1665
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.
1670
1671 @lisp
1672 (define (break! proc)
1673 (install-trap (make <procedure-trap>
1674 #:procedure proc
1675 #:behaviour gds-debug-trap)))
1676
1677 (define (trace! proc)
1678 (install-trap (make <procedure-trap>
1679 #:procedure proc
1680 #:behaviour (list trace-trap
1681 trace-at-exit))))
1682
1683 (define (trace-subtree! proc)
1684 (install-trap (make <procedure-trap>
1685 #:procedure proc
1686 #:behaviour (list trace-trap
1687 trace-until-exit))))
1688 @end lisp
1689
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.
1695
1696
1697 @node Trap Utilities
1698 @subsubsection Trap Utilities
1699
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}.
1707
1708 @deffn {Variable} all-traps
1709 Weak value hash table containing all known trap objects.
1710 @end deffn
1711
1712 @deffn {Procedure} list-traps
1713 Print a description of all known trap objects.
1714 @end deffn
1715
1716 The following example shows a single trap that traces applications of
1717 the procedure @code{facti}.
1718
1719 @lisp
1720 guile> (list-traps)
1721 #<<procedure-trap> 100d2e30> is an instance of class <procedure-trap>
1722 Slots are:
1723 number = 1
1724 installed = #t
1725 condition = #f
1726 skip-count = 0
1727 single-shot = #f
1728 behaviour = (#<procedure trace-trap (trap-context)>)
1729 repeat-identical-behaviour = #f
1730 procedure = #<procedure facti (n a)>
1731 @end lisp
1732
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
1737 just above.
1738
1739 @lisp
1740 (slot-set! (get-trap 1) 'behaviour (list debug-trap))
1741 @end lisp
1742
1743 @deffn {Procedure} get-trap number
1744 Return the trap object with the specified @var{number}, or @code{#f}
1745 if there isn't one.
1746 @end deffn
1747
1748
1749 @node Debugging Examples
1750 @subsection Debugging Examples
1751
1752 Here we present some examples of what you can do with the debugging
1753 facilities just described.
1754
1755 @menu
1756 * Single Stepping through a Procedure's Code::
1757 * Profiling or Tracing a Procedure's Code::
1758 @end menu
1759
1760
1761 @node Single Stepping through a Procedure's Code
1762 @subsubsection Single Stepping through a Procedure's Code
1763
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)}.
1768
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}.
1773
1774 @lisp
1775 $ /usr/bin/guile -q
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))
1782 guile> (do-main 4)
1783 This is the Guile debugger -- for help, type `help'.
1784 There are 3 frames on the stack.
1785
1786 Frame 2 at matrix.scm:8:3
1787 [mkmatrix]
1788 debug> next
1789 Frame 3 at matrix.scm:4:3
1790 (let ((x 1)) (quote hi!))
1791 debug> info frame
1792 Stack frame: 3
1793 This frame is an evaluation.
1794 The expression being evaluated is:
1795 matrix.scm:4:3:
1796 (let ((x 1)) (quote hi!))
1797 debug> next
1798 Frame 3 at matrix.scm:5:21
1799 (quote hi!)
1800 debug> bt
1801 In unknown file:
1802 ?: 0* [primitive-eval (do-main 4)]
1803 In standard input:
1804 4: 1* [do-main 4]
1805 In matrix.scm:
1806 8: 2 [mkmatrix]
1807 ...
1808 5: 3 (quote hi!)
1809 debug> quit
1810 hi!
1811 guile>
1812 @end lisp
1813
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
1818 Guile command line.
1819
1820
1821 @node Profiling or Tracing a Procedure's Code
1822 @subsubsection Profiling or Tracing a Procedure's Code
1823
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.
1831
1832 @lisp
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)))
1838 guile> (do-main 4)
1839 | 2: [mkmatrix]
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)]
1845 | 5: =>#f
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)]
1851 | 5: =>#f
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)]
1857 | 5: =>#f
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)]
1863 | 5: =>#f
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)]
1869 | 5: =>#f
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)]
1876 | 5: =>#f
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)]
1882 | 5: =>#f
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)]
1888 | 5: =>#f
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)]
1895 | 5: =>#f
1896 | 2: [let (let # #) (# # #)]
1897 | 2: [let (let # #) (# # #)]
1898 | 2: =>(#@@let* (x 1) #@@let (quote hi!))
1899 hi!
1900 guile> (do-main 4)
1901 | 2: [mkmatrix]
1902 | 2: (letrec ((yy 23)) (let* ((x 1)) (quote hi!)))
1903 | 2: (let* ((x 1)) (quote hi!))
1904 | 2: (quote hi!)
1905 | 2: =>hi!
1906 hi!
1907 guile>
1908 @end lisp
1909
1910 This example shows the default configuration for how each line of trace
1911 output is formatted, which is:
1912
1913 @itemize
1914 @item
1915 the character @code{|}, a visual clue that the line is a line of trace
1916 output, followed by
1917
1918 @item
1919 a number indicating the real evaluator stack depth (where ``real'' means
1920 not counting tail-calls), followed by
1921
1922 @item
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{}}).
1926 @end itemize
1927
1928 @noindent
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.
1933
1934 @lisp
1935 guile> (set-trace-layout "|~16@@a: ~a\n" trace/source trace/info)
1936 guile> (do-main 4)
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!
1942 hi!
1943 guile>
1944 @end lisp
1945
1946 @c Local Variables:
1947 @c TeX-master: "guile.texi"
1948 @c End: