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