finish cleaning out api-options.texi
[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 * Debug on Error:: 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 Debug on Error
281 @subsection Debugging when an error occurs
282
283 A common requirement is to be able to show as much useful context as
284 possible when a Scheme program hits an error. The most immediate
285 information about an error is the kind of error that it is -- such as
286 ``division by zero'' -- and any parameters that the code which signalled
287 the error chose explicitly to provide. This information originates with
288 the @code{error} or @code{throw} call (or their C code equivalents, if
289 the error is detected by C code) that signals the error, and is passed
290 automatically to the handler procedure of the innermost applicable
291 @code{catch} or @code{with-throw-handler} expression.
292
293 @subsubsection Intercepting basic error information
294
295 Therefore, to catch errors that occur within a chunk of Scheme code, and
296 to intercept basic information about those errors, you need to execute
297 that code inside the dynamic context of a @code{catch} or
298 @code{with-throw-handler} expression, or the equivalent in C. In Scheme,
299 this means you need something like this:
300
301 @lisp
302 (catch #t
303 (lambda ()
304 ;; Execute the code in which
305 ;; you want to catch errors here.
306 ...)
307 (lambda (key . parameters)
308 ;; Put the code which you want
309 ;; to handle an error here.
310 ...))
311 @end lisp
312
313 @noindent
314 The @code{catch} here can also be @code{with-throw-handler}; see @ref{Throw
315 Handlers} for information on the when you might want to use
316 @code{with-throw-handler} instead of @code{catch}. The @code{#t} means that the
317 catch is applicable to all kinds of error; if you want to restrict your catch to
318 just one kind of error, you can put the symbol for that kind of error instead of
319 @code{#t}. The equivalent to this in C would be something like this:
320
321 @lisp
322 SCM my_body_proc (void *body_data)
323 @{
324 /* Execute the code in which
325 you want to catch errors here. */
326 ...
327 @}
328
329 SCM my_handler_proc (void *handler_data,
330 SCM key,
331 SCM parameters)
332 @{
333 /* Put the code which you want
334 to handle an error here. */
335 ...
336 @}
337
338 @{
339 ...
340 scm_c_catch (SCM_BOOL_T,
341 my_body_proc, body_data,
342 my_handler_proc, handler_data,
343 NULL, NULL);
344 ...
345 @}
346 @end lisp
347
348 @noindent
349 Again, as with the Scheme version, @code{scm_c_catch} could be replaced
350 by @code{scm_c_with_throw_handler}, and @code{SCM_BOOL_T} could instead
351 be the symbol for a particular kind of error.
352
353 @subsubsection Capturing the full error stack
354
355 The other interesting information about an error is the full Scheme
356 stack at the point where the error occurred; in other words what
357 innermost expression was being evaluated, what was the expression that
358 called that one, and so on. If you want to write your code so that it
359 captures and can display this information as well, there are a couple
360 important things to understand.
361
362 Firstly, the stack at the point of the error needs to be explicitly
363 captured by a @code{make-stack} call (or the C equivalent
364 @code{scm_make_stack}). The Guile library does not do this
365 ``automatically'' for you, so you will need to write code with a
366 @code{make-stack} or @code{scm_make_stack} call yourself. (We emphasise
367 this point because some people are misled by the fact that the Guile
368 interactive REPL code @emph{does} capture and display the stack
369 automatically. But the Guile interactive REPL is itself a Scheme
370 program@footnote{In effect, it is the default program which is run when
371 no commands or script file are specified on the Guile command line.}
372 running on top of the Guile library, and which uses @code{catch} and
373 @code{make-stack} in the way we are about to describe to capture the
374 stack when an error occurs.)
375
376 And secondly, in order to capture the stack effectively at the point
377 where the error occurred, the @code{make-stack} call must be made before
378 Guile unwinds the stack back to the location of the prevailing catch
379 expression. This means that the @code{make-stack} call must be made
380 within the handler of a @code{with-throw-handler} expression, or the
381 optional "pre-unwind" handler of a @code{catch}. (For the full story of
382 how these alternatives differ from each other, see @ref{Exceptions}. The
383 main difference is that @code{catch} terminates the error, whereas
384 @code{with-throw-handler} only intercepts it temporarily and then allow
385 it to continue propagating up to the next innermost handler.)
386
387 So, here are some examples of how to do all this in Scheme and in C.
388 For the purpose of these examples we assume that the captured stack
389 should be stored in a variable, so that it can be displayed or
390 arbitrarily processed later on. In Scheme:
391
392 @lisp
393 (let ((captured-stack #f))
394 (catch #t
395 (lambda ()
396 ;; Execute the code in which
397 ;; you want to catch errors here.
398 ...)
399 (lambda (key . parameters)
400 ;; Put the code which you want
401 ;; to handle an error after the
402 ;; stack has been unwound here.
403 ...)
404 (lambda (key . parameters)
405 ;; Capture the stack here:
406 (set! captured-stack (make-stack #t))))
407 ...
408 (if captured-stack
409 (begin
410 ;; Display or process the captured stack.
411 ...))
412 ...)
413 @end lisp
414
415 @noindent
416 And in C:
417
418 @lisp
419 SCM my_body_proc (void *body_data)
420 @{
421 /* Execute the code in which
422 you want to catch errors here. */
423 ...
424 @}
425
426 SCM my_handler_proc (void *handler_data,
427 SCM key,
428 SCM parameters)
429 @{
430 /* Put the code which you want
431 to handle an error after the
432 stack has been unwound here. */
433 ...
434 @}
435
436 SCM my_preunwind_proc (void *handler_data,
437 SCM key,
438 SCM parameters)
439 @{
440 /* Capture the stack here: */
441 *(SCM *)handler_data = scm_make_stack (SCM_BOOL_T, SCM_EOL);
442 @}
443
444 @{
445 SCM captured_stack = SCM_BOOL_F;
446 ...
447 scm_c_catch (SCM_BOOL_T,
448 my_body_proc, body_data,
449 my_handler_proc, handler_data,
450 my_preunwind_proc, &captured_stack);
451 ...
452 if (captured_stack != SCM_BOOL_F)
453 @{
454 /* Display or process the captured stack. */
455 ...
456 @}
457 ...
458 @}
459 @end lisp
460
461 @noindent
462 Note that you don't have to wait until after the @code{catch} or
463 @code{scm_c_catch} has returned. You can also do whatever you like with
464 the stack immediately after it has been captured in the pre-unwind
465 handler, or in the normal (post-unwind) handler. (Except that for the
466 latter case in C you will need to change @code{handler_data} in the
467 @code{scm_c_catch(@dots{})} call to @code{&captured_stack}, so that
468 @code{my_handler_proc} has access to the captured stack.)
469
470 @subsubsection Displaying or interrogating the captured stack
471
472 Once you have a captured stack, you can interrogate and display its
473 details in any way that you want, using the @code{stack-@dots{}} and
474 @code{frame-@dots{}} API described in @ref{Examining the Stack} and
475 @ref{Examining Stack Frames}.
476
477 If you want to print out a backtrace in the same format that the Guile
478 REPL does, you can use the @code{display-backtrace} procedure to do so.
479 You can also use @code{display-application} to display an individual
480 application frame -- that is, a frame that satisfies the
481 @code{frame-procedure?} predicate -- in the Guile REPL format.
482
483 @subsubsection What the Guile REPL does
484
485 The Guile REPL code (in @file{system/repl/repl.scm} and related files)
486 uses a @code{catch} with a pre-unwind handler to capture the stack when
487 an error occurs in an expression that was typed into the REPL, and saves
488 the captured stack in a fluid (@pxref{Fluids and Dynamic States}) called
489 @code{the-last-stack}. You can then use the @code{(backtrace)} command,
490 which is basically equivalent to @code{(display-backtrace (fluid-ref
491 the-last-stack))}, to print out this stack at any time until it is
492 overwritten by the next error that occurs.
493
494 @deffn {Scheme Procedure} backtrace [highlights]
495 @deffnx {C Function} scm_backtrace_with_highlights (highlights)
496 @deffnx {C Function} scm_backtrace ()
497 Display a backtrace of the stack saved by the last error
498 to the current output port. If @var{highlights} is given
499 it should be a list; the elements of this list will be
500 highlighted wherever they appear in the backtrace.
501 @end deffn
502
503 You can also use the @code{(debug)} command to explore the saved stack
504 using an interactive command-line-driven debugger. See @ref{Interactive
505 Debugging} for more information about this.
506
507 @deffn {Scheme Procedure} debug
508 Invoke the Guile debugger to explore the context of the last error.
509 @end deffn
510
511 @subsubsection Debug options
512
513 The behavior when an error is the @code{backtrace} procedure and of the
514 default error handler can be parameterized via the debug options.
515
516 @cindex options - debug
517 @cindex debug options
518 @deffn {Scheme Procedure} debug-options [setting]
519 Display the current settings of the debug options. If @var{setting} is
520 omitted, only a short form of the current read options is printed.
521 Otherwise if @var{setting} is the symbol @code{help}, a complete options
522 description is displayed.
523 @end deffn
524
525 The set of available options, and their default values, may be had by
526 invoking @code{debug-options} at the prompt.
527
528 @smallexample
529 scheme@@(guile-user)>
530 backwards no Display backtrace in anti-chronological order.
531 width 79 Maximal width of backtrace.
532 depth 20 Maximal length of printed backtrace.
533 backtrace yes Show backtrace on error.
534 stack 1048576 Stack size limit (measured in words;
535 0 = no check).
536 show-file-name #t Show file names and line numbers in backtraces
537 when not `#f'. A value of `base' displays only
538 base names, while `#t' displays full names.
539 warn-deprecated no Warn when deprecated features are used.
540 @end smallexample
541
542 The boolean options may be toggled with @code{debug-enable} and
543 @code{debug-disable}. The non-boolean @code{keywords} option must be set
544 using @code{debug-set!}.
545
546 @deffn {Scheme Procedure} debug-enable option-name
547 @deffnx {Scheme Procedure} debug-disable option-name
548 @deffnx {Scheme Procedure} debug-set! option-name value
549 Modify the debug options. @code{debug-enable} should be used with boolean
550 options and switches them on, @code{debug-disable} switches them off.
551 @code{debug-set!} can be used to set an option to a specific value.
552 @end deffn
553
554 @subsubheading Stack overflow
555
556 @cindex overflow, stack
557 @cindex stack overflow
558 Stack overflow errors are caused by a computation trying to use more
559 stack space than has been enabled by the @code{stack} option. They are
560 reported like this:
561
562 @lisp
563 (non-tail-recursive-factorial 500)
564 @print{}
565 ERROR: Stack overflow
566 ABORT: (stack-overflow)
567 @end lisp
568
569 If you get an error like this, you can either try rewriting your code to
570 use less stack space, or increase the maximum stack size. To increase
571 the maximum stack size, use @code{debug-set!}, for example:
572
573 @lisp
574 (debug-set! stack 200000)
575 @result{}
576 (show-file-name #t stack 200000 debug backtrace depth 20
577 maxdepth 1000 frames 3 indent 10 width 79 procnames cheap)
578
579 (non-tail-recursive-factorial 500)
580 @result{}
581 122013682599111006870123878542304692625357434@dots{}
582 @end lisp
583
584 If you prefer to try rewriting your code, you may be able to save stack
585 space by making some of your procedures @dfn{tail recursive}
586 (@pxref{Tail Calls}).
587
588
589 @node Traps
590 @subsection Traps
591
592 @cindex Traps
593 @cindex Evaluator trap calls
594 @cindex Breakpoints
595 @cindex Trace
596 @cindex Tracing
597 @cindex Code coverage
598 @cindex Profiling
599 Guile's virtual machine can be configured to call out at key points to
600 arbitrary user-specified procedures. For more information on these
601 hooks, and the circumstances under which the VM calls them, see @ref{VM
602 Behaviour}.
603
604 In principle, these hooks allow Scheme code to implement any model it
605 chooses for examining the evaluation stack as program execution
606 proceeds, and for suspending execution to be resumed later. Possible
607 applications of this feature include breakpoints, runtime tracing, code
608 coverage, and profiling.
609
610 @cindex Trap classes
611 @cindex Trap objects
612 Based on these low level trap calls, Guile provides a higher level,
613 object-oriented interface for the manipulation of traps. Different
614 kinds of trap are represented as GOOPS classes; for example, the
615 @code{<procedure-trap>} class describes traps that are triggered by
616 invocation of a specified procedure. A particular instance of a trap
617 class --- or @dfn{trap object} --- describes the condition under which
618 a single trap will be triggered, and what will happen then; for
619 example, an instance of @code{<procedure-trap>} whose @code{procedure}
620 and @code{behaviour} slots contain @code{my-factorial} and
621 @code{debug-trap} would be a trap that enters the command line
622 debugger when the @code{my-factorial} procedure is invoked.
623
624 The following subsections describe all this in detail, for both the
625 user wanting to use traps, and the developer interested in
626 understanding how the interface hangs together.
627
628
629 @subsubsection Actually, this section is bitrotten
630
631 Dear reader: the following sections have some great ideas, and some code
632 that just needs a few days of massaging to get it to work with the VM
633 (as opposed to the old interpreter). Want to help? Yes? Yes!
634 @code{guile-devel@@gnu.org}, that's where.
635
636
637 @subsubsection A Quick Note on Terminology
638
639 @cindex Trap terminology
640 It feels natural to use the word ``trap'' in some form for all levels
641 of the structure just described, so we need to be clear on the
642 terminology we use to describe each particular level. The terminology
643 used in this subsection is as follows.
644
645 @itemize @bullet
646 @item
647 @cindex Evaluator trap calls
648 @cindex Low level trap calls
649 ``Low level trap calls'', or ``low level traps'', are the calls made
650 directly from the C code of the Guile evaluator.
651
652 @item
653 @cindex Trap classes
654 ``Trap classes'' are self-explanatory.
655
656 @item
657 @cindex Trap objects
658 ``Trap objects'', ``trap instances'', or just ``traps'', are instances
659 of a trap class, and each describe a single logical trap condition
660 plus behaviour as specified by the user of this interface.
661 @end itemize
662
663 A good example of when it is important to be clear, is when we talk
664 below of behaviours that should only happen once per low level trap.
665 A single low level trap call will typically map onto the processing of
666 several trap objects, so ``once per low level trap'' is significantly
667 different from ``once per trap''.
668
669
670 @menu
671 * How to Set a Trap::
672 * Specifying Trap Behaviour::
673 * Trap Context::
674 * Tracing Examples::
675 * Tracing Configuration::
676 * Tracing and (ice-9 debug)::
677 * Traps Installing More Traps::
678 * Common Trap Options::
679 * Procedure Traps::
680 * Exit Traps::
681 * Entry Traps::
682 * Apply Traps::
683 * Step Traps::
684 * Source Traps::
685 * Location Traps::
686 * Trap Shorthands::
687 * Trap Utilities::
688 @end menu
689
690
691 @node How to Set a Trap
692 @subsubsection How to Set a Trap
693
694 @cindex Setting traps
695 @cindex Installing and uninstalling traps
696 Setting a trap is done in two parts. First the trap is defined by
697 creating an instance of the appropriate trap class, with slot values
698 specifying the condition under which the trap will fire and the action
699 to take when it fires. Secondly the trap object thus created must be
700 @dfn{installed}.
701
702 To make this immediately concrete, here is an example that sets a trap
703 to fire on the next application of the @code{facti} procedure, and to
704 handle the trap by entering the command line debugger.
705
706 @lisp
707 (install-trap (make <procedure-trap>
708 #:procedure facti
709 #:single-shot #t
710 #:behaviour debug-trap))
711 @end lisp
712
713 @noindent
714 Briefly, the elements of this incantation are as follows. (All of
715 these are described more fully in the following subsubsections.)
716
717 @itemize @bullet
718 @item
719 @code{<procedure-trap>} is the trap class for trapping on invocation
720 of a specific procedure.
721
722 @item
723 @code{#:procedure facti} says that the specific procedure to trap on for this
724 trap object is @code{facti}.
725
726 @item
727 @code{#:single-shot #t} says that this trap should only fire on the
728 @emph{next} invocation of @code{facti}, not on all future invocations
729 (which is the default if the @code{#:single-shot} option is not
730 specified).
731
732 @item
733 @code{#:behaviour debug-trap} says that the trap infrastructure should
734 call the procedure @code{debug-trap} when this trap fires.
735
736 @item
737 Finally, the @code{install-trap} call installs the trap immediately.
738 @end itemize
739
740 @noindent
741 It is of course possible for the user to define more convenient
742 shorthands for setting common kinds of traps. @xref{Trap Shorthands},
743 for some examples.
744
745 The ability to install, uninstall and reinstall a trap without losing
746 its definition is Guile's equivalent of the disable/enable commands
747 provided by debuggers like GDB.
748
749 @deffn {Generic Function} install-trap trap
750 Install the trap object @var{trap}, so that its behaviour will be
751 executed when the conditions for the trap firing are met.
752 @end deffn
753
754 @deffn {Generic Function} uninstall-trap trap
755 Uninstall the trap object @var{trap}, so that its behaviour will
756 @emph{not} be executed even if the conditions for the trap firing are
757 met.
758 @end deffn
759
760
761 @node Specifying Trap Behaviour
762 @subsubsection Specifying Trap Behaviour
763
764 @cindex Trap behaviour
765 Guile provides several ``out-of-the-box'' behaviours for common needs.
766 All of the following can be used directly as the value of the
767 @code{#:behaviour} option when creating a trap object.
768
769 @deffn {Procedure} debug-trap trap-context
770 Enter Guile's command line debugger to explore the stack at
771 @var{trap-context}, and to single-step or continue program execution
772 from that point.
773 @end deffn
774
775 @deffn {Procedure} gds-debug-trap trap-context
776 Use the GDS debugging interface, which displays the stack and
777 corresponding source code via Emacs, to explore the stack at
778 @var{trap-context} and to single-step or continue program execution
779 from that point.
780 @end deffn
781
782 @cindex Trace
783 @cindex Tracing
784 @deffn {Procedure} trace-trap trap-context
785 Display trace information to summarize the current @var{trap-context}.
786 @end deffn
787
788 @deffn {Procedure} trace-at-exit trap-context
789 Install a further trap to cause the return value of the application or
790 evaluation just starting (as described by @var{trap-context}) to be
791 traced using @code{trace-trap}, when this application or evaluation
792 completes. The extra trap is automatically uninstalled after the
793 return value has been traced.
794 @end deffn
795
796 @deffn {Procedure} trace-until-exit trap-context
797 Install a further trap so that every step that the evaluator performs
798 as part of the application or evaluation just starting (as described
799 by @var{trap-context}) is traced using @code{trace-trap}. The extra
800 trap is automatically uninstalled when the application or evaluation
801 is complete. @code{trace-until-exit} can be very useful as a first
802 step when all you know is that there is a bug ``somewhere in XXX or in
803 something that XXX calls''.
804 @end deffn
805
806 @noindent
807 @code{debug-trap} and @code{gds-debug-trap} are provided by the modules
808 @code{(ice-9 debugger)} and @code{(ice-9 gds-client)} respectively, and
809 their behaviours are fairly self-explanatory. For more information on
810 the operation of the GDS interface via Emacs, see @ref{Using Guile in
811 Emacs}. The tracing behaviours are explained more fully below.
812
813 @cindex Trap context
814 More generally, the @dfn{behaviour} specified for a trap can be any
815 procedure that expects to be called with one @dfn{trap context}
816 argument. A trivial example would be:
817
818 @lisp
819 (define (report-stack-depth trap-context)
820 (display "Stack depth at the trap is: ")
821 (display (tc:depth trap-context))
822 (newline))
823 @end lisp
824
825
826 @node Trap Context
827 @subsubsection Trap Context
828
829 The @dfn{trap context} is an object that caches information about the
830 low level trap call and the stack at the point of the trap, and is
831 passed as the only argument to all behaviour procedures. The
832 information in the trap context can be accessed through the procedures
833 beginning @code{tc:} that are exported by the @code{(ice-9 debugging
834 traps)} module@footnote{Plus of course any procedures that build on
835 these, such as the @code{trace/@dots{}} procedures exported by
836 @code{(ice-9 debugging trace)} (@pxref{Tracing Configuration}).}; the
837 most useful of these are as follows.
838
839 @deffn {Generic Function} tc:type trap-context
840 Indicates the type of the low level trap by returning one of the
841 keywords @code{#:application}, @code{#:evaluation}, @code{#:return} or
842 @code{#:error}.
843 @end deffn
844
845 @deffn {Generic Function} tc:return-value trap-context
846 When @code{tc:type} gives @code{#:return}, this provides the value
847 that is being returned.
848 @end deffn
849
850 @deffn {Generic Function} tc:stack trap-context
851 Provides the stack at the point of the trap (as computed by
852 @code{make-stack}, but cached so that the lengthy @code{make-stack}
853 operation is not performed more than once for the same low level
854 trap).
855 @end deffn
856
857 @deffn {Generic Function} tc:frame trap-context
858 The innermost frame of the stack at the point of the trap.
859 @end deffn
860
861 @deffn {Generic Function} tc:depth trap-context
862 The number of frames (including tail recursive non-real frames) in the
863 stack at the point of the trap.
864 @end deffn
865
866 @deffn {Generic Function} tc:real-depth trap-context
867 The number of real frames (that is, excluding the non-real frames that
868 describe tail recursive calls) in the stack at the point of the trap.
869 @end deffn
870
871
872 @node Tracing Examples
873 @subsubsection Tracing Examples
874
875 The following examples show what tracing is and the kind of output that
876 it generates. In the first example, we define a recursive function for
877 reversing a list, then watch the effect of the recursive calls by
878 tracing each call and return value.
879
880 @lisp
881 guile> (define (rev ls)
882 (if (null? ls)
883 ls
884 (append (rev (cdr ls))
885 (list (car ls)))))
886 guile> (use-modules (ice-9 debugging traps) (ice-9 debugging trace))
887 guile> (define t1 (make <procedure-trap>
888 #:procedure rev
889 #:behaviour (list trace-trap
890 trace-at-exit)))
891 guile> (install-trap t1)
892 guile> (rev '(a b c))
893 | 2: [rev (a b c)]
894 | 3: [rev (b c)]
895 | 4: [rev (c)]
896 | 5: [rev ()]
897 | 5: =>()
898 | 4: =>(c)
899 | 3: =>(c b)
900 | 2: =>(c b a)
901 (c b a)
902 @end lisp
903
904 @noindent
905 The number before the colon in this output (which follows @code{(ice-9
906 debugging trace)}'s default output format) is the number of real frames
907 on the stack. The fact that this number increases for each recursive
908 call confirms that the implementation above of @code{rev} is not
909 tail-recursive.
910
911 In the next example, we probe the @emph{internal} workings of
912 @code{rev} in more detail by using the @code{trace-until-exit}
913 behaviour.
914
915 @lisp
916 guile> (uninstall-trap t1)
917 guile> (define t2 (make <procedure-trap>
918 #:procedure rev
919 #:behaviour (list trace-trap
920 trace-until-exit)))
921 guile> (install-trap t2)
922 guile> (rev '(a b))
923 | 2: [rev (a b)]
924 | 2: (if (null? ls) ls (append (rev (cdr ls)) (list (car ls))))
925 | 3: (null? ls)
926 | 3: [null? (a b)]
927 | 3: =>#f
928 | 2: (append (rev (cdr ls)) (list (car ls)))
929 | 3: (rev (cdr ls))
930 | 4: (cdr ls)
931 | 4: [cdr (a b)]
932 | 4: =>(b)
933 | 3: [rev (b)]
934 | 3: (if (null? ls) ls (append (rev (cdr ls)) (list (car ls))))
935 | 4: (null? ls)
936 | 4: [null? (b)]
937 | 4: =>#f
938 | 3: (append (rev (cdr ls)) (list (car ls)))
939 | 4: (rev (cdr ls))
940 | 5: (cdr ls)
941 | 5: [cdr (b)]
942 | 5: =>()
943 | 4: [rev ()]
944 | 4: (if (null? ls) ls (append (rev (cdr ls)) (list (car ls))))
945 | 5: (null? ls)
946 | 5: [null? ()]
947 | 5: =>#t
948 | 4: (list (car ls))
949 | 5: (car ls)
950 | 5: [car (b)]
951 | 5: =>b
952 | 4: [list b]
953 | 4: =>(b)
954 | 3: [append () (b)]
955 | 3: =>(b)
956 | 3: (list (car ls))
957 | 4: (car ls)
958 | 4: [car (a b)]
959 | 4: =>a
960 | 3: [list a]
961 | 3: =>(a)
962 | 2: [append (b) (a)]
963 | 2: =>(b a)
964 (b a)
965 @end lisp
966
967 @noindent
968 The output in this case shows every step that the evaluator performs
969 in evaluating @code{(rev '(a b))}.
970
971
972 @node Tracing Configuration
973 @subsubsection Tracing Configuration
974
975 The detail of what gets printed in each trace line, and the port to
976 which tracing is written, can be configured by the procedures
977 @code{set-trace-layout} and @code{trace-port}, both exported by the
978 @code{(ice-9 debugging trace)} module.
979
980 @deffn {Procedure with Setter} trace-port
981 Get or set the port to which tracing is printed. The default is the
982 value of @code{(current-output-port)} when the @code{(ice-9 debugging
983 trace)} module is first loaded.
984 @end deffn
985
986 @deffn {Procedure} set-trace-layout format-string . arg-procs
987 Layout each trace line using @var{format-string} and @var{arg-procs}.
988 For each trace line, the list of values to be printed is obtained by
989 calling all the @var{arg-procs}, passing the trap context as the only
990 parameter to each one. This list of values is then formatted using
991 the specified @var{format-string}.
992 @end deffn
993
994 @noindent
995 The @code{(ice-9 debugging trace)} module exports a set of arg-proc
996 procedures to cover most common needs, with names beginning
997 @code{trace/}. These are all implemented on top of the @code{tc:} trap
998 context accessor procedures documented in @ref{Trap Context}, and if any
999 trace output not provided by the following is needed, it should be
1000 possible to implement based on a combination of the @code{tc:}
1001 procedures.
1002
1003 @deffn {Procedure} trace/pid trap-context
1004 An arg-proc that returns the current process ID.
1005 @end deffn
1006
1007 @deffn {Procedure} trace/stack-id trap-context
1008 An arg-proc that returns the stack ID of the stack in which the
1009 current trap occurred.
1010 @end deffn
1011
1012 @deffn {Procedure} trace/stack-depth trap-context
1013 An arg-proc that returns the length (including non-real frames) of the
1014 stack at the point of the current trap.
1015 @end deffn
1016
1017 @deffn {Procedure} trace/stack-real-depth trap-context
1018 An arg-proc that returns the length excluding non-real frames of the
1019 stack at the point of the current trap.
1020 @end deffn
1021
1022 @deffn {Procedure} trace/stack trap-context
1023 An arg-proc that returns a string summarizing stack information. This
1024 string includes the stack ID, real depth, and count of additional
1025 non-real frames, with the format @code{"~a:~a+~a"}.
1026 @end deffn
1027
1028 @deffn {Procedure} trace/source-file-name trap-context
1029 An arg-proc that returns the name of the source file for the innermost
1030 stack frame, or an empty string if source is not available for the
1031 innermost frame.
1032 @end deffn
1033
1034 @deffn {Procedure} trace/source-line trap-context
1035 An arg-proc that returns the line number of the source code for the
1036 innermost stack frame, or zero if source is not available for the
1037 innermost frame.
1038 @end deffn
1039
1040 @deffn {Procedure} trace/source-column trap-context
1041 An arg-proc that returns the column number of the start of the source
1042 code for the innermost stack frame, or zero if source is not available
1043 for the innermost frame.
1044 @end deffn
1045
1046 @deffn {Procedure} trace/source trap-context
1047 An arg-proc that returns the source location for the innermost stack
1048 frame. This is a string composed of file name, line and column number
1049 with the format @code{"~a:~a:~a"}, or an empty string if source is not
1050 available for the innermost frame.
1051 @end deffn
1052
1053 @deffn {Procedure} trace/type trap-context
1054 An arg-proc that returns a three letter abbreviation indicating the
1055 type of the current trap: @code{"APP"} for an application frame,
1056 @code{"EVA"} for an evaluation, @code{"RET"} for an exit trap, or
1057 @code{"ERR"} for an error (pseudo-)trap.
1058 @end deffn
1059
1060 @deffn {Procedure} trace/real? trap-context
1061 An arg-proc that returns @code{" "} if the innermost stack frame is a
1062 real frame, or @code{"t"} if it is not.
1063 @end deffn
1064
1065 @deffn {Procedure} trace/info trap-context
1066 An arg-proc that returns a string describing the expression being
1067 evaluated, application being performed, or return value, according to
1068 the current trap type.
1069 @end deffn
1070
1071 @noindent
1072 @code{trace/stack-depth} and @code{trace/stack-real-depth} are identical
1073 to the trap context methods @code{tc:depth} and @code{tc:real-depth}
1074 described before (@pxref{Trap Context}), but renamed here for
1075 convenience.
1076
1077 The default trace layout, as exhibited by the examples of the previous
1078 subsubsubsection, is set by this line of code from the @code{(ice-9 debugging
1079 traps)} module:
1080
1081 @lisp
1082 (set-trace-layout "|~3@@a: ~a\n" trace/stack-real-depth trace/info)
1083 @end lisp
1084
1085 @noindent
1086 If we rerun the first of those examples, but with trace layout
1087 configured to show source location and trap type in addition, the
1088 output looks like this:
1089
1090 @lisp
1091 guile> (set-trace-layout "| ~25a ~3@@a: ~a ~a\n"
1092 trace/source
1093 trace/stack-real-depth
1094 trace/type
1095 trace/info)
1096 guile> (rev '(a b c))
1097 | standard input:29:0 2: APP [rev (a b c)]
1098 | standard input:4:21 3: APP [rev (b c)]
1099 | standard input:4:21 4: APP [rev (c)]
1100 | standard input:4:21 5: APP [rev ()]
1101 | standard input:2:9 5: RET =>()
1102 | standard input:4:13 4: RET =>(c)
1103 | standard input:4:13 3: RET =>(c b)
1104 | standard input:4:13 2: RET =>(c b a)
1105 (c b a)
1106 @end lisp
1107
1108
1109 @node Tracing and (ice-9 debug)
1110 @subsubsection Tracing and (ice-9 debug)
1111
1112 The @code{(ice-9 debug)} module provides a tracing facility
1113 (@pxref{Tracing}) that is roughly similar to that described here, but
1114 there are important differences.
1115
1116 @itemize @bullet
1117 @item
1118 The @code{(ice-9 debug)} trace gives a nice pictorial view of changes
1119 in stack depth, by using indentation like this:
1120
1121 @lisp
1122 [fact1 4]
1123 | [fact1 3]
1124 | | [fact1 2]
1125 | | | [fact1 1]
1126 | | | | [fact1 0]
1127 | | | | 1
1128 | | | 1
1129 | | 2
1130 | 6
1131 24
1132 @end lisp
1133
1134 However its output can @emph{only} show the information seen here,
1135 which corresponds to @code{(ice-9 debugging trace)}'s
1136 @code{trace/info} procedure; it cannot be configured to show other
1137 pieces of information about the trap context in the way that the
1138 @code{(ice-9 debugging trace)} implementation can.
1139
1140 @item
1141 The @code{(ice-9 debug)} trace only allows the tracing of procedure
1142 applications and their return values, whereas the @code{(ice-9 debugging
1143 trace)} implementation allows any kind of trap to be traced.
1144
1145 It's interesting to note that @code{(ice-9 debug)}'s restriction here,
1146 which might initially appear to be just a straightforward consequence
1147 of its implementation, is also somewhat dictated by its pictorial
1148 display. The use of indentation in the output relies on hooking into
1149 the low level trap calls in such a way that the trapped application
1150 entries and exits exactly balance each other. The @code{ice-9
1151 debugging trace} implementation allows traps to be installed such that
1152 entry and exit traps don't necessarily balance, which means that, in
1153 general, indentation diagrams like the one above don't work.
1154 @end itemize
1155
1156 It isn't currently possible to use both @code{(ice-9 debug)} trace and
1157 @code{(ice-9 debugging trace)} in the same Guile session, because
1158 their settings of the low level trap options conflict with each other.
1159
1160
1161 @node Traps Installing More Traps
1162 @subsubsection Traps Installing More Traps
1163
1164 Sometimes it is desirable for the behaviour at one trap to install
1165 further traps. In other words, the behaviour is something like
1166 ``Don't do much right now, but set things up to stop after two or
1167 three more steps'', or ``@dots{} when this frame completes''. This is
1168 absolutely fine. For example, it is easy to code a generic ``do
1169 so-and-so when the current frame exits'' procedure, which can be used
1170 wherever a trap context is available, as follows.
1171
1172 @lisp
1173 (define (at-exit trap-context behaviour)
1174 (install-trap (make <exit-trap>
1175 #:depth (tc:depth trap-context)
1176 #:single-shot #t
1177 #:behaviour behaviour)))
1178 @end lisp
1179
1180 To continue and pin down the example, this could then be used as part
1181 of a behaviour whose purpose was to measure the accumulated time spent
1182 in and below a specified procedure.
1183
1184 @lisp
1185 (define calls 0)
1186 (define total 0)
1187
1188 (define accumulate-time
1189 (lambda (trap-context)
1190 (set! calls (+ calls 1))
1191 (let ((entry (current-time)))
1192 (at-exit trap-context
1193 (lambda (ignored)
1194 (set! total
1195 (+ total (- (current-time)
1196 entry))))))))
1197
1198 (install-trap (make <procedure-trap>
1199 #:procedure my-proc
1200 #:behaviour accumulate-time))
1201 @end lisp
1202
1203
1204 @node Common Trap Options
1205 @subsubsection Common Trap Options
1206
1207 When creating any kind of trap object, settings for the trap being
1208 created are specified as options on the @code{make} call using syntax
1209 like this:
1210
1211 @lisp
1212 (make <@var{trap-class}>
1213 #:@var{option-keyword} @var{setting}
1214 @dots{})
1215 @end lisp
1216
1217 The following common options are provided by the base class
1218 @code{<trap>}, and so can be specified for any kind of trap.
1219
1220 @deffn {Class} <trap>
1221 Base class for trap objects.
1222 @end deffn
1223
1224 @deffn {Trap Option} #:condition thunk
1225 If not @code{#f}, this is a thunk which is called when the trap fires,
1226 to determine whether trap processing should proceed any further. If
1227 the thunk returns @code{#f}, the trap is basically suppressed.
1228 Otherwise processing continues normally. (Default value @code{#f}.)
1229 @end deffn
1230
1231 @deffn {Trap Option} #:skip-count count
1232 A count of valid (after @code{#:condition} processing) firings of this
1233 trap to skip. (Default value 0.)
1234 @end deffn
1235
1236 @deffn {Trap Option} #:single-shot boolean
1237 If not @code{#f}, this indicates that the trap should be automatically
1238 uninstalled after it has successfully fired (after @code{#:condition}
1239 and @code{#:skip-count} processing) for the first time. (Default
1240 value @code{#f}.)
1241 @end deffn
1242
1243 @deffn {Trap Option} #:behaviour behaviour-proc
1244 A trap behaviour procedure --- as discussed in the preceding subsubsection
1245 --- or a list of such procedures, in which case each procedure is
1246 called in turn when the trap fires. (Default value @code{'()}.)
1247 @end deffn
1248
1249 @deffn {Trap Option} #:repeat-identical-behaviour boolean
1250 Normally, if multiple trap objects are triggered by the same low level
1251 trap, and they request the same behaviour, it's only actually useful
1252 to do that behaviour once (per low level trap); so by default multiple
1253 requests for the same behaviour are coalesced. If this option is set
1254 other than @code{#f}, the contents of the @code{#:behaviour} option
1255 are uniquified so that they avoid being coalesced in this way.
1256 (Default value @code{#f}.)
1257 @end deffn
1258
1259
1260 @node Procedure Traps
1261 @subsubsection Procedure Traps
1262
1263 The @code{<procedure-trap>} class implements traps that are triggered
1264 upon application of a specified procedure. Instances of this class
1265 should use the @code{#:procedure} option to specify the procedure to
1266 trap on.
1267
1268 @deffn {Class} <procedure-trap>
1269 Class for traps triggered by application of a specified procedure.
1270 @end deffn
1271
1272 @deffn {Trap Option} #:procedure procedure
1273 Specifies the procedure to trap on.
1274 @end deffn
1275
1276 @noindent
1277 Example:
1278
1279 @lisp
1280 (install-trap (make <procedure-trap>
1281 #:procedure my-proc
1282 #:behaviour (list trace-trap
1283 trace-until-exit)))
1284 @end lisp
1285
1286
1287 @node Exit Traps
1288 @subsubsection Exit Traps
1289
1290 The @code{<exit-trap>} class implements traps that are triggered upon
1291 stack frame exit past a specified stack depth. Instances of this
1292 class should use the @code{#:depth} option to specify the target stack
1293 depth.
1294
1295 @deffn {Class} <exit-trap>
1296 Class for traps triggered by exit past a specified stack depth.
1297 @end deffn
1298
1299 @deffn {Trap Option} #:depth depth
1300 Specifies the reference depth for the trap.
1301 @end deffn
1302
1303 @noindent
1304 Example:
1305
1306 @lisp
1307 (define (trace-at-exit trap-context)
1308 (install-trap (make <exit-trap>
1309 #:depth (tc:depth trap-context)
1310 #:single-shot #t
1311 #:behaviour trace-trap)))
1312 @end lisp
1313
1314 @noindent
1315 (This is the actual definition of the @code{trace-at-exit} behaviour.)
1316
1317
1318 @node Entry Traps
1319 @subsubsection Entry Traps
1320
1321 The @code{<entry-trap>} class implements traps that are triggered upon
1322 any stack frame entry. No further parameters are needed to specify an
1323 instance of this class, so there are no class-specific trap options.
1324 Note that it remains possible to use the common trap options
1325 (@pxref{Common Trap Options}), for example to set a trap for the
1326 @var{n}th next frame entry.
1327
1328 @deffn {Class} <entry-trap>
1329 Class for traps triggered by any stack frame entry.
1330 @end deffn
1331
1332 @noindent
1333 Example:
1334
1335 @lisp
1336 (install-trap (make <entry-trap>
1337 #:skip-count 5
1338 #:behaviour gds-debug-trap))
1339 @end lisp
1340
1341
1342 @node Apply Traps
1343 @subsubsection Apply Traps
1344
1345 The @code{<apply-trap>} class implements traps that are triggered upon
1346 any procedure application. No further parameters are needed to
1347 specify an instance of this class, so there are no class-specific trap
1348 options. Note that it remains possible to use the common trap options
1349 (@pxref{Common Trap Options}), for example to set a trap for the next
1350 application where some condition is true.
1351
1352 @deffn {Class} <apply-trap>
1353 Class for traps triggered by any procedure application.
1354 @end deffn
1355
1356 @noindent
1357 Example:
1358
1359 @lisp
1360 (install-trap (make <apply-trap>
1361 #:condition my-condition
1362 #:behaviour gds-debug-trap))
1363 @end lisp
1364
1365
1366 @node Step Traps
1367 @subsubsection Step Traps
1368
1369 The @code{<step-trap>} class implements traps that do single-stepping
1370 through a program's execution. They come in two flavours, with and
1371 without a specified file name. If a file name is specified, the trap
1372 is triggered by the next evaluation, application or frame exit
1373 pertaining to source code from the specified file. If a file name is
1374 not specified, the trap is triggered by the next evaluation,
1375 application or frame exit from any file (or for code whose source
1376 location was not recorded), in other words by the next evaluator step
1377 of any kind.
1378
1379 The design goal of the @code{<step-trap>} class is to match what a
1380 user would intuitively think of as single-stepping through their code,
1381 either through code in general (roughly corresponding to GDB's
1382 @code{step} command, for example), or through code from a particular
1383 source file (roughly corresponding to GDB's @code{next}). Therefore
1384 if you are using a step trap to single-step through code and finding
1385 its behaviour counter-intuitive, please report that so we can improve
1386 it.
1387
1388 The implementation and options of the @code{<step-trap>} class are
1389 complicated by the fact that it is unreliable to determine whether a
1390 low level frame exit trap is applicable to a specified file by
1391 examining the details of the reported frame. This is a consequence of
1392 tail recursion, which has the effect that many frames can be removed
1393 from the stack at once, with only the outermost frame being reported
1394 by the low level trap call. The effects of this on the
1395 @code{<step-trap>} class are such as to require the introduction of
1396 the strange-looking @code{#:exit-depth} option, for the following
1397 reasons.
1398
1399 @itemize @bullet
1400 @item
1401 When stopped at the start of an application or evaluation frame, and
1402 it is desired to continue execution until the next ``step'' in the same
1403 source file, that next step could be the start of a nested application
1404 or evaluation frame, or --- if the procedure definition is in a
1405 different file, for example --- it could be the exit from the current
1406 frame.
1407
1408 @item
1409 Because of the effects of tail recursion noted above, the current
1410 frame exit possibility must be expressed as frame exit past a
1411 specified stack depth. When an instance of the @code{<step-trap>}
1412 class is installed from the context of an application or evaluation
1413 frame entry, the @code{#:exit-depth} option should be used to specify
1414 this stack depth.
1415
1416 @item
1417 When stopped at a frame exit, on the other hand, we know that the next
1418 step must be an application or evaluation frame entry. In this
1419 context the @code{#:exit-depth} option is not needed and should be
1420 omitted or set to @code{#f}.
1421 @end itemize
1422
1423 @noindent
1424 When a step trap is installed without @code{#:single-shot #t}, such
1425 that it keeps firing, the @code{<step-trap>} code automatically
1426 updates its idea of the @code{#:exit-depth} setting each time, so that
1427 the trap always fires correctly for the following step.
1428
1429 @deffn {Class} <step-trap>
1430 Class for single-stepping traps.
1431 @end deffn
1432
1433 @deffn {Trap Option} #:file-name name
1434 If not @code{#f}, this is a string containing the name of a source
1435 file, and restricts the step trap to evaluation steps within that
1436 source file. (Default value @code{#f}.)
1437 @end deffn
1438
1439 @deffn {Trap Option} #:exit-depth depth
1440 If not @code{#f}, this is a positive integer implying that the next
1441 step may be frame exit past the stack depth @var{depth}. See the
1442 discussion above for more details. (Default value @code{#f}.)
1443 @end deffn
1444
1445 @noindent
1446 Example:
1447
1448 @lisp
1449 (install-trap (make <step-trap>
1450 #:file-name (frame-file-name
1451 (stack-ref stack index))
1452 #:exit-depth (- (stack-length stack)
1453 (stack-ref stack index))
1454 #:single-shot #t
1455 #:behaviour debug-trap))
1456 @end lisp
1457
1458
1459 @node Source Traps
1460 @subsubsection Source Traps
1461
1462 The @code{<source-trap>} class implements traps that are attached to a
1463 precise source code expression, as read by the reader, and which fire
1464 each time that that expression is evaluated. These traps use a low
1465 level Guile feature which can mark individual expressions for
1466 trapping, and are relatively efficient. But it can be tricky to get
1467 at the source expression in the first place, and these traps are
1468 liable to become irrelevant if the procedure containing the expression
1469 is reevaluated; these issues are discussed further below.
1470
1471 @deffn {Class} <source-trap>
1472 Class for traps triggered by evaluation of a specific Scheme
1473 expression.
1474 @end deffn
1475
1476 @deffn {Trap Option} #:expression expr
1477 Specifies the Scheme expression to trap on.
1478 @end deffn
1479
1480 @noindent
1481 Example:
1482
1483 @lisp
1484 (display "Enter an expression: ")
1485 (let ((x (read)))
1486 (install-trap (make <source-trap>
1487 #:expression x
1488 #:behaviour (list trace-trap
1489 trace-at-exit)))
1490 (primitive-eval x))
1491 @print{}
1492 Enter an expression: (+ 1 2 3 4 5 6)
1493 | 3: (+ 1 2 3 4 5 6)
1494 | 3: =>21
1495 21
1496 @end lisp
1497
1498 The key point here is that the expression specified by the
1499 @code{#:expression} option must be @emph{exactly} (i.e. @code{eq?} to)
1500 what is going to be evaluated later. It doesn't work, for example, to
1501 say @code{#:expression '(+ x 3)}, with the expectation that the trap
1502 will fire whenever evaluating any expression @code{(+ x 3)}.
1503
1504 The @code{trap-here} macro can be used in source code to create and
1505 install a source trap correctly. Take for example the factorial
1506 function defined in the @code{(ice-9 debugging example-fns)} module:
1507
1508 @lisp
1509 (define (fact1 n)
1510 (if (= n 0)
1511 1
1512 (* n (fact1 (- n 1)))))
1513 @end lisp
1514
1515 @noindent
1516 To set a source trap on a particular expression --- let's say the
1517 expression @code{(= n 0)} --- edit the code so that the expression is
1518 enclosed in a @code{trap-here} macro call like this:
1519
1520 @lisp
1521 (define (fact1 n)
1522 (if (trap-here (= n 0) #:behaviour debug-trap)
1523 1
1524 (* n (fact1 (- n 1)))))
1525 @end lisp
1526
1527 @deffn {Macro} trap-here expression . trap-options
1528 Install a source trap with options @var{trap-options} on
1529 @var{expression}, then return with the whole call transformed to
1530 @code{(begin @var{expression})}.
1531 @end deffn
1532
1533 Note that if the @code{trap-here} incantation is removed, and
1534 @code{fact1} then redefined by reloading its source file, the effect
1535 of the source trap is lost, because the text ``(= n 0)'' is read again
1536 from scratch and becomes a new expression @code{(= n 0)} which does
1537 not have the ``trap here'' mark on it.
1538
1539 If the semantics and setting of source traps seem unwieldy, location
1540 traps may meet your need more closely; these are described in the
1541 following subsubsection.
1542
1543
1544 @node Location Traps
1545 @subsubsection Location Traps
1546
1547 The @code{<location-trap>} class implements traps that are triggered
1548 by evaluation of code at a specific source location. When compared
1549 with source traps, they are easier to set, and do not become
1550 irrelevant when the relevant code is reloaded; but unfortunately they
1551 are a lot less efficient, as they require running some ``are we in the
1552 right place for a trap'' code on every low level frame entry trap
1553 call.
1554
1555 @deffn {Class} <location-trap>
1556 Class for traps triggered by evaluation of code at a specific source
1557 location.
1558 @end deffn
1559
1560 @deffn {Trap Option} #:file-regexp regexp
1561 A regular expression specifying the filenames that will match this
1562 trap. This option must be specified when creating a location trap.
1563 @end deffn
1564
1565 @deffn {Trap Option} #:line line
1566 The line number (0-based) of the source location at which the trap
1567 should be triggered. This option must be specified when creating a
1568 location trap.
1569 @end deffn
1570
1571 @deffn {Trap Option} #:column column
1572 The column number (0-based) of the source location at which the trap
1573 should be triggered. This option must be specified when creating a
1574 location trap.
1575 @end deffn
1576
1577 @noindent
1578 Here is an example, which matches the @code{(facti (- n 1) (* a n))}
1579 expression in @file{ice-9/debugging/example-fns.scm}:
1580
1581 @lisp
1582 (install-trap (make <location-trap>
1583 #:file-regexp "example-fns.scm"
1584 #:line 11
1585 #:column 6
1586 #:behaviour gds-debug-trap))
1587 @end lisp
1588
1589
1590 @node Trap Shorthands
1591 @subsubsection Trap Shorthands
1592
1593 If the code described in the preceding subsubsections for creating and
1594 manipulating traps seems a little long-winded, it is of course
1595 possible to define more convenient shorthand forms for typical usage
1596 patterns. Here are some examples.
1597
1598 @lisp
1599 (define (break! proc)
1600 (install-trap (make <procedure-trap>
1601 #:procedure proc
1602 #:behaviour gds-debug-trap)))
1603
1604 (define (trace! proc)
1605 (install-trap (make <procedure-trap>
1606 #:procedure proc
1607 #:behaviour (list trace-trap
1608 trace-at-exit))))
1609
1610 (define (trace-subtree! proc)
1611 (install-trap (make <procedure-trap>
1612 #:procedure proc
1613 #:behaviour (list trace-trap
1614 trace-until-exit))))
1615 @end lisp
1616
1617 Definitions like these are not provided out-of-the-box by Guile,
1618 because different users will have different ideas about what their
1619 default debugger should be, or, for example, which of the common trap
1620 options (@pxref{Common Trap Options}) it might be useful to expose
1621 through such shorthand procedures.
1622
1623
1624 @node Trap Utilities
1625 @subsubsection Trap Utilities
1626
1627 @code{list-traps} can be used to print a description of all known trap
1628 objects. This uses a weak value hash table, keyed by a trap index
1629 number. Each trap object has its index number assigned, and is added
1630 to the hash table, when it is created by a @code{make @var{trap-class}
1631 @dots{}} call. When a trap object is GC'd, it is automatically
1632 removed from the hash table, and so no longer appears in the output
1633 from @code{list-traps}.
1634
1635 @deffn {Variable} all-traps
1636 Weak value hash table containing all known trap objects.
1637 @end deffn
1638
1639 @deffn {Procedure} list-traps
1640 Print a description of all known trap objects.
1641 @end deffn
1642
1643 The following example shows a single trap that traces applications of
1644 the procedure @code{facti}.
1645
1646 @lisp
1647 guile> (list-traps)
1648 #<<procedure-trap> 100d2e30> is an instance of class <procedure-trap>
1649 Slots are:
1650 number = 1
1651 installed = #t
1652 condition = #f
1653 skip-count = 0
1654 single-shot = #f
1655 behaviour = (#<procedure trace-trap (trap-context)>)
1656 repeat-identical-behaviour = #f
1657 procedure = #<procedure facti (n a)>
1658 @end lisp
1659
1660 When @code{all-traps} or @code{list-traps} reveals a trap that you
1661 want to modify but no longer have a reference to, you can retrieve the
1662 trap object by calling @code{get-trap} with the trap's number. For
1663 example, here's how you could change the behaviour of the trap listed
1664 just above.
1665
1666 @lisp
1667 (slot-set! (get-trap 1) 'behaviour (list debug-trap))
1668 @end lisp
1669
1670 @deffn {Procedure} get-trap number
1671 Return the trap object with the specified @var{number}, or @code{#f}
1672 if there isn't one.
1673 @end deffn
1674
1675
1676 @node Debugging Examples
1677 @subsection Debugging Examples
1678
1679 Here we present some examples of what you can do with the debugging
1680 facilities just described.
1681
1682 @menu
1683 * Single Stepping through a Procedure's Code::
1684 * Profiling or Tracing a Procedure's Code::
1685 @end menu
1686
1687
1688 @node Single Stepping through a Procedure's Code
1689 @subsubsection Single Stepping through a Procedure's Code
1690
1691 A good way to explore in detail what a Scheme procedure does is to set
1692 a trap on it and then single step through what it does. To do this,
1693 make and install a @code{<procedure-trap>} with the @code{debug-trap}
1694 behaviour from @code{(ice-9 debugger)}.
1695
1696 The following sample session illustrates this. It assumes that the
1697 file @file{matrix.scm} defines a procedure @code{mkmatrix}, which is
1698 the one we want to explore, and another procedure @code{do-main} which
1699 calls @code{mkmatrix}.
1700
1701 @lisp
1702 $ /usr/bin/guile -q
1703 guile> (use-modules (ice-9 debugger)
1704 (ice-9 debugging traps))
1705 guile> (load "matrix.scm")
1706 guile> (install-trap (make <procedure-trap>
1707 #:procedure mkmatrix
1708 #:behaviour debug-trap))
1709 guile> (do-main 4)
1710 This is the Guile debugger -- for help, type `help'.
1711 There are 3 frames on the stack.
1712
1713 Frame 2 at matrix.scm:8:3
1714 [mkmatrix]
1715 debug> next
1716 Frame 3 at matrix.scm:4:3
1717 (let ((x 1)) (quote hi!))
1718 debug> info frame
1719 Stack frame: 3
1720 This frame is an evaluation.
1721 The expression being evaluated is:
1722 matrix.scm:4:3:
1723 (let ((x 1)) (quote hi!))
1724 debug> next
1725 Frame 3 at matrix.scm:5:21
1726 (quote hi!)
1727 debug> bt
1728 In unknown file:
1729 ?: 0* [primitive-eval (do-main 4)]
1730 In standard input:
1731 4: 1* [do-main 4]
1732 In matrix.scm:
1733 8: 2 [mkmatrix]
1734 ...
1735 5: 3 (quote hi!)
1736 debug> quit
1737 hi!
1738 guile>
1739 @end lisp
1740
1741 Or you can use Guile's Emacs interface (GDS), by using the module
1742 @code{(ice-9 gds-client)} instead of @code{(ice-9 debugger)} and
1743 changing @code{debug-trap} to @code{gds-debug-trap}. Then the stack and
1744 corresponding source locations are displayed in Emacs instead of on the
1745 Guile command line.
1746
1747
1748 @node Profiling or Tracing a Procedure's Code
1749 @subsubsection Profiling or Tracing a Procedure's Code
1750
1751 What if you wanted to get a trace of everything that the Guile
1752 evaluator does within a given procedure, but without Guile stopping
1753 and waiting for your input at every step? For this requirement you
1754 can install a trap on the procedure, as in the previous example, but
1755 instead of @code{debug-trap} or @code{gds-debug-trap}, use the
1756 @code{trace-trap} and @code{trace-until-exit} behaviours provided by
1757 the @code{(ice-9 debugging trace)} module.
1758
1759 @lisp
1760 guile> (use-modules (ice-9 debugging traps) (ice-9 debugging trace))
1761 guile> (load "matrix.scm")
1762 guile> (install-trap (make <procedure-trap>
1763 #:procedure mkmatrix
1764 #:behaviour (list trace-trap trace-until-exit)))
1765 guile> (do-main 4)
1766 | 2: [mkmatrix]
1767 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> define #f]
1768 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> define #f]
1769 | 4: (and (memq sym bindings) (let ...))
1770 | 5: (memq sym bindings)
1771 | 5: [memq define (debug)]
1772 | 5: =>#f
1773 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> define #f]
1774 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> define #f]
1775 | 4: (and (memq sym bindings) (let ...))
1776 | 5: (memq sym bindings)
1777 | 5: [memq define (debug)]
1778 | 5: =>#f
1779 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1780 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1781 | 4: (and (memq sym bindings) (let ...))
1782 | 5: (memq sym bindings)
1783 | 5: [memq let (debug)]
1784 | 5: =>#f
1785 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1786 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1787 | 4: (and (memq sym bindings) (let ...))
1788 | 5: (memq sym bindings)
1789 | 5: [memq let (debug)]
1790 | 5: =>#f
1791 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1792 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1793 | 4: (and (memq sym bindings) (let ...))
1794 | 5: (memq sym bindings)
1795 | 5: [memq let (debug)]
1796 | 5: =>#f
1797 | 2: (letrec ((yy 23)) (let ((x 1)) (quote hi!)))
1798 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1799 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1800 | 4: (and (memq sym bindings) (let ...))
1801 | 5: (memq sym bindings)
1802 | 5: [memq let (debug)]
1803 | 5: =>#f
1804 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1805 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1806 | 4: (and (memq sym bindings) (let ...))
1807 | 5: (memq sym bindings)
1808 | 5: [memq let (debug)]
1809 | 5: =>#f
1810 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1811 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1812 | 4: (and (memq sym bindings) (let ...))
1813 | 5: (memq sym bindings)
1814 | 5: [memq let (debug)]
1815 | 5: =>#f
1816 | 2: (let ((x 1)) (quote hi!))
1817 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1818 | 3: [#<procedure #f (a sym definep)> #<autoload # b7c93870> let #f]
1819 | 4: (and (memq sym bindings) (let ...))
1820 | 5: (memq sym bindings)
1821 | 5: [memq let (debug)]
1822 | 5: =>#f
1823 | 2: [let (let # #) (# # #)]
1824 | 2: [let (let # #) (# # #)]
1825 | 2: =>(#@@let* (x 1) #@@let (quote hi!))
1826 hi!
1827 guile> (do-main 4)
1828 | 2: [mkmatrix]
1829 | 2: (letrec ((yy 23)) (let* ((x 1)) (quote hi!)))
1830 | 2: (let* ((x 1)) (quote hi!))
1831 | 2: (quote hi!)
1832 | 2: =>hi!
1833 hi!
1834 guile>
1835 @end lisp
1836
1837 This example shows the default configuration for how each line of trace
1838 output is formatted, which is:
1839
1840 @itemize
1841 @item
1842 the character @code{|}, a visual clue that the line is a line of trace
1843 output, followed by
1844
1845 @item
1846 a number indicating the real evaluator stack depth (where ``real'' means
1847 not counting tail-calls), followed by
1848
1849 @item
1850 a summary of the expression being evaluated (@code{(@dots{})}), the
1851 procedure being called (@code{[@dots{}]}), or the value being returned
1852 from an evaluation or procedure call (@code{=>@dots{}}).
1853 @end itemize
1854
1855 @noindent
1856 You can customize @code{(ice-9 debugging trace)} to show different
1857 information in each trace line using the @code{set-trace-layout}
1858 procedure. The next example shows how to get the source location in
1859 each trace line instead of the stack depth.
1860
1861 @lisp
1862 guile> (set-trace-layout "|~16@@a: ~a\n" trace/source trace/info)
1863 guile> (do-main 4)
1864 | matrix.scm:7:2: [mkmatrix]
1865 | : (letrec ((yy 23)) (let* ((x 1)) (quote hi!)))
1866 | matrix.scm:3:2: (let* ((x 1)) (quote hi!))
1867 | matrix.scm:4:4: (quote hi!)
1868 | matrix.scm:4:4: =>hi!
1869 hi!
1870 guile>
1871 @end lisp
1872
1873 @c Local Variables:
1874 @c TeX-master: "guile.texi"
1875 @c End: