finish cleaning out api-options.texi
[bpt/guile.git] / doc / ref / api-debug.texi
CommitLineData
07d83abe
MV
1@c -*-texinfo-*-
2@c This is part of the GNU Guile Reference Manual.
e10cf6b9 3@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2007, 2010
07d83abe
MV
4@c Free Software Foundation, Inc.
5@c See the file guile.texi for copying conditions.
6
07d83abe
MV
7@node Debugging
8@section Debugging Infrastructure
9
b20ef3a6 10@cindex Debugging
5af872e1 11In order to understand Guile's debugging facilities, you first need to
42cb9b03 12understand a little about how Guile represent the Scheme control stack.
a1652dec
AW
13With that in place we explain the low level trap calls that the virtual
14machine can be configured to make, and the trap and breakpoint
5af872e1
NJ
15infrastructure that builds on top of those calls.
16
07d83abe 17@menu
5af872e1
NJ
18* Evaluation Model:: Evaluation and the Scheme stack.
19* Debug on Error:: Debugging when an error occurs.
24dbb5ed 20* Traps::
24dbb5ed 21* Debugging Examples::
5af872e1
NJ
22@end menu
23
24@node Evaluation Model
25@subsection Evaluation and the Scheme Stack
26
42cb9b03
AW
27The idea of the Scheme stack is central to a lot of debugging. The
28Scheme stack is a reified representation of the pending function returns
a1652dec 29in an expression's continuation. As Guile implements function calls
42cb9b03 30using a stack, this reification takes the form of a number of nested
a1652dec
AW
31stack frames, each of which corresponds to the application of a
32procedure to a set of arguments.
42cb9b03
AW
33
34A Scheme stack always exists implicitly, and can be summoned into
35concrete existence as a first-class Scheme value by the
36@code{make-stack} call, so that an introspective Scheme program -- such
37as a debugger -- can present it in some way and allow the user to query
38its details. The first thing to understand, therefore, is how Guile's
39function call convention creates the stack.
40
41Broadly speaking, Guile represents all control flow on a stack. Calling
42a function involves pushing an empty frame on the stack, then evaluating
43the procedure and its arguments, then fixing up the new frame so that it
44points to the old one. Frames on the stack are thus linked together. A
45tail call is the same, except it reuses the existing frame instead of
46pushing on a new one.
47
48In this way, the only frames that are on the stack are ``active''
49frames, frames which need to do some work before the computation is
50complete. On the other hand, a function that has tail-called another
51function will not be on the stack, as it has no work left to do.
5af872e1
NJ
52
53Therefore, when an error occurs in a running program, or the program
54hits a breakpoint, or in fact at any point that the programmer chooses,
55its state at that point can be represented by a @dfn{stack} of all the
a1652dec
AW
56procedure applications that are logically in progress at that time, each
57of which is known as a @dfn{frame}. The programmer can learn more about
58the program's state at that point by inspecting the stack and its
59frames.
5af872e1
NJ
60
61@menu
07d83abe
MV
62* Capturing the Stack or Innermost Stack Frame::
63* Examining the Stack::
64* Examining Stack Frames::
5af872e1 65* Source Properties:: Remembering the source of an expression.
07d83abe
MV
66* Starting a New Stack::
67@end menu
68
07d83abe 69@node Capturing the Stack or Innermost Stack Frame
5af872e1 70@subsubsection Capturing the Stack or Innermost Stack Frame
07d83abe 71
5af872e1
NJ
72A Scheme program can use the @code{make-stack} primitive anywhere in its
73code, with first arg @code{#t}, to construct a Scheme value that
74describes the Scheme stack at that point.
75
76@lisp
77(make-stack #t)
78@result{}
a1652dec 79#<stack 25205a0>
5af872e1 80@end lisp
07d83abe
MV
81
82@deffn {Scheme Procedure} make-stack obj . args
83@deffnx {C Function} scm_make_stack (obj, args)
84Create a new stack. If @var{obj} is @code{#t}, the current
85evaluation stack is used for creating the stack frames,
86otherwise the frames are taken from @var{obj} (which must be
42cb9b03 87a continuation or a frame object).
07d83abe
MV
88
89@var{args} should be a list containing any combination of
42cb9b03 90integer, procedure, prompt tag and @code{#t} values.
07d83abe
MV
91
92These values specify various ways of cutting away uninteresting
93stack 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
42cb9b03
AW
98Each @var{inner_cut_N} can be @code{#t}, an integer, a prompt
99tag, or a procedure. @code{#t} means to cut away all frames up
100to but excluding the first user module frame. An integer means
101to cut away exactly that number of frames. A prompt tag means
102to cut away all frames that are inside a prompt with the given
103tag. A procedure means to cut away all frames up to but
104excluding the application frame whose procedure matches the
105specified one.
106
107Each @var{outer_cut_N} can be an integer, a prompt tag, or a
108procedure. An integer means to cut away that number of frames.
109A prompt tag means to cut away all frames that are outside a
110prompt with the given tag. A procedure means to cut away
111frames down to but excluding the application frame whose
07d83abe
MV
112procedure matches the specified one.
113
07d83abe
MV
114If the @var{outer_cut_N} of the last pair is missing, it is
115taken as 0.
116@end deffn
117
07d83abe
MV
118
119@node Examining the Stack
5af872e1 120@subsubsection Examining the Stack
07d83abe
MV
121
122@deffn {Scheme Procedure} stack? obj
123@deffnx {C Function} scm_stack_p (obj)
124Return @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)
129Return 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)
134Return 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)
139Return the @var{index}'th frame from @var{stack}.
140@end deffn
141
7cd44c6d
MV
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)
07d83abe 144@deffnx {C Function} scm_display_backtrace (stack, port, first, depth)
fc3d5c43 145Display a backtrace to the output port @var{port}. @var{stack}
07d83abe 146is the stack to take the backtrace from, @var{first} specifies
fc3d5c43
NJ
147where in the stack to start and @var{depth} how many frames
148to display. @var{first} and @var{depth} can be @code{#f},
07d83abe 149which means that default values will be used.
fc3d5c43
NJ
150If @var{highlights} is given it should be a list; the elements
151of this list will be highlighted wherever they appear in the
152backtrace.
07d83abe
MV
153@end deffn
154
155
156@node Examining Stack Frames
5af872e1 157@subsubsection Examining Stack Frames
07d83abe
MV
158
159@deffn {Scheme Procedure} frame? obj
160@deffnx {C Function} scm_frame_p (obj)
161Return @code{#t} if @var{obj} is a stack frame.
162@end deffn
163
07d83abe
MV
164@deffn {Scheme Procedure} frame-previous frame
165@deffnx {C Function} scm_frame_previous (frame)
166Return the previous frame of @var{frame}, or @code{#f} if
167@var{frame} is the first frame in its stack.
168@end deffn
169
07d83abe
MV
170@deffn {Scheme Procedure} frame-procedure frame
171@deffnx {C Function} scm_frame_procedure (frame)
172Return the procedure for @var{frame}, or @code{#f} if no
173procedure is associated with @var{frame}.
174@end deffn
175
176@deffn {Scheme Procedure} frame-arguments frame
177@deffnx {C Function} scm_frame_arguments (frame)
178Return the arguments of @var{frame}.
179@end deffn
180
07d83abe
MV
181@deffn {Scheme Procedure} display-application frame [port [indent]]
182@deffnx {C Function} scm_display_application (frame, port, indent)
183Display a procedure application @var{frame} to the output port
184@var{port}. @var{indent} specifies the indentation of the
185output.
186@end deffn
187
188
5af872e1
NJ
189@node Source Properties
190@subsubsection Source Properties
191
192@cindex source properties
193As Guile reads in Scheme code from file or from standard input, it
194remembers the file name, line number and column number where each
42cb9b03
AW
195expression begins. These pieces of information are known as the
196@dfn{source properties} of the expression. Syntax expanders and the
197compiler propagate these source properties to compiled procedures, so
198that, if an error occurs when evaluating the transformed expression,
199Guile's debugger can point back to the file and location where the
200expression originated.
5af872e1
NJ
201
202The way that source properties are stored means that Guile can only
203associate source properties with parenthesized expressions, and not, for
204example, with individual symbols, numbers or strings. The difference
205can 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
a1652dec
AW
209scheme@@(guile-user)> (xxx)
210<unnamed port>:4:1: In procedure module-lookup:
211<unnamed port>:4:1: Unbound variable: xxx
212
213scheme@@(guile-user)> xxx
214ERROR: In procedure module-lookup:
215ERROR: Unbound variable: xxx
5af872e1
NJ
216@end example
217
218@noindent
a1652dec
AW
219In the latter case, no source properties were stored, so the error
220doesn't have any source information.
5af872e1
NJ
221
222The recording of source properties is controlled by the read option
1518f649 223named ``positions'' (@pxref{Scheme Read}). This option is switched
42cb9b03 224@emph{on} by default.
5af872e1
NJ
225
226The following procedures can be used to access and set the source
227properties of read expressions.
228
916f175f
NJ
229@deffn {Scheme Procedure} set-source-properties! obj alist
230@deffnx {C Function} scm_set_source_properties_x (obj, alist)
231Install the association list @var{alist} as the source property
5af872e1
NJ
232list 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)
237Set 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)
243Return 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)
916f175f
NJ
248Return the property specified by @var{key} from @var{obj}'s source
249properties.
5af872e1
NJ
250@end deffn
251
42cb9b03
AW
252If the @code{positions} reader option is enabled, each parenthesized
253expression will have values set for the @code{filename}, @code{line} and
254@code{column} properties.
5af872e1 255
1fc8dcc7
AW
256If you're stuck with defmacros (@pxref{Defmacros}), and want to preserve
257source information, the following helper function might be useful to
258you:
07d83abe 259
1fc8dcc7
AW
260@deffn {Scheme Procedure} cons-source xorig x y
261@deffnx {C Function} scm_cons_source (xorig, x, y)
262Create and return a new pair whose car and cdr are @var{x} and @var{y}.
263Any source properties associated with @var{xorig} are also associated
264with the new pair.
07d83abe
MV
265@end deffn
266
267
268@node Starting a New Stack
5af872e1 269@subsubsection Starting a New Stack
07d83abe
MV
270
271@deffn {Scheme Syntax} start-stack id exp
272Evaluate @var{exp} on a new calling stack with identity @var{id}. If
273@var{exp} is interrupted during evaluation, backtraces will not display
274frames farther back than @var{exp}'s top-level form. This macro is a
275way of artificially limiting backtraces and stack procedures, largely as
276a convenience to the user.
277@end deffn
278
279
5af872e1
NJ
280@node Debug on Error
281@subsection Debugging when an error occurs
282
2202fd6c
NJ
283A common requirement is to be able to show as much useful context as
284possible when a Scheme program hits an error. The most immediate
285information 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
287the error chose explicitly to provide. This information originates with
288the @code{error} or @code{throw} call (or their C code equivalents, if
289the error is detected by C code) that signals the error, and is passed
290automatically to the handler procedure of the innermost applicable
42cb9b03 291@code{catch} or @code{with-throw-handler} expression.
2202fd6c
NJ
292
293@subsubsection Intercepting basic error information
294
295Therefore, to catch errors that occur within a chunk of Scheme code, and
296to intercept basic information about those errors, you need to execute
42cb9b03
AW
297that code inside the dynamic context of a @code{catch} or
298@code{with-throw-handler} expression, or the equivalent in C. In Scheme,
299this means you need something like this:
2202fd6c
NJ
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
e10cf6b9
AW
314The @code{catch} here can also be @code{with-throw-handler}; see @ref{Throw
315Handlers} 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
317catch is applicable to all kinds of error; if you want to restrict your catch to
318just 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:
2202fd6c
NJ
320
321@lisp
322SCM my_body_proc (void *body_data)
323@{
324 /* Execute the code in which
325 you want to catch errors here. */
326 ...
327@}
328
fc3d5c43
NJ
329SCM my_handler_proc (void *handler_data,
330 SCM key,
331 SCM parameters)
2202fd6c
NJ
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
349Again, as with the Scheme version, @code{scm_c_catch} could be replaced
42cb9b03
AW
350by @code{scm_c_with_throw_handler}, and @code{SCM_BOOL_T} could instead
351be the symbol for a particular kind of error.
2202fd6c
NJ
352
353@subsubsection Capturing the full error stack
354
355The other interesting information about an error is the full Scheme
356stack at the point where the error occurred; in other words what
357innermost expression was being evaluated, what was the expression that
358called that one, and so on. If you want to write your code so that it
42cb9b03 359captures and can display this information as well, there are a couple
2202fd6c
NJ
360important things to understand.
361
42cb9b03 362Firstly, the stack at the point of the error needs to be explicitly
2202fd6c 363captured by a @code{make-stack} call (or the C equivalent
fc3d5c43 364@code{scm_make_stack}). The Guile library does not do this
2202fd6c
NJ
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
367this point because some people are misled by the fact that the Guile
368interactive REPL code @emph{does} capture and display the stack
369automatically. But the Guile interactive REPL is itself a Scheme
370program@footnote{In effect, it is the default program which is run when
371no commands or script file are specified on the Guile command line.}
372running 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
374stack when an error occurs.)
375
42cb9b03
AW
376And secondly, in order to capture the stack effectively at the point
377where the error occurred, the @code{make-stack} call must be made before
378Guile unwinds the stack back to the location of the prevailing catch
379expression. This means that the @code{make-stack} call must be made
380within the handler of a @code{with-throw-handler} expression, or the
381optional "pre-unwind" handler of a @code{catch}. (For the full story of
382how these alternatives differ from each other, see @ref{Exceptions}. The
383main difference is that @code{catch} terminates the error, whereas
384@code{with-throw-handler} only intercepts it temporarily and then allow
fc3d5c43
NJ
385it to continue propagating up to the next innermost handler.)
386
387So, here are some examples of how to do all this in Scheme and in C.
388For the purpose of these examples we assume that the captured stack
389should be stored in a variable, so that it can be displayed or
390arbitrarily 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
416And in C:
417
418@lisp
419SCM my_body_proc (void *body_data)
420@{
421 /* Execute the code in which
422 you want to catch errors here. */
423 ...
424@}
425
426SCM 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
436SCM 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
462Note 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
464the stack immediately after it has been captured in the pre-unwind
465handler, or in the normal (post-unwind) handler. (Except that for the
466latter 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
472Once you have a captured stack, you can interrogate and display its
473details 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
477If you want to print out a backtrace in the same format that the Guile
478REPL does, you can use the @code{display-backtrace} procedure to do so.
479You can also use @code{display-application} to display an individual
480application 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
42cb9b03
AW
485The Guile REPL code (in @file{system/repl/repl.scm} and related files)
486uses a @code{catch} with a pre-unwind handler to capture the stack when
487an error occurs in an expression that was typed into the REPL, and saves
488the captured stack in a fluid (@pxref{Fluids and Dynamic States}) called
489@code{the-last-stack}. You can then use the @code{(backtrace)} command,
5b2da4cc
NJ
490which is basically equivalent to @code{(display-backtrace (fluid-ref
491the-last-stack))}, to print out this stack at any time until it is
492overwritten by the next error that occurs.
fc3d5c43 493
5af872e1
NJ
494@deffn {Scheme Procedure} backtrace [highlights]
495@deffnx {C Function} scm_backtrace_with_highlights (highlights)
496@deffnx {C Function} scm_backtrace ()
497Display a backtrace of the stack saved by the last error
fc3d5c43
NJ
498to the current output port. If @var{highlights} is given
499it should be a list; the elements of this list will be
500highlighted wherever they appear in the backtrace.
5af872e1
NJ
501@end deffn
502
5b2da4cc
NJ
503You can also use the @code{(debug)} command to explore the saved stack
504using an interactive command-line-driven debugger. See @ref{Interactive
3c0b7725 505Debugging} for more information about this.
5b2da4cc 506
5af872e1
NJ
507@deffn {Scheme Procedure} debug
508Invoke the Guile debugger to explore the context of the last error.
509@end deffn
510
1cfdb1bb
AW
511@subsubsection Debug options
512
513The behavior when an error is the @code{backtrace} procedure and of the
514default 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]
519Display the current settings of the debug options. If @var{setting} is
520omitted, only a short form of the current read options is printed.
521Otherwise if @var{setting} is the symbol @code{help}, a complete options
522description is displayed.
523@end deffn
524
525The set of available options, and their default values, may be had by
526invoking @code{debug-options} at the prompt.
527
528@smallexample
529scheme@@(guile-user)>
530backwards no Display backtrace in anti-chronological order.
531width 79 Maximal width of backtrace.
532depth 20 Maximal length of printed backtrace.
533backtrace yes Show backtrace on error.
534stack 1048576 Stack size limit (measured in words;
535 0 = no check).
536show-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.
539warn-deprecated no Warn when deprecated features are used.
540@end smallexample
541
542The boolean options may be toggled with @code{debug-enable} and
543@code{debug-disable}. The non-boolean @code{keywords} option must be set
544using @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
549Modify the debug options. @code{debug-enable} should be used with boolean
550options 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
558Stack overflow errors are caused by a computation trying to use more
559stack space than has been enabled by the @code{stack} option. They are
560reported like this:
561
562@lisp
563(non-tail-recursive-factorial 500)
564@print{}
565ERROR: Stack overflow
566ABORT: (stack-overflow)
567@end lisp
568
569If you get an error like this, you can either try rewriting your code to
570use less stack space, or increase the maximum stack size. To increase
571the 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{}
581122013682599111006870123878542304692625357434@dots{}
582@end lisp
583
584If you prefer to try rewriting your code, you may be able to save stack
585space by making some of your procedures @dfn{tail recursive}
586(@pxref{Tail Calls}).
587
62ae9557 588
24dbb5ed
NJ
589@node Traps
590@subsection Traps
62ae9557
NJ
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
42cb9b03
AW
599Guile's virtual machine can be configured to call out at key points to
600arbitrary user-specified procedures. For more information on these
601hooks, and the circumstances under which the VM calls them, see @ref{VM
602Behaviour}.
603
604In principle, these hooks allow Scheme code to implement any model it
605chooses for examining the evaluation stack as program execution
606proceeds, and for suspending execution to be resumed later. Possible
607applications of this feature include breakpoints, runtime tracing, code
608coverage, and profiling.
62ae9557
NJ
609
610@cindex Trap classes
611@cindex Trap objects
24dbb5ed
NJ
612Based on these low level trap calls, Guile provides a higher level,
613object-oriented interface for the manipulation of traps. Different
614kinds of trap are represented as GOOPS classes; for example, the
615@code{<procedure-trap>} class describes traps that are triggered by
616invocation of a specified procedure. A particular instance of a trap
617class --- or @dfn{trap object} --- describes the condition under which
618a single trap will be triggered, and what will happen then; for
619example, an instance of @code{<procedure-trap>} whose @code{procedure}
620and @code{behaviour} slots contain @code{my-factorial} and
621@code{debug-trap} would be a trap that enters the command line
622debugger when the @code{my-factorial} procedure is invoked.
623
624The following subsections describe all this in detail, for both the
625user wanting to use traps, and the developer interested in
62ae9557
NJ
626understanding how the interface hangs together.
627
628
42cb9b03
AW
629@subsubsection Actually, this section is bitrotten
630
631Dear reader: the following sections have some great ideas, and some code
632that 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
62ae9557
NJ
637@subsubsection A Quick Note on Terminology
638
639@cindex Trap terminology
640It feels natural to use the word ``trap'' in some form for all levels
641of the structure just described, so we need to be clear on the
642terminology we use to describe each particular level. The terminology
643used 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
650directly 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
659of a trap class, and each describe a single logical trap condition
660plus behaviour as specified by the user of this interface.
661@end itemize
662
663A good example of when it is important to be clear, is when we talk
664below of behaviours that should only happen once per low level trap.
665A single low level trap call will typically map onto the processing of
666several trap objects, so ``once per low level trap'' is significantly
667different 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
696Setting a trap is done in two parts. First the trap is defined by
697creating an instance of the appropriate trap class, with slot values
698specifying the condition under which the trap will fire and the action
699to take when it fires. Secondly the trap object thus created must be
700@dfn{installed}.
701
702To make this immediately concrete, here is an example that sets a trap
703to fire on the next application of the @code{facti} procedure, and to
704handle 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
714Briefly, the elements of this incantation are as follows. (All of
715these 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
720of a specific procedure.
721
722@item
723@code{#:procedure facti} says that the specific procedure to trap on for this
724trap 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
730specified).
731
732@item
733@code{#:behaviour debug-trap} says that the trap infrastructure should
734call the procedure @code{debug-trap} when this trap fires.
735
736@item
737Finally, the @code{install-trap} call installs the trap immediately.
738@end itemize
739
740@noindent
741It is of course possible for the user to define more convenient
742shorthands for setting common kinds of traps. @xref{Trap Shorthands},
743for some examples.
744
745The ability to install, uninstall and reinstall a trap without losing
24dbb5ed
NJ
746its definition is Guile's equivalent of the disable/enable commands
747provided by debuggers like GDB.
62ae9557
NJ
748
749@deffn {Generic Function} install-trap trap
750Install the trap object @var{trap}, so that its behaviour will be
751executed when the conditions for the trap firing are met.
752@end deffn
753
754@deffn {Generic Function} uninstall-trap trap
755Uninstall the trap object @var{trap}, so that its behaviour will
756@emph{not} be executed even if the conditions for the trap firing are
757met.
758@end deffn
759
760
761@node Specifying Trap Behaviour
762@subsubsection Specifying Trap Behaviour
763
764@cindex Trap behaviour
24dbb5ed
NJ
765Guile provides several ``out-of-the-box'' behaviours for common needs.
766All of the following can be used directly as the value of the
767@code{#:behaviour} option when creating a trap object.
62ae9557
NJ
768
769@deffn {Procedure} debug-trap trap-context
770Enter Guile's command line debugger to explore the stack at
771@var{trap-context}, and to single-step or continue program execution
772from that point.
773@end deffn
774
775@deffn {Procedure} gds-debug-trap trap-context
776Use the GDS debugging interface, which displays the stack and
777corresponding source code via Emacs, to explore the stack at
778@var{trap-context} and to single-step or continue program execution
779from that point.
780@end deffn
781
782@cindex Trace
783@cindex Tracing
784@deffn {Procedure} trace-trap trap-context
785Display trace information to summarize the current @var{trap-context}.
786@end deffn
787
788@deffn {Procedure} trace-at-exit trap-context
789Install a further trap to cause the return value of the application or
790evaluation just starting (as described by @var{trap-context}) to be
791traced using @code{trace-trap}, when this application or evaluation
792completes. The extra trap is automatically uninstalled after the
793return value has been traced.
794@end deffn
795
796@deffn {Procedure} trace-until-exit trap-context
797Install a further trap so that every step that the evaluator performs
798as part of the application or evaluation just starting (as described
799by @var{trap-context}) is traced using @code{trace-trap}. The extra
800trap is automatically uninstalled when the application or evaluation
801is complete. @code{trace-until-exit} can be very useful as a first
802step when all you know is that there is a bug ``somewhere in XXX or in
803something 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
809their behaviours are fairly self-explanatory. For more information on
810the operation of the GDS interface via Emacs, see @ref{Using Guile in
811Emacs}. The tracing behaviours are explained more fully below.
812
813@cindex Trap context
814More generally, the @dfn{behaviour} specified for a trap can be any
815procedure that expects to be called with one @dfn{trap context}
816argument. 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
829The @dfn{trap context} is an object that caches information about the
830low level trap call and the stack at the point of the trap, and is
831passed as the only argument to all behaviour procedures. The
832information in the trap context can be accessed through the procedures
833beginning @code{tc:} that are exported by the @code{(ice-9 debugging
834traps)} module@footnote{Plus of course any procedures that build on
835these, such as the @code{trace/@dots{}} procedures exported by
836@code{(ice-9 debugging trace)} (@pxref{Tracing Configuration}).}; the
837most useful of these are as follows.
838
839@deffn {Generic Function} tc:type trap-context
840Indicates the type of the low level trap by returning one of the
841keywords @code{#:application}, @code{#:evaluation}, @code{#:return} or
842@code{#:error}.
843@end deffn
844
845@deffn {Generic Function} tc:return-value trap-context
846When @code{tc:type} gives @code{#:return}, this provides the value
847that is being returned.
848@end deffn
849
850@deffn {Generic Function} tc:stack trap-context
851Provides the stack at the point of the trap (as computed by
852@code{make-stack}, but cached so that the lengthy @code{make-stack}
853operation is not performed more than once for the same low level
854trap).
855@end deffn
856
857@deffn {Generic Function} tc:frame trap-context
858The innermost frame of the stack at the point of the trap.
859@end deffn
860
861@deffn {Generic Function} tc:depth trap-context
862The number of frames (including tail recursive non-real frames) in the
863stack at the point of the trap.
864@end deffn
865
866@deffn {Generic Function} tc:real-depth trap-context
867The number of real frames (that is, excluding the non-real frames that
868describe 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
875The following examples show what tracing is and the kind of output that
876it generates. In the first example, we define a recursive function for
877reversing a list, then watch the effect of the recursive calls by
878tracing each call and return value.
879
880@lisp
881guile> (define (rev ls)
882 (if (null? ls)
883 ls
884 (append (rev (cdr ls))
885 (list (car ls)))))
886guile> (use-modules (ice-9 debugging traps) (ice-9 debugging trace))
887guile> (define t1 (make <procedure-trap>
888 #:procedure rev
889 #:behaviour (list trace-trap
890 trace-at-exit)))
891guile> (install-trap t1)
892guile> (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
905The number before the colon in this output (which follows @code{(ice-9
906debugging trace)}'s default output format) is the number of real frames
907on the stack. The fact that this number increases for each recursive
908call confirms that the implementation above of @code{rev} is not
909tail-recursive.
910
911In the next example, we probe the @emph{internal} workings of
912@code{rev} in more detail by using the @code{trace-until-exit}
913behaviour.
914
915@lisp
916guile> (uninstall-trap t1)
917guile> (define t2 (make <procedure-trap>
918 #:procedure rev
919 #:behaviour (list trace-trap
920 trace-until-exit)))
921guile> (install-trap t2)
922guile> (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
968The output in this case shows every step that the evaluator performs
969in evaluating @code{(rev '(a b))}.
970
971
972@node Tracing Configuration
973@subsubsection Tracing Configuration
974
975The detail of what gets printed in each trace line, and the port to
976which 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
981Get or set the port to which tracing is printed. The default is the
982value of @code{(current-output-port)} when the @code{(ice-9 debugging
983trace)} module is first loaded.
984@end deffn
985
986@deffn {Procedure} set-trace-layout format-string . arg-procs
987Layout each trace line using @var{format-string} and @var{arg-procs}.
988For each trace line, the list of values to be printed is obtained by
989calling all the @var{arg-procs}, passing the trap context as the only
990parameter to each one. This list of values is then formatted using
991the specified @var{format-string}.
992@end deffn
993
994@noindent
995The @code{(ice-9 debugging trace)} module exports a set of arg-proc
996procedures to cover most common needs, with names beginning
997@code{trace/}. These are all implemented on top of the @code{tc:} trap
998context accessor procedures documented in @ref{Trap Context}, and if any
999trace output not provided by the following is needed, it should be
1000possible to implement based on a combination of the @code{tc:}
1001procedures.
1002
1003@deffn {Procedure} trace/pid trap-context
1004An arg-proc that returns the current process ID.
1005@end deffn
1006
1007@deffn {Procedure} trace/stack-id trap-context
1008An arg-proc that returns the stack ID of the stack in which the
1009current trap occurred.
1010@end deffn
1011
1012@deffn {Procedure} trace/stack-depth trap-context
1013An arg-proc that returns the length (including non-real frames) of the
1014stack at the point of the current trap.
1015@end deffn
1016
1017@deffn {Procedure} trace/stack-real-depth trap-context
1018An arg-proc that returns the length excluding non-real frames of the
1019stack at the point of the current trap.
1020@end deffn
1021
1022@deffn {Procedure} trace/stack trap-context
1023An arg-proc that returns a string summarizing stack information. This
1024string includes the stack ID, real depth, and count of additional
1025non-real frames, with the format @code{"~a:~a+~a"}.
1026@end deffn
1027
1028@deffn {Procedure} trace/source-file-name trap-context
1029An arg-proc that returns the name of the source file for the innermost
1030stack frame, or an empty string if source is not available for the
1031innermost frame.
1032@end deffn
1033
1034@deffn {Procedure} trace/source-line trap-context
1035An arg-proc that returns the line number of the source code for the
1036innermost stack frame, or zero if source is not available for the
1037innermost frame.
1038@end deffn
1039
1040@deffn {Procedure} trace/source-column trap-context
1041An arg-proc that returns the column number of the start of the source
1042code for the innermost stack frame, or zero if source is not available
1043for the innermost frame.
1044@end deffn
1045
1046@deffn {Procedure} trace/source trap-context
1047An arg-proc that returns the source location for the innermost stack
1048frame. This is a string composed of file name, line and column number
1049with the format @code{"~a:~a:~a"}, or an empty string if source is not
1050available for the innermost frame.
1051@end deffn
1052
1053@deffn {Procedure} trace/type trap-context
1054An arg-proc that returns a three letter abbreviation indicating the
1055type 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
1061An arg-proc that returns @code{" "} if the innermost stack frame is a
1062real frame, or @code{"t"} if it is not.
1063@end deffn
1064
1065@deffn {Procedure} trace/info trap-context
1066An arg-proc that returns a string describing the expression being
1067evaluated, application being performed, or return value, according to
1068the current trap type.
1069@end deffn
1070
1071@noindent
1072@code{trace/stack-depth} and @code{trace/stack-real-depth} are identical
1073to the trap context methods @code{tc:depth} and @code{tc:real-depth}
1074described before (@pxref{Trap Context}), but renamed here for
1075convenience.
1076
1077The default trace layout, as exhibited by the examples of the previous
1078subsubsubsection, is set by this line of code from the @code{(ice-9 debugging
1079traps)} module:
1080
1081@lisp
1082(set-trace-layout "|~3@@a: ~a\n" trace/stack-real-depth trace/info)
1083@end lisp
1084
1085@noindent
1086If we rerun the first of those examples, but with trace layout
1087configured to show source location and trap type in addition, the
1088output looks like this:
1089
1090@lisp
1091guile> (set-trace-layout "| ~25a ~3@@a: ~a ~a\n"
1092 trace/source
1093 trace/stack-real-depth
1094 trace/type
1095 trace/info)
1096guile> (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
24dbb5ed
NJ
1112The @code{(ice-9 debug)} module provides a tracing facility
1113(@pxref{Tracing}) that is roughly similar to that described here, but
1114there are important differences.
62ae9557
NJ
1115
1116@itemize @bullet
1117@item
1118The @code{(ice-9 debug)} trace gives a nice pictorial view of changes
1119in 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
113124
1132@end lisp
1133
1134However its output can @emph{only} show the information seen here,
24dbb5ed
NJ
1135which corresponds to @code{(ice-9 debugging trace)}'s
1136@code{trace/info} procedure; it cannot be configured to show other
1137pieces of information about the trap context in the way that the
1138@code{(ice-9 debugging trace)} implementation can.
62ae9557
NJ
1139
1140@item
1141The @code{(ice-9 debug)} trace only allows the tracing of procedure
24dbb5ed
NJ
1142applications and their return values, whereas the @code{(ice-9 debugging
1143trace)} implementation allows any kind of trap to be traced.
62ae9557
NJ
1144
1145It's interesting to note that @code{(ice-9 debug)}'s restriction here,
1146which might initially appear to be just a straightforward consequence
1147of its implementation, is also somewhat dictated by its pictorial
1148display. The use of indentation in the output relies on hooking into
1149the low level trap calls in such a way that the trapped application
24dbb5ed
NJ
1150entries and exits exactly balance each other. The @code{ice-9
1151debugging trace} implementation allows traps to be installed such that
1152entry and exit traps don't necessarily balance, which means that, in
1153general, indentation diagrams like the one above don't work.
62ae9557
NJ
1154@end itemize
1155
1156It isn't currently possible to use both @code{(ice-9 debug)} trace and
24dbb5ed
NJ
1157@code{(ice-9 debugging trace)} in the same Guile session, because
1158their settings of the low level trap options conflict with each other.
62ae9557
NJ
1159
1160
1161@node Traps Installing More Traps
1162@subsubsection Traps Installing More Traps
1163
1164Sometimes it is desirable for the behaviour at one trap to install
1165further 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
1167three more steps'', or ``@dots{} when this frame completes''. This is
1168absolutely fine. For example, it is easy to code a generic ``do
1169so-and-so when the current frame exits'' procedure, which can be used
1170wherever 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
1180To continue and pin down the example, this could then be used as part
1181of a behaviour whose purpose was to measure the accumulated time spent
1182in 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
1207When creating any kind of trap object, settings for the trap being
1208created are specified as options on the @code{make} call using syntax
1209like this:
1210
1211@lisp
1212(make <@var{trap-class}>
1213 #:@var{option-keyword} @var{setting}
1214 @dots{})
1215@end lisp
1216
1217The 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>
1221Base class for trap objects.
1222@end deffn
1223
1224@deffn {Trap Option} #:condition thunk
1225If not @code{#f}, this is a thunk which is called when the trap fires,
1226to determine whether trap processing should proceed any further. If
1227the thunk returns @code{#f}, the trap is basically suppressed.
1228Otherwise processing continues normally. (Default value @code{#f}.)
1229@end deffn
1230
1231@deffn {Trap Option} #:skip-count count
1232A count of valid (after @code{#:condition} processing) firings of this
1233trap to skip. (Default value 0.)
1234@end deffn
1235
1236@deffn {Trap Option} #:single-shot boolean
1237If not @code{#f}, this indicates that the trap should be automatically
1238uninstalled after it has successfully fired (after @code{#:condition}
1239and @code{#:skip-count} processing) for the first time. (Default
1240value @code{#f}.)
1241@end deffn
1242
1243@deffn {Trap Option} #:behaviour behaviour-proc
1244A trap behaviour procedure --- as discussed in the preceding subsubsection
1245--- or a list of such procedures, in which case each procedure is
1246called in turn when the trap fires. (Default value @code{'()}.)
1247@end deffn
1248
1249@deffn {Trap Option} #:repeat-identical-behaviour boolean
1250Normally, if multiple trap objects are triggered by the same low level
1251trap, and they request the same behaviour, it's only actually useful
1252to do that behaviour once (per low level trap); so by default multiple
1253requests for the same behaviour are coalesced. If this option is set
1254other than @code{#f}, the contents of the @code{#:behaviour} option
1255are 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
1263The @code{<procedure-trap>} class implements traps that are triggered
1264upon application of a specified procedure. Instances of this class
1265should use the @code{#:procedure} option to specify the procedure to
1266trap on.
1267
1268@deffn {Class} <procedure-trap>
1269Class for traps triggered by application of a specified procedure.
1270@end deffn
1271
1272@deffn {Trap Option} #:procedure procedure
1273Specifies the procedure to trap on.
1274@end deffn
1275
1276@noindent
1277Example:
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
1290The @code{<exit-trap>} class implements traps that are triggered upon
1291stack frame exit past a specified stack depth. Instances of this
1292class should use the @code{#:depth} option to specify the target stack
1293depth.
1294
1295@deffn {Class} <exit-trap>
1296Class for traps triggered by exit past a specified stack depth.
1297@end deffn
1298
1299@deffn {Trap Option} #:depth depth
1300Specifies the reference depth for the trap.
1301@end deffn
1302
1303@noindent
1304Example:
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
1321The @code{<entry-trap>} class implements traps that are triggered upon
1322any stack frame entry. No further parameters are needed to specify an
1323instance of this class, so there are no class-specific trap options.
1324Note 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>
1329Class for traps triggered by any stack frame entry.
1330@end deffn
1331
1332@noindent
1333Example:
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
1345The @code{<apply-trap>} class implements traps that are triggered upon
1346any procedure application. No further parameters are needed to
1347specify an instance of this class, so there are no class-specific trap
1348options. 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
1350application where some condition is true.
1351
1352@deffn {Class} <apply-trap>
1353Class for traps triggered by any procedure application.
1354@end deffn
1355
1356@noindent
1357Example:
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
1369The @code{<step-trap>} class implements traps that do single-stepping
1370through a program's execution. They come in two flavours, with and
1371without a specified file name. If a file name is specified, the trap
1372is triggered by the next evaluation, application or frame exit
1373pertaining to source code from the specified file. If a file name is
1374not specified, the trap is triggered by the next evaluation,
1375application or frame exit from any file (or for code whose source
1376location was not recorded), in other words by the next evaluator step
1377of any kind.
1378
1379The design goal of the @code{<step-trap>} class is to match what a
1380user would intuitively think of as single-stepping through their code,
1381either through code in general (roughly corresponding to GDB's
1382@code{step} command, for example), or through code from a particular
1383source file (roughly corresponding to GDB's @code{next}). Therefore
24dbb5ed
NJ
1384if you are using a step trap to single-step through code and finding
1385its behaviour counter-intuitive, please report that so we can improve
1386it.
62ae9557
NJ
1387
1388The implementation and options of the @code{<step-trap>} class are
1389complicated by the fact that it is unreliable to determine whether a
1390low level frame exit trap is applicable to a specified file by
1391examining the details of the reported frame. This is a consequence of
1392tail recursion, which has the effect that many frames can be removed
1393from the stack at once, with only the outermost frame being reported
1394by the low level trap call. The effects of this on the
1395@code{<step-trap>} class are such as to require the introduction of
1396the strange-looking @code{#:exit-depth} option, for the following
1397reasons.
1398
1399@itemize @bullet
1400@item
1401When stopped at the start of an application or evaluation frame, and
1402it is desired to continue execution until the next ``step'' in the same
1403source file, that next step could be the start of a nested application
1404or evaluation frame, or --- if the procedure definition is in a
1405different file, for example --- it could be the exit from the current
1406frame.
1407
1408@item
1409Because of the effects of tail recursion noted above, the current
1410frame exit possibility must be expressed as frame exit past a
1411specified stack depth. When an instance of the @code{<step-trap>}
1412class is installed from the context of an application or evaluation
1413frame entry, the @code{#:exit-depth} option should be used to specify
1414this stack depth.
1415
1416@item
1417When stopped at a frame exit, on the other hand, we know that the next
1418step must be an application or evaluation frame entry. In this
1419context the @code{#:exit-depth} option is not needed and should be
1420omitted or set to @code{#f}.
1421@end itemize
1422
1423@noindent
1424When a step trap is installed without @code{#:single-shot #t}, such
1425that it keeps firing, the @code{<step-trap>} code automatically
1426updates its idea of the @code{#:exit-depth} setting each time, so that
1427the trap always fires correctly for the following step.
1428
1429@deffn {Class} <step-trap>
1430Class for single-stepping traps.
1431@end deffn
1432
1433@deffn {Trap Option} #:file-name name
1434If not @code{#f}, this is a string containing the name of a source
1435file, and restricts the step trap to evaluation steps within that
1436source file. (Default value @code{#f}.)
1437@end deffn
1438
1439@deffn {Trap Option} #:exit-depth depth
1440If not @code{#f}, this is a positive integer implying that the next
1441step may be frame exit past the stack depth @var{depth}. See the
1442discussion above for more details. (Default value @code{#f}.)
1443@end deffn
1444
1445@noindent
1446Example:
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
1462The @code{<source-trap>} class implements traps that are attached to a
1463precise source code expression, as read by the reader, and which fire
1464each time that that expression is evaluated. These traps use a low
1465level Guile feature which can mark individual expressions for
1466trapping, and are relatively efficient. But it can be tricky to get
1467at the source expression in the first place, and these traps are
1468liable to become irrelevant if the procedure containing the expression
1469is reevaluated; these issues are discussed further below.
1470
1471@deffn {Class} <source-trap>
1472Class for traps triggered by evaluation of a specific Scheme
1473expression.
1474@end deffn
1475
1476@deffn {Trap Option} #:expression expr
1477Specifies the Scheme expression to trap on.
1478@end deffn
1479
1480@noindent
1481Example:
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{}
1492Enter an expression: (+ 1 2 3 4 5 6)
1493| 3: (+ 1 2 3 4 5 6)
1494| 3: =>21
149521
1496@end lisp
1497
1498The key point here is that the expression specified by the
1499@code{#:expression} option must be @emph{exactly} (i.e. @code{eq?} to)
1500what is going to be evaluated later. It doesn't work, for example, to
1501say @code{#:expression '(+ x 3)}, with the expectation that the trap
1502will fire whenever evaluating any expression @code{(+ x 3)}.
1503
1504The @code{trap-here} macro can be used in source code to create and
1505install a source trap correctly. Take for example the factorial
1506function 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
1516To set a source trap on a particular expression --- let's say the
1517expression @code{(= n 0)} --- edit the code so that the expression is
1518enclosed 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
1528Install 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
1533Note that if the @code{trap-here} incantation is removed, and
1534@code{fact1} then redefined by reloading its source file, the effect
1535of the source trap is lost, because the text ``(= n 0)'' is read again
1536from scratch and becomes a new expression @code{(= n 0)} which does
1537not have the ``trap here'' mark on it.
1538
1539If the semantics and setting of source traps seem unwieldy, location
1540traps may meet your need more closely; these are described in the
1541following subsubsection.
1542
1543
1544@node Location Traps
1545@subsubsection Location Traps
1546
1547The @code{<location-trap>} class implements traps that are triggered
24dbb5ed
NJ
1548by evaluation of code at a specific source location. When compared
1549with source traps, they are easier to set, and do not become
1550irrelevant when the relevant code is reloaded; but unfortunately they
1551are a lot less efficient, as they require running some ``are we in the
1552right place for a trap'' code on every low level frame entry trap
1553call.
62ae9557
NJ
1554
1555@deffn {Class} <location-trap>
1556Class for traps triggered by evaluation of code at a specific source
24dbb5ed 1557location.
62ae9557
NJ
1558@end deffn
1559
1560@deffn {Trap Option} #:file-regexp regexp
1561A regular expression specifying the filenames that will match this
1562trap. This option must be specified when creating a location trap.
1563@end deffn
1564
24dbb5ed
NJ
1565@deffn {Trap Option} #:line line
1566The line number (0-based) of the source location at which the trap
1567should be triggered. This option must be specified when creating a
1568location trap.
62ae9557
NJ
1569@end deffn
1570
24dbb5ed
NJ
1571@deffn {Trap Option} #:column column
1572The column number (0-based) of the source location at which the trap
1573should be triggered. This option must be specified when creating a
1574location trap.
62ae9557
NJ
1575@end deffn
1576
1577@noindent
24dbb5ed
NJ
1578Here is an example, which matches the @code{(facti (- n 1) (* a n))}
1579expression in @file{ice-9/debugging/example-fns.scm}:
62ae9557
NJ
1580
1581@lisp
1582(install-trap (make <location-trap>
1583 #:file-regexp "example-fns.scm"
24dbb5ed
NJ
1584 #:line 11
1585 #:column 6
62ae9557
NJ
1586 #:behaviour gds-debug-trap))
1587@end lisp
1588
1589
1590@node Trap Shorthands
1591@subsubsection Trap Shorthands
1592
1593If the code described in the preceding subsubsections for creating and
1594manipulating traps seems a little long-winded, it is of course
1595possible to define more convenient shorthand forms for typical usage
24dbb5ed 1596patterns. Here are some examples.
62ae9557
NJ
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
24dbb5ed
NJ
1617Definitions like these are not provided out-of-the-box by Guile,
1618because different users will have different ideas about what their
1619default debugger should be, or, for example, which of the common trap
1620options (@pxref{Common Trap Options}) it might be useful to expose
1621through such shorthand procedures.
62ae9557
NJ
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
1628objects. This uses a weak value hash table, keyed by a trap index
1629number. Each trap object has its index number assigned, and is added
1630to 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
1632removed from the hash table, and so no longer appears in the output
1633from @code{list-traps}.
1634
1635@deffn {Variable} all-traps
1636Weak value hash table containing all known trap objects.
1637@end deffn
1638
1639@deffn {Procedure} list-traps
1640Print a description of all known trap objects.
1641@end deffn
1642
1643The following example shows a single trap that traces applications of
1644the procedure @code{facti}.
1645
1646@lisp
1647guile> (list-traps)
1648#<<procedure-trap> 100d2e30> is an instance of class <procedure-trap>
1649Slots 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
1660When @code{all-traps} or @code{list-traps} reveals a trap that you
1661want to modify but no longer have a reference to, you can retrieve the
1662trap object by calling @code{get-trap} with the trap's number. For
1663example, here's how you could change the behaviour of the trap listed
1664just above.
1665
1666@lisp
1667(slot-set! (get-trap 1) 'behaviour (list debug-trap))
1668@end lisp
1669
1670@deffn {Procedure} get-trap number
1671Return the trap object with the specified @var{number}, or @code{#f}
1672if there isn't one.
1673@end deffn
1674
1675
24dbb5ed
NJ
1676@node Debugging Examples
1677@subsection Debugging Examples
1678
1679Here we present some examples of what you can do with the debugging
1680facilities 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
1691A good way to explore in detail what a Scheme procedure does is to set
1692a trap on it and then single step through what it does. To do this,
1693make and install a @code{<procedure-trap>} with the @code{debug-trap}
ba5f8bf4 1694behaviour from @code{(ice-9 debugger)}.
24dbb5ed
NJ
1695
1696The following sample session illustrates this. It assumes that the
1697file @file{matrix.scm} defines a procedure @code{mkmatrix}, which is
1698the one we want to explore, and another procedure @code{do-main} which
1699calls @code{mkmatrix}.
1700
1701@lisp
1702$ /usr/bin/guile -q
1703guile> (use-modules (ice-9 debugger)
24dbb5ed
NJ
1704 (ice-9 debugging traps))
1705guile> (load "matrix.scm")
1706guile> (install-trap (make <procedure-trap>
1707 #:procedure mkmatrix
1708 #:behaviour debug-trap))
1709guile> (do-main 4)
1710This is the Guile debugger -- for help, type `help'.
1711There are 3 frames on the stack.
1712
1713Frame 2 at matrix.scm:8:3
1714 [mkmatrix]
1715debug> next
1716Frame 3 at matrix.scm:4:3
45867c2a 1717 (let ((x 1)) (quote hi!))
24dbb5ed
NJ
1718debug> info frame
1719Stack frame: 3
1720This frame is an evaluation.
1721The expression being evaluated is:
1722matrix.scm:4:3:
45867c2a 1723 (let ((x 1)) (quote hi!))
24dbb5ed
NJ
1724debug> next
1725Frame 3 at matrix.scm:5:21
45867c2a 1726 (quote hi!)
24dbb5ed
NJ
1727debug> bt
1728In unknown file:
1729 ?: 0* [primitive-eval (do-main 4)]
1730In standard input:
1731 4: 1* [do-main 4]
1732In matrix.scm:
1733 8: 2 [mkmatrix]
1734 ...
45867c2a 1735 5: 3 (quote hi!)
24dbb5ed 1736debug> quit
45867c2a 1737hi!
24dbb5ed
NJ
1738guile>
1739@end lisp
1740
1741Or 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
ba5f8bf4
NJ
1743changing @code{debug-trap} to @code{gds-debug-trap}. Then the stack and
1744corresponding source locations are displayed in Emacs instead of on the
1745Guile command line.
24dbb5ed
NJ
1746
1747
1748@node Profiling or Tracing a Procedure's Code
1749@subsubsection Profiling or Tracing a Procedure's Code
1750
1751What if you wanted to get a trace of everything that the Guile
1752evaluator does within a given procedure, but without Guile stopping
1753and waiting for your input at every step? For this requirement you
1754can install a trap on the procedure, as in the previous example, but
1755instead of @code{debug-trap} or @code{gds-debug-trap}, use the
1756@code{trace-trap} and @code{trace-until-exit} behaviours provided by
1757the @code{(ice-9 debugging trace)} module.
1758
1759@lisp
1760guile> (use-modules (ice-9 debugging traps) (ice-9 debugging trace))
1761guile> (load "matrix.scm")
1762guile> (install-trap (make <procedure-trap>
1763 #:procedure mkmatrix
1764 #:behaviour (list trace-trap trace-until-exit)))
1765guile> (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
45867c2a 1797| 2: (letrec ((yy 23)) (let ((x 1)) (quote hi!)))
24dbb5ed
NJ
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
45867c2a 1816| 2: (let ((x 1)) (quote hi!))
24dbb5ed
NJ
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 # #) (# # #)]
45867c2a
NJ
1825| 2: =>(#@@let* (x 1) #@@let (quote hi!))
1826hi!
24dbb5ed
NJ
1827guile> (do-main 4)
1828| 2: [mkmatrix]
45867c2a
NJ
1829| 2: (letrec ((yy 23)) (let* ((x 1)) (quote hi!)))
1830| 2: (let* ((x 1)) (quote hi!))
1831| 2: (quote hi!)
1832| 2: =>hi!
1833hi!
24dbb5ed
NJ
1834guile>
1835@end lisp
1836
1837This example shows the default configuration for how each line of trace
1838output is formatted, which is:
1839
1840@itemize
1841@item
1842the character @code{|}, a visual clue that the line is a line of trace
1843output, followed by
1844
1845@item
1846a number indicating the real evaluator stack depth (where ``real'' means
1847not counting tail-calls), followed by
1848
1849@item
1850a summary of the expression being evaluated (@code{(@dots{})}), the
1851procedure being called (@code{[@dots{}]}), or the value being returned
1852from an evaluation or procedure call (@code{=>@dots{}}).
1853@end itemize
1854
1855@noindent
1856You can customize @code{(ice-9 debugging trace)} to show different
1857information in each trace line using the @code{set-trace-layout}
1858procedure. The next example shows how to get the source location in
1859each trace line instead of the stack depth.
1860
1861@lisp
1862guile> (set-trace-layout "|~16@@a: ~a\n" trace/source trace/info)
1863guile> (do-main 4)
1864| matrix.scm:7:2: [mkmatrix]
45867c2a
NJ
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!
1869hi!
24dbb5ed
NJ
1870guile>
1871@end lisp
1872
07d83abe
MV
1873@c Local Variables:
1874@c TeX-master: "guile.texi"
1875@c End: