(Expression Syntax): Add findex entries for
[bpt/guile.git] / doc / ref / scheme-control.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
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
6
7 @page
8 @node Control Mechanisms
9 @chapter Controlling the Flow of Program Execution
10
11 @menu
12 * begin:: Evaluating a sequence of expressions.
13 * if cond case:: Simple conditional evaluation.
14 * and or:: Conditional evaluation of a sequence.
15 * while do:: Iteration mechanisms.
16 * Continuations:: Continuations.
17 * Multiple Values:: Returning and accepting multiple values.
18 * Exceptions:: Throwing and catching exceptions.
19 * Error Reporting:: Procedures for signaling errors.
20 * Dynamic Wind:: Guarding against non-local entrance/exit.
21 * Frames:: Another way to handle non-localness
22 * Handling Errors:: How to handle errors in C code.
23 @end menu
24
25 Scheme has a more general view of program flow than C, both locally and
26 non-locally.
27
28 Controlling the local flow of control involves things like gotos, loops,
29 calling functions and returning from them. Non-local control flow
30 refers to situations where the program jumps across one or more levels
31 of function activations without using the normal call or return
32 operations.
33
34 The primitive means of C for local control flow is the @code{goto}
35 statement, together with @code{if}. Loops done with @code{for},
36 @code{while} or @code{do} could in principle be rewritten with just
37 @code{goto} and @code{if}. In Scheme, the primitive means for local
38 control flow is the @emph{function call} (together with @code{if}).
39 Thus, the repetition of some computation in a loop is ultimately
40 implemented by a function that calls itself, that is, by recursion.
41
42 This approach is theoretically very powerful since it is easier to
43 reason formally about recursion than about gotos. In C, using
44 recursion exclusively would not be practical, tho, since it would eat
45 up the stack very quickly. In Scheme, however, it is practical:
46 function calls that appear in a @dfn{tail position} do not use any
47 additional stack space.
48
49 A function call is in a tail position when it is the last thing the
50 calling function does. The value returned by the called function is
51 immediately returned from the calling function. In the following
52 example, the call to @code{bar-1} is in a tail position, while the
53 call to @code{bar-2} is not. (The call to @code{1-} in @code{foo-2}
54 is in a tail position, tho.)
55
56 @lisp
57 (define (foo-1 x)
58 (bar-1 (1- x)))
59
60 (define (foo-2 x)
61 (1- (bar-2 x)))
62 @end lisp
63
64 Thus, when you take care to recurse only in tail positions, the
65 recursion will only use constant stack space and will be as good as a
66 loop constructed from gotos.
67
68 Scheme offers a few syntactic abstractions (@code{do} and @dfn{named}
69 @code{let}) that make writing loops slightly easier.
70
71 But only Scheme functions can call other functions in a tail position:
72 C functions can not. This matters when you have, say, two functions
73 that call each other recursively to form a common loop. The following
74 (unrealistic) example shows how one might go about determing whether a
75 non-negative integer @var{n} is even or odd.
76
77 @lisp
78 (define (my-even? n)
79 (cond ((zero? n) #t)
80 (else (my-odd? (1- n)))))
81
82 (define (my-odd? n)
83 (cond ((zero? n) #f)
84 (else (my-even? (1- n)))))
85 @end lisp
86
87 Because the calls to @code{my-even?} and @code{my-odd?} are in tail
88 positions, these two procedures can be applied to arbitrary large
89 integers without overflowing the stack. (They will still take a lot
90 of time, of course.)
91
92 However, when one or both of the two procedures would be rewritten in
93 C, it could no longer call its companion in a tail position (since C
94 does not have this concept). You might need to take this
95 consideration into account when deciding which parts of your program
96 to write in Scheme and which in C.
97
98 In addition to calling functions and returning from them, a Scheme
99 program can also exit non-locally from a function so that the control
100 flow returns directly to an outer level. This means that some functions
101 might not return at all.
102
103 Even more, it is not only possible to jump to some outer level of
104 control, a Scheme program can also jump back into the middle of a
105 function that has already exited. This might cause some functions to
106 return more than once.
107
108 In general, these non-local jumps are done by invoking
109 @dfn{continuations} that have previously been captured using
110 @code{call-with-current-continuation}. Guile also offers a slightly
111 restricted set of functions, @code{catch} and @code{throw}, that can
112 only be used for non-local exits. This restriction makes them more
113 efficient. Error reporting (with the function @code{error}) is
114 implemented by invoking @code{throw}, for example. The functions
115 @code{catch} and @code{throw} belong to the topic of @dfn{exceptions}.
116
117 Since Scheme functions can call C functions and vice versa, C code can
118 experience the more general control flow of Scheme as well. It is
119 possible that a C function will not return at all, or will return more
120 than once. While C does offer @code{setjmp} and @code{longjmp} for
121 non-local exits, it is still an unusual thing for C code. In
122 contrast, non-local exits are very common in Scheme, mostly to report
123 errors.
124
125 You need to be prepared for the non-local jumps in the control flow
126 whenever you use a function from @code{libguile}: it is best to assume
127 that any @code{libguile} function might signal an error or run a pending
128 signal handler (which in turn can do arbitrary things).
129
130 It is often necessary to take cleanup actions when the control leaves a
131 function non-locally. Also, when the control returns non-locally, some
132 setup actions might be called for. For example, the Scheme function
133 @code{with-output-to-port} needs to modify the global state so that
134 @code{current-output-port} returns the port passed to
135 @code{with-output-to-port}. The global output port needs to be reset to
136 its previous value when @code{with-output-to-port} returns normally or
137 when it is exited non-locally. Likewise, the port needs to be set again
138 when control enters non-locally.
139
140 Scheme code can use the @code{dynamic-wind} function to arrange for
141 the setting and resetting of the global state. C code could use the
142 corresponding @code{scm_internal_dynamic_wind} function, but it might
143 prefer to use the @dfn{frames} concept that is more natural for C
144 code.
145
146
147 @node begin
148 @section Evaluating a Sequence of Expressions
149
150 @cindex begin
151 @cindex sequencing
152 @cindex expression sequencing
153
154 The @code{begin} syntax is used for grouping several expressions
155 together so that they are treated as if they were one expression.
156 This is particularly important when syntactic expressions are used
157 which only allow one expression, but the programmer wants to use more
158 than one expression in that place. As an example, consider the
159 conditional expression below:
160
161 @lisp
162 (if (> x 0)
163 (begin (display "greater") (newline)))
164 @end lisp
165
166 If the two calls to @code{display} and @code{newline} were not embedded
167 in a @code{begin}-statement, the call to @code{newline} would get
168 misinterpreted as the else-branch of the @code{if}-expression.
169
170 @deffn syntax begin expr1 expr2 @dots{}
171 The expression(s) are evaluated in left-to-right order and the value
172 of the last expression is returned as the value of the
173 @code{begin}-expression. This expression type is used when the
174 expressions before the last one are evaluated for their side effects.
175
176 Guile also allows the expression @code{(begin)}, a @code{begin} with no
177 sub-expressions. Such an expression returns the `unspecified' value.
178 @end deffn
179
180 @node if cond case
181 @section Simple Conditional Evaluation
182
183 @cindex conditional evaluation
184 @cindex if
185 @cindex case
186 @cindex cond
187
188 Guile provides three syntactic constructs for conditional evaluation.
189 @code{if} is the normal if-then-else expression (with an optional else
190 branch), @code{cond} is a conditional expression with multiple branches
191 and @code{case} branches if an expression has one of a set of constant
192 values.
193
194 @deffn syntax if test consequent [alternate]
195 All arguments may be arbitrary expressions. First, @var{test} is
196 evaluated. If it returns a true value, the expression @var{consequent}
197 is evaluated and @var{alternate} is ignored. If @var{test} evaluates to
198 @code{#f}, @var{alternate} is evaluated instead. The value of the
199 evaluated branch (@var{consequent} or @var{alternate}) is returned as
200 the value of the @code{if} expression.
201
202 When @var{alternate} is omitted and the @var{test} evaluates to
203 @code{#f}, the value of the expression is not specified.
204 @end deffn
205
206 @deffn syntax cond clause1 clause2 @dots{}
207 Each @code{cond}-clause must look like this:
208
209 @lisp
210 (@var{test} @var{expression} @dots{})
211 @end lisp
212
213 where @var{test} and @var{expression} are arbitrary expression, or like
214 this
215
216 @lisp
217 (@var{test} => @var{expression})
218 @end lisp
219
220 where @var{expression} must evaluate to a procedure.
221
222 The @var{test}s of the clauses are evaluated in order and as soon as one
223 of them evaluates to a true values, the corresponding @var{expression}s
224 are evaluated in order and the last value is returned as the value of
225 the @code{cond}-expression. For the @code{=>} clause type,
226 @var{expression} is evaluated and the resulting procedure is applied to
227 the value of @var{test}. The result of this procedure application is
228 then the result of the @code{cond}-expression.
229
230 The @var{test} of the last @var{clause} may be the symbol @code{else}.
231 Then, if none of the preceding @var{test}s is true, the
232 @var{expression}s following the @code{else} are evaluated to produce the
233 result of the @code{cond}-expression.
234 @end deffn
235
236 @deffn syntax case key clause1 clause2 @dots{}
237 @var{key} may be any expression, the @var{clause}s must have the form
238
239 @lisp
240 ((@var{datum1} @dots{}) @var{expr1} @var{expr2} @dots{})
241 @end lisp
242
243 and the last @var{clause} may have the form
244
245 @lisp
246 (else @var{expr1} @var{expr2} @dots{})
247 @end lisp
248
249 All @var{datum}s must be distinct. First, @var{key} is evaluated. The
250 the result of this evaluation is compared against all @var{datum}s using
251 @code{eqv?}. When this comparison succeeds, the expression(s) following
252 the @var{datum} are evaluated from left to right, returning the value of
253 the last expression as the result of the @code{case} expression.
254
255 If the @var{key} matches no @var{datum} and there is an
256 @code{else}-clause, the expressions following the @code{else} are
257 evaluated. If there is no such clause, the result of the expression is
258 unspecified.
259 @end deffn
260
261
262 @node and or
263 @section Conditional Evaluation of a Sequence of Expressions
264
265 @code{and} and @code{or} evaluate all their arguments in order, similar
266 to @code{begin}, but evaluation stops as soon as one of the expressions
267 evaluates to false or true, respectively.
268
269 @deffn syntax and expr @dots{}
270 Evaluate the @var{expr}s from left to right and stop evaluation as soon
271 as one expression evaluates to @code{#f}; the remaining expressions are
272 not evaluated. The value of the last evaluated expression is returned.
273 If no expression evaluates to @code{#f}, the value of the last
274 expression is returned.
275
276 If used without expressions, @code{#t} is returned.
277 @end deffn
278
279 @deffn syntax or expr @dots{}
280 Evaluate the @var{expr}s from left to right and stop evaluation as soon
281 as one expression evaluates to a true value (that is, a value different
282 from @code{#f}); the remaining expressions are not evaluated. The value
283 of the last evaluated expression is returned. If all expressions
284 evaluate to @code{#f}, @code{#f} is returned.
285
286 If used without expressions, @code{#f} is returned.
287 @end deffn
288
289
290 @node while do
291 @section Iteration mechanisms
292
293 @cindex iteration
294 @cindex looping
295 @cindex named let
296
297 Scheme has only few iteration mechanisms, mainly because iteration in
298 Scheme programs is normally expressed using recursion. Nevertheless,
299 R5RS defines a construct for programming loops, calling @code{do}. In
300 addition, Guile has an explicit looping syntax called @code{while}.
301
302 @deffn syntax do ((variable init [step]) @dots{}) (test [expr @dots{}]) body @dots{}
303 Bind @var{variable}s and evaluate @var{body} until @var{test} is true.
304 The return value is the last @var{expr} after @var{test}, if given. A
305 simple example will illustrate the basic form,
306
307 @example
308 (do ((i 1 (1+ i)))
309 ((> i 4))
310 (display i))
311 @print{} 1234
312 @end example
313
314 @noindent
315 Or with two variables and a final return value,
316
317 @example
318 (do ((i 1 (1+ i))
319 (p 3 (* 3 p)))
320 ((> i 4)
321 p)
322 (format #t "3**~s is ~s\n" i p))
323 @print{}
324 3**1 is 3
325 3**2 is 9
326 3**3 is 27
327 3**4 is 81
328 @result{}
329 789
330 @end example
331
332 The @var{variable} bindings are established like a @code{let}, in that
333 the expressions are all evaluated and then all bindings made. When
334 iterating, the optional @var{step} expressions are evaluated with the
335 previous bindings in scope, then new bindings all made.
336
337 The @var{test} expression is a termination condition. Looping stops
338 when the @var{test} is true. It's evaluated before running the
339 @var{body} each time, so if it's true the first time then @var{body}
340 is not run at all.
341
342 The optional @var{expr}s after the @var{test} are evaluated at the end
343 of looping, with the final @var{variable} bindings available. The
344 last @var{expr} gives the return value, or if there are no @var{expr}s
345 the return value is unspecified.
346
347 Each iteration establishes bindings to fresh locations for the
348 @var{variable}s, like a new @code{let} for each iteration. This is
349 done for @var{variable}s without @var{step} expressions too. The
350 following illustrates this, showing how a new @code{i} is captured by
351 the @code{lambda} in each iteration (@pxref{About Closure,, The
352 Concept of Closure}).
353
354 @example
355 (define lst '())
356 (do ((i 1 (1+ i)))
357 ((> i 4))
358 (set! lst (cons (lambda () i) lst)))
359 (map (lambda (proc) (proc)) lst)
360 @result{}
361 (4 3 2 1)
362 @end example
363 @end deffn
364
365 @deffn syntax while cond body @dots{}
366 Run a loop executing the @var{body} forms while @var{cond} is true.
367 @var{cond} is tested at the start of each iteration, so if it's
368 @code{#f} the first time then @var{body} is not executed at all. The
369 return value is unspecified.
370
371 Within @code{while}, two extra bindings are provided, they can be used
372 from both @var{cond} and @var{body}.
373
374 @deffn {Scheme Procedure} break
375 Break out of the @code{while} form.
376 @end deffn
377
378 @deffn {Scheme Procedure} continue
379 Abandon the current iteration, go back to the start and test
380 @var{cond} again, etc.
381 @end deffn
382
383 Each @code{while} form gets its own @code{break} and @code{continue}
384 procedures, operating on that @code{while}. This means when loops are
385 nested the outer @code{break} can be used to escape all the way out.
386 For example,
387
388 @example
389 (while (test1)
390 (let ((outer-break break))
391 (while (test2)
392 (if (something)
393 (outer-break #f))
394 ...)))
395 @end example
396
397 Note that each @code{break} and @code{continue} procedure can only be
398 used within the dynamic extent of its @code{while}. Outside the
399 @code{while} their behaviour is unspecified.
400 @end deffn
401
402 @cindex named let
403 Another very common way of expressing iteration in Scheme programs is
404 the use of the so-called @dfn{named let}.
405
406 Named let is a variant of @code{let} which creates a procedure and calls
407 it in one step. Because of the newly created procedure, named let is
408 more powerful than @code{do}--it can be used for iteration, but also
409 for arbitrary recursion.
410
411 @deffn syntax let variable bindings body
412 For the definition of @var{bindings} see the documentation about
413 @code{let} (@pxref{Local Bindings}).
414
415 Named @code{let} works as follows:
416
417 @itemize @bullet
418 @item
419 A new procedure which accepts as many arguments as are in @var{bindings}
420 is created and bound locally (using @code{let}) to @var{variable}. The
421 new procedure's formal argument names are the name of the
422 @var{variables}.
423
424 @item
425 The @var{body} expressions are inserted into the newly created procedure.
426
427 @item
428 The procedure is called with the @var{init} expressions as the formal
429 arguments.
430 @end itemize
431
432 The next example implements a loop which iterates (by recursion) 1000
433 times.
434
435 @lisp
436 (let lp ((x 1000))
437 (if (positive? x)
438 (lp (- x 1))
439 x))
440 @result{}
441 0
442 @end lisp
443 @end deffn
444
445
446 @node Continuations
447 @section Continuations
448 @cindex continuations
449
450 A ``continuation'' is the code that will execute when a given function
451 or expression returns. For example, consider
452
453 @example
454 (define (foo)
455 (display "hello\n")
456 (display (bar)) (newline)
457 (exit))
458 @end example
459
460 The continuation from the call to @code{bar} comprises a
461 @code{display} of the value returned, a @code{newline} and an
462 @code{exit}. This can be expressed as a function of one argument.
463
464 @example
465 (lambda (r)
466 (display r) (newline)
467 (exit))
468 @end example
469
470 In Scheme, continuations are represented as special procedures just
471 like this. The special property is that when a continuation is called
472 it abandons the current program location and jumps directly to that
473 represented by the continuation.
474
475 A continuation is like a dynamic label, capturing at run-time a point
476 in program execution, including all the nested calls that have lead to
477 it, or rather the code that will execute when those calls return.
478
479 Continuations are created with the following functions.
480
481 @deffn {Scheme Procedure} call-with-current-continuation proc
482 @deffnx {Scheme Procedure} call/cc proc
483 @rnindex call-with-current-continuation
484 Capture the current continuation and call @code{(@var{proc}
485 @var{cont})} with it. The return value is the value returned by
486 @var{proc}, or when @code{(@var{cont} @var{value})} is later invoked,
487 the return is the @var{value} passed.
488
489 Normally @var{cont} should be called with one argument, but when the
490 location resumed is expecting multiple values (@pxref{Multiple
491 Values}) then they should be passed as multiple arguments, for
492 instance @code{(@var{cont} @var{x} @var{y} @var{z})}.
493
494 @var{cont} may only be used from the dynamic root in which it was
495 created (@pxref{Dynamic Roots}), and in a multi-threaded program only
496 from the thread in which it was created, since each thread is a
497 separate dynamic root.
498
499 The call to @var{proc} is not part of the continuation captured, it runs
500 only when the continuation is created. Often a program will want to
501 store @var{cont} somewhere for later use; this can be done in
502 @var{proc}.
503
504 The @code{call} in the name @code{call-with-current-continuation}
505 refers to the way a call to @var{proc} gives the newly created
506 continuation. It's not related to the way a call is used later to
507 invoke that continuation.
508
509 @code{call/cc} is an alias for @code{call-with-current-continuation}.
510 This is in common use since the latter is rather long.
511 @end deffn
512
513 @deftypefn {C Function} SCM scm_make_continuation (int *first)
514 Capture the current continuation as described above. The return value
515 is the new continuation, and @var{*first} is set to 1.
516
517 When the continuation is invoked, @code{scm_make_continuation} will
518 return again, this time returning the value (or set of multiple
519 values) passed in that invocation, and with @var{*first} set to 0.
520 @end deftypefn
521
522 @sp 1
523 @noindent
524 Here is a simple example,
525
526 @example
527 (define kont #f)
528 (format #t "the return is ~a\n"
529 (call/cc (lambda (k)
530 (set! kont k)
531 1)))
532 @result{} the return is 1
533
534 (kont 2)
535 @result{} the return is 2
536 @end example
537
538 @code{call/cc} captures a continuation in which the value returned is
539 going to be displayed by @code{format}. The @code{lambda} stores this
540 in @code{kont} and gives an initial return @code{1} which is
541 displayed. The later invocation of @code{kont} resumes the captured
542 point, but this time returning @code{2}, which is displayed.
543
544 When Guile is run interactively, a call to @code{format} like this has
545 an implicit return back to the read-eval-print loop. @code{call/cc}
546 captures that like any other return, which is why interactively
547 @code{kont} will come back to read more input.
548
549 @sp 1
550 C programmers may note that @code{call/cc} is like @code{setjmp} in
551 the way it records at runtime a point in program execution. A call to
552 a continuation is like a @code{longjmp} in that it abandons the
553 present location and goes to the recorded one. Like @code{longjmp},
554 the value passed to the continuation is the value returned by
555 @code{call/cc} on resuming there. However @code{longjmp} can only go
556 up the program stack, but the continuation mechanism can go anywhere.
557
558 When a continuation is invoked, @code{call/cc} and subsequent code
559 effectively ``returns'' a second time. It can be confusing to imagine
560 a function returning more times than it was called. It may help
561 instead to think of it being stealthily re-entered and then program
562 flow going on as normal.
563
564 The functions @code{dynamic-wind} (@pxref{Dynamic Wind}) can be used to
565 ensure setup and cleanup code is run when a program locus is resumed or
566 abandoned through the continuation mechanism. C code can use
567 @dfn{frames} (@pxref{Frames}).
568
569 @sp 1
570 Continuations are a powerful mechanism, and can be used to implement
571 almost any sort of control structure, such as loops, coroutines, or
572 exception handlers.
573
574 However the implementation of continuations in Guile is not as
575 efficient as one might hope, because Guile is designed to cooperate
576 with programs written in other languages, such as C, which do not know
577 about continuations. Basically continuations are captured by a block
578 copy of the stack, and resumed by copying back.
579
580 For this reason, generally continuations should be used only when
581 there is no other simple way to achieve the desired result, or when
582 the elegance of the continuation mechanism outweighs the need for
583 performance.
584
585 Escapes upwards from loops or nested functions are generally best
586 handled with exceptions (@pxref{Exceptions}). Coroutines can be
587 efficiently implemented with cooperating threads (a thread holds a
588 full program stack but doesn't copy it around the way continuations
589 do).
590
591
592 @node Multiple Values
593 @section Returning and Accepting Multiple Values
594
595 @cindex multiple values
596 @cindex receive
597
598 Scheme allows a procedure to return more than one value to its caller.
599 This is quite different to other languages which only allow
600 single-value returns. Returning multiple values is different from
601 returning a list (or pair or vector) of values to the caller, because
602 conceptually not @emph{one} compound object is returned, but several
603 distinct values.
604
605 The primitive procedures for handling multiple values are @code{values}
606 and @code{call-with-values}. @code{values} is used for returning
607 multiple values from a procedure. This is done by placing a call to
608 @code{values} with zero or more arguments in tail position in a
609 procedure body. @code{call-with-values} combines a procedure returning
610 multiple values with a procedure which accepts these values as
611 parameters.
612
613 @rnindex values
614 @deffn {Scheme Procedure} values arg1 @dots{} argN
615 @deffnx {C Function} scm_values (args)
616 Delivers all of its arguments to its continuation. Except for
617 continuations created by the @code{call-with-values} procedure,
618 all continuations take exactly one value. The effect of
619 passing no value or more than one value to continuations that
620 were not created by @code{call-with-values} is unspecified.
621
622 For @code{scm_values}, @var{args} is a list of arguments and the
623 return is a multiple-values object which the caller can return. In
624 the current implementation that object shares structure with
625 @var{args}, so @var{args} should not be modified subsequently.
626 @end deffn
627
628 @rnindex call-with-values
629 @deffn {Scheme Procedure} call-with-values producer consumer
630 Calls its @var{producer} argument with no values and a
631 continuation that, when passed some values, calls the
632 @var{consumer} procedure with those values as arguments. The
633 continuation for the call to @var{consumer} is the continuation
634 of the call to @code{call-with-values}.
635
636 @example
637 (call-with-values (lambda () (values 4 5))
638 (lambda (a b) b))
639 @result{} 5
640
641 @end example
642 @example
643 (call-with-values * -)
644 @result{} -1
645 @end example
646 @end deffn
647
648 In addition to the fundamental procedures described above, Guile has a
649 module which exports a syntax called @code{receive}, which is much more
650 convenient. If you want to use it in your programs, you have to load
651 the module @code{(ice-9 receive)} with the statement
652
653 @lisp
654 (use-modules (ice-9 receive))
655 @end lisp
656
657 @deffn {library syntax} receive formals expr body @dots{}
658 Evaluate the expression @var{expr}, and bind the result values (zero or
659 more) to the formal arguments in the formal argument list @var{formals}.
660 @var{formals} must have the same syntax like the formal argument list
661 used in @code{lambda} (@pxref{Lambda}). After binding the variables,
662 the expressions in @var{body} @dots{} are evaluated in order.
663 @end deffn
664
665
666 @node Exceptions
667 @section Exceptions
668 @cindex error handling
669 @cindex exception handling
670
671 A common requirement in applications is to want to jump
672 @dfn{non-locally} from the depths of a computation back to, say, the
673 application's main processing loop. Usually, the place that is the
674 target of the jump is somewhere in the calling stack of procedures that
675 called the procedure that wants to jump back. For example, typical
676 logic for a key press driven application might look something like this:
677
678 @example
679 main-loop:
680 read the next key press and call dispatch-key
681
682 dispatch-key:
683 lookup the key in a keymap and call an appropriate procedure,
684 say find-file
685
686 find-file:
687 interactively read the required file name, then call
688 find-specified-file
689
690 find-specified-file:
691 check whether file exists; if not, jump back to main-loop
692 @dots{}
693 @end example
694
695 The jump back to @code{main-loop} could be achieved by returning through
696 the stack one procedure at a time, using the return value of each
697 procedure to indicate the error condition, but Guile (like most modern
698 programming languages) provides an additional mechanism called
699 @dfn{exception handling} that can be used to implement such jumps much
700 more conveniently.
701
702 @menu
703 * Exception Terminology:: Different ways to say the same thing.
704 * Catch:: Setting up to catch exceptions.
705 * Throw:: Throwing an exception.
706 * Lazy Catch:: Catch without unwinding the stack.
707 * Exception Implementation:: How Guile implements exceptions.
708 @end menu
709
710
711 @node Exception Terminology
712 @subsection Exception Terminology
713
714 There are several variations on the terminology for dealing with
715 non-local jumps. It is useful to be aware of them, and to realize
716 that they all refer to the same basic mechanism.
717
718 @itemize @bullet
719 @item
720 Actually making a non-local jump may be called @dfn{raising an
721 exception}, @dfn{raising a signal}, @dfn{throwing an exception} or
722 @dfn{doing a long jump}. When the jump indicates an error condition,
723 people may talk about @dfn{signalling}, @dfn{raising} or @dfn{throwing}
724 @dfn{an error}.
725
726 @item
727 Handling the jump at its target may be referred to as @dfn{catching} or
728 @dfn{handling} the @dfn{exception}, @dfn{signal} or, where an error
729 condition is involved, @dfn{error}.
730 @end itemize
731
732 Where @dfn{signal} and @dfn{signalling} are used, special care is needed
733 to avoid the risk of confusion with POSIX signals.
734
735 This manual prefers to speak of throwing and catching exceptions, since
736 this terminology matches the corresponding Guile primitives.
737
738
739 @node Catch
740 @subsection Catching Exceptions
741
742 @code{catch} is used to set up a target for a possible non-local jump.
743 The arguments of a @code{catch} expression are a @dfn{key}, which
744 restricts the set of exceptions to which this @code{catch} applies, a
745 thunk that specifies the code to execute and a @dfn{handler} procedure
746 that says what to do if an exception is thrown while executing the code.
747 Note that if the execution thunk executes @dfn{normally}, which means
748 without throwing any exceptions, the handler procedure is not called at
749 all.
750
751 When an exception is thrown using the @code{throw} function, the first
752 argument of the @code{throw} is a symbol that indicates the type of the
753 exception. For example, Guile throws an exception using the symbol
754 @code{numerical-overflow} to indicate numerical overflow errors such as
755 division by zero:
756
757 @lisp
758 (/ 1 0)
759 @result{}
760 ABORT: (numerical-overflow)
761 @end lisp
762
763 The @var{key} argument in a @code{catch} expression corresponds to this
764 symbol. @var{key} may be a specific symbol, such as
765 @code{numerical-overflow}, in which case the @code{catch} applies
766 specifically to exceptions of that type; or it may be @code{#t}, which
767 means that the @code{catch} applies to all exceptions, irrespective of
768 their type.
769
770 The second argument of a @code{catch} expression should be a thunk
771 (i.e. a procedure that accepts no arguments) that specifies the normal
772 case code. The @code{catch} is active for the execution of this thunk,
773 including any code called directly or indirectly by the thunk's body.
774 Evaluation of the @code{catch} expression activates the catch and then
775 calls this thunk.
776
777 The third argument of a @code{catch} expression is a handler procedure.
778 If an exception is thrown, this procedure is called with exactly the
779 arguments specified by the @code{throw}. Therefore, the handler
780 procedure must be designed to accept a number of arguments that
781 corresponds to the number of arguments in all @code{throw} expressions
782 that can be caught by this @code{catch}.
783
784 @deffn {Scheme Procedure} catch key thunk handler
785 @deffnx {C Function} scm_catch (key, thunk, handler)
786 Invoke @var{thunk} in the dynamic context of @var{handler} for
787 exceptions matching @var{key}. If thunk throws to the symbol
788 @var{key}, then @var{handler} is invoked this way:
789 @lisp
790 (handler key args ...)
791 @end lisp
792
793 @var{key} is a symbol or @code{#t}.
794
795 @var{thunk} takes no arguments. If @var{thunk} returns
796 normally, that is the return value of @code{catch}.
797
798 Handler is invoked outside the scope of its own @code{catch}.
799 If @var{handler} again throws to the same key, a new handler
800 from further up the call chain is invoked.
801
802 If the key is @code{#t}, then a throw to @emph{any} symbol will
803 match this call to @code{catch}.
804 @end deffn
805
806 If the handler procedure needs to match a variety of @code{throw}
807 expressions with varying numbers of arguments, you should write it like
808 this:
809
810 @lisp
811 (lambda (key . args)
812 @dots{})
813 @end lisp
814
815 @noindent
816 The @var{key} argument is guaranteed always to be present, because a
817 @code{throw} without a @var{key} is not valid. The number and
818 interpretation of the @var{args} varies from one type of exception to
819 another, but should be specified by the documentation for each exception
820 type.
821
822 Note that, once the handler procedure is invoked, the catch that led to
823 the handler procedure being called is no longer active. Therefore, if
824 the handler procedure itself throws an exception, that exception can
825 only be caught by another active catch higher up the call stack, if
826 there is one.
827
828 @sp 1
829 @deftypefn {C Function} SCM scm_internal_catch (SCM tag, scm_t_catch_body body, void *body_data, scm_t_catch_handler handler, void *handler_data)
830 The above @code{scm_catch} takes Scheme procedures as body and handler
831 arguments. @code{scm_internal_catch} is an equivalent taking C
832 functions.
833
834 @var{body} is called as @code{@var{body} (@var{body_data})} with a
835 catch on exceptions of the given @var{tag} type. If an exception is
836 caught, @var{handler} is called @code{@var{handler}
837 (@var{handler_data}, @var{key}, @var{args})}. @var{key} and
838 @var{args} are the @code{SCM} key and argument list from the
839 @code{throw}.
840
841 @tpindex scm_t_catch_body
842 @tpindex scm_t_catch_handler
843 @var{body} and @var{handler} should have the following prototypes.
844 @code{scm_t_catch_body} and @code{scm_t_catch_handler} are pointer
845 typedefs for these.
846
847 @example
848 SCM body (void *data);
849 SCM handler (void *data, SCM key, SCM args);
850 @end example
851
852 The @var{body_data} and @var{handler_data} parameters are passed to
853 the respective calls so an application can communicate extra
854 information to those functions.
855
856 If the data consists of an @code{SCM} object, care should be taken
857 that it isn't garbage collected while still required. If the
858 @code{SCM} is a local C variable, one way to protect it is to pass a
859 pointer to that variable as the data parameter, since the C compiler
860 will then know the value must be held on the stack. Another way is to
861 use @code{scm_remember_upto_here_1} (@pxref{Remembering During
862 Operations}).
863 @end deftypefn
864
865
866 @node Throw
867 @subsection Throwing Exceptions
868
869 The @code{throw} primitive is used to throw an exception. One argument,
870 the @var{key}, is mandatory, and must be a symbol; it indicates the type
871 of exception that is being thrown. Following the @var{key},
872 @code{throw} accepts any number of additional arguments, whose meaning
873 depends on the exception type. The documentation for each possible type
874 of exception should specify the additional arguments that are expected
875 for that kind of exception.
876
877 @deffn {Scheme Procedure} throw key . args
878 @deffnx {C Function} scm_throw (key, args)
879 Invoke the catch form matching @var{key}, passing @var{args} to the
880 @var{handler}.
881
882 @var{key} is a symbol. It will match catches of the same symbol or of
883 @code{#t}.
884
885 If there is no handler at all, Guile prints an error and then exits.
886 @end deffn
887
888 When an exception is thrown, it will be caught by the innermost
889 @code{catch} expression that applies to the type of the thrown
890 exception; in other words, the innermost @code{catch} whose @var{key} is
891 @code{#t} or is the same symbol as that used in the @code{throw}
892 expression. Once Guile has identified the appropriate @code{catch}, it
893 handles the exception by applying that @code{catch} expression's handler
894 procedure to the arguments of the @code{throw}.
895
896 If there is no appropriate @code{catch} for a thrown exception, Guile
897 prints an error to the current error port indicating an uncaught
898 exception, and then exits. In practice, it is quite difficult to
899 observe this behaviour, because Guile when used interactively installs a
900 top level @code{catch} handler that will catch all exceptions and print
901 an appropriate error message @emph{without} exiting. For example, this
902 is what happens if you try to throw an unhandled exception in the
903 standard Guile REPL; note that Guile's command loop continues after the
904 error message:
905
906 @lisp
907 guile> (throw 'badex)
908 <unnamed port>:3:1: In procedure gsubr-apply @dots{}
909 <unnamed port>:3:1: unhandled-exception: badex
910 ABORT: (misc-error)
911 guile>
912 @end lisp
913
914 The default uncaught exception behaviour can be observed by evaluating a
915 @code{throw} expression from the shell command line:
916
917 @example
918 $ guile -c "(begin (throw 'badex) (display \"here\\n\"))"
919 guile: uncaught throw to badex: ()
920 $
921 @end example
922
923 @noindent
924 That Guile exits immediately following the uncaught exception
925 is shown by the absence of any output from the @code{display}
926 expression, because Guile never gets to the point of evaluating that
927 expression.
928
929
930 @node Lazy Catch
931 @subsection Catch Without Unwinding
932
933 A @dfn{lazy catch} is used in the same way as a normal @code{catch},
934 with @var{key}, @var{thunk} and @var{handler} arguments specifying the
935 exception type, normal case code and handler procedure, but differs in
936 one important respect: the handler procedure is executed without
937 unwinding the call stack from the context of the @code{throw} expression
938 that caused the handler to be invoked.
939
940 @deffn {Scheme Procedure} lazy-catch key thunk handler
941 @deffnx {C Function} scm_lazy_catch (key, thunk, handler)
942 This behaves exactly like @code{catch}, except that it does
943 not unwind the stack before invoking @var{handler}.
944 The @var{handler} procedure is not allowed to return:
945 it must throw to another catch, or otherwise exit non-locally.
946 @end deffn
947
948 @deftypefn {C Function} SCM scm_internal_lazy_catch (SCM tag, scm_t_catch_body body, void *body_data, scm_t_catch_handler handler, void *handler_data)
949 The above @code{scm_lazy_catch} takes Scheme procedures as body and
950 handler arguments. @code{scm_internal_lazy_catch} is an equivalent
951 taking C functions. See @code{scm_internal_catch} (@pxref{Catch}) for
952 a description of the parameters, the behaviour however of course
953 follows @code{lazy-catch}.
954 @end deftypefn
955
956 Typically, @var{handler} should save any desired state associated with
957 the stack at the point where the corresponding @code{throw} occurred,
958 and then throw an exception itself --- usually the same exception as the
959 one it caught. If @var{handler} is invoked and does @emph{not} throw an
960 exception, Guile itself throws an exception with key @code{misc-error}.
961
962 Not unwinding the stack means that throwing an exception that is caught
963 by a @code{lazy-catch} is @emph{almost} equivalent to calling the
964 @code{lazy-catch}'s handler inline instead of each @code{throw}, and
965 then omitting the surrounding @code{lazy-catch}. In other words,
966
967 @lisp
968 (lazy-catch 'key
969 (lambda () @dots{} (throw 'key args @dots{}) @dots{})
970 handler)
971 @end lisp
972
973 @noindent
974 is @emph{almost} equivalent to
975
976 @lisp
977 ((lambda () @dots{} (handler 'key args @dots{}) @dots{}))
978 @end lisp
979
980 @noindent
981 But why only @emph{almost}? The difference is that with
982 @code{lazy-catch} (as with normal @code{catch}), the dynamic context is
983 unwound back to just outside the @code{lazy-catch} expression before
984 invoking the handler. (For an introduction to what is meant by dynamic
985 context, @xref{Dynamic Wind}.)
986
987 Then, when the handler @emph{itself} throws an exception, that exception
988 must be caught by some kind of @code{catch} (including perhaps another
989 @code{lazy-catch}) higher up the call stack.
990
991 The dynamic context also includes @code{with-fluids} blocks (REFFIXME),
992 so the effect of unwinding the dynamic context can also be seen in fluid
993 variable values. This is illustrated by the following code, in which
994 the normal case thunk uses @code{with-fluids} to temporarily change the
995 value of a fluid:
996
997 @lisp
998 (define f (make-fluid))
999 (fluid-set! f "top level value")
1000
1001 (define (handler . args)
1002 (cons (fluid-ref f) args))
1003
1004 (lazy-catch 'foo
1005 (lambda ()
1006 (with-fluids ((f "local value"))
1007 (throw 'foo)))
1008 handler)
1009 @result{}
1010 ("top level value" foo)
1011
1012 ((lambda ()
1013 (with-fluids ((f "local value"))
1014 (handler 'foo))))
1015 @result{}
1016 ("local value" foo)
1017 @end lisp
1018
1019 @noindent
1020 In the @code{lazy-catch} version, the unwinding of dynamic context
1021 restores @code{f} to its value outside the @code{with-fluids} block
1022 before the handler is invoked, so the handler's @code{(fluid-ref f)}
1023 returns the external value.
1024
1025 @code{lazy-catch} is useful because it permits the implementation of
1026 debuggers and other reflective programming tools that need to access the
1027 state of the call stack at the exact point where an exception or an
1028 error is thrown. For an example of this, see REFFIXME:stack-catch.
1029
1030
1031 @node Exception Implementation
1032 @subsection How Guile Implements Exceptions
1033
1034 It is traditional in Scheme to implement exception systems using
1035 @code{call-with-current-continuation}. Continuations
1036 (@pxref{Continuations}) are such a powerful concept that any other
1037 control mechanism --- including @code{catch} and @code{throw} --- can be
1038 implemented in terms of them.
1039
1040 Guile does not implement @code{catch} and @code{throw} like this,
1041 though. Why not? Because Guile is specifically designed to be easy to
1042 integrate with applications written in C. In a mixed Scheme/C
1043 environment, the concept of @dfn{continuation} must logically include
1044 ``what happens next'' in the C parts of the application as well as the
1045 Scheme parts, and it turns out that the only reasonable way of
1046 implementing continuations like this is to save and restore the complete
1047 C stack.
1048
1049 So Guile's implementation of @code{call-with-current-continuation} is a
1050 stack copying one. This allows it to interact well with ordinary C
1051 code, but means that creating and calling a continuation is slowed down
1052 by the time that it takes to copy the C stack.
1053
1054 The more targeted mechanism provided by @code{catch} and @code{throw}
1055 does not need to save and restore the C stack because the @code{throw}
1056 always jumps to a location higher up the stack of the code that executes
1057 the @code{throw}. Therefore Guile implements the @code{catch} and
1058 @code{throw} primitives independently of
1059 @code{call-with-current-continuation}, in a way that takes advantage of
1060 this @emph{upwards only} nature of exceptions.
1061
1062
1063 @node Error Reporting
1064 @section Procedures for Signaling Errors
1065
1066 Guile provides a set of convenience procedures for signaling error
1067 conditions that are implemented on top of the exception primitives just
1068 described.
1069
1070 @deffn {Scheme Procedure} error msg args @dots{}
1071 Raise an error with key @code{misc-error} and a message constructed by
1072 displaying @var{msg} and writing @var{args}.
1073 @end deffn
1074
1075 @deffn {Scheme Procedure} scm-error key subr message args data
1076 @deffnx {C Function} scm_error_scm (key, subr, message, args, data)
1077 Raise an error with key @var{key}. @var{subr} can be a string
1078 naming the procedure associated with the error, or @code{#f}.
1079 @var{message} is the error message string, possibly containing
1080 @code{~S} and @code{~A} escapes. When an error is reported,
1081 these are replaced by formatting the corresponding members of
1082 @var{args}: @code{~A} (was @code{%s} in older versions of
1083 Guile) formats using @code{display} and @code{~S} (was
1084 @code{%S}) formats using @code{write}. @var{data} is a list or
1085 @code{#f} depending on @var{key}: if @var{key} is
1086 @code{system-error} then it should be a list containing the
1087 Unix @code{errno} value; If @var{key} is @code{signal} then it
1088 should be a list containing the Unix signal number; otherwise
1089 it will usually be @code{#f}.
1090 @end deffn
1091
1092 @deffn {Scheme Procedure} strerror err
1093 @deffnx {C Function} scm_strerror (err)
1094 Return the Unix error message corresponding to @var{err}, which
1095 must be an integer value.
1096 @end deffn
1097
1098 @c begin (scm-doc-string "boot-9.scm" "false-if-exception")
1099 @deffn syntax false-if-exception expr
1100 Returns the result of evaluating its argument; however
1101 if an exception occurs then @code{#f} is returned instead.
1102 @end deffn
1103 @c end
1104
1105
1106 @node Dynamic Wind
1107 @section Dynamic Wind
1108
1109 @rnindex dynamic-wind
1110 @deffn {Scheme Procedure} dynamic-wind in_guard thunk out_guard
1111 @deffnx {C Function} scm_dynamic_wind (in_guard, thunk, out_guard)
1112 All three arguments must be 0-argument procedures.
1113 @var{in_guard} is called, then @var{thunk}, then
1114 @var{out_guard}.
1115
1116 If, any time during the execution of @var{thunk}, the
1117 dynamic extent of the @code{dynamic-wind} expression is escaped
1118 non-locally, @var{out_guard} is called. If the dynamic extent of
1119 the dynamic-wind is re-entered, @var{in_guard} is called. Thus
1120 @var{in_guard} and @var{out_guard} may be called any number of
1121 times.
1122 @lisp
1123 (define x 'normal-binding)
1124 @result{} x
1125 (define a-cont (call-with-current-continuation
1126 (lambda (escape)
1127 (let ((old-x x))
1128 (dynamic-wind
1129 ;; in-guard:
1130 ;;
1131 (lambda () (set! x 'special-binding))
1132
1133 ;; thunk
1134 ;;
1135 (lambda () (display x) (newline)
1136 (call-with-current-continuation escape)
1137 (display x) (newline)
1138 x)
1139
1140 ;; out-guard:
1141 ;;
1142 (lambda () (set! x old-x)))))))
1143
1144 ;; Prints:
1145 special-binding
1146 ;; Evaluates to:
1147 @result{} a-cont
1148 x
1149 @result{} normal-binding
1150 (a-cont #f)
1151 ;; Prints:
1152 special-binding
1153 ;; Evaluates to:
1154 @result{} a-cont ;; the value of the (define a-cont...)
1155 x
1156 @result{} normal-binding
1157 a-cont
1158 @result{} special-binding
1159 @end lisp
1160 @end deffn
1161
1162 @node Frames
1163 @section Frames
1164
1165 For Scheme code, the fundamental procedure to react to non-local entry
1166 and exits of dynamic contexts is @code{dynamic-wind}. C code could use
1167 @code{scm_internal_dynamic_wind}, but since C does not allow the
1168 convenient construction of anonymous procedures that close over lexical
1169 variables, this will be, well, inconvenient. Instead, C code can use
1170 @dfn{frames}.
1171
1172 Guile offers the functions @code{scm_frame_begin} and
1173 @code{scm_frame_end} to delimit a dynamic extent. Within this dynamic
1174 extent, which is called a @dfn{frame}, you can perform various
1175 @dfn{frame actions} that control what happens when the frame is entered
1176 or left. For example, you can register a cleanup routine with
1177 @code{scm_frame_unwind} that is executed when the frame is left. There are
1178 several other more specialized frame actions as well, for example to
1179 temporarily block the execution of asyncs or to temporarily change the
1180 current output port. They are described elsewhere in this manual.
1181
1182 Here is an example that shows how to prevent memory leaks.
1183
1184 @example
1185
1186 /* Suppose there is a function called FOO in some library that you
1187 would like to make available to Scheme code (or to C code that
1188 follows the Scheme conventions).
1189
1190 FOO takes two C strings and returns a new string. When an error has
1191 occurred in FOO, it returns NULL.
1192 */
1193
1194 char *foo (char *s1, char *s2);
1195
1196 /* SCM_FOO interfaces the C function FOO to the Scheme way of life.
1197 It takes care to free up all temporary strings in the case of
1198 non-local exits.
1199
1200 It uses SCM_TO_STRING as a helper procedure.
1201 */
1202
1203 char *
1204 scm_to_string (SCM obj)
1205 @{
1206 if (SCM_STRINGP (obj))
1207 @{
1208 char *res = scm_malloc (SCM_STRING_LENGTH (obj)+1);
1209 strcpy (res, SCM_STRING_CHARS (obj));
1210 scm_remember_upto_here_1 (obj);
1211 return res;
1212 @}
1213 else
1214 scm_wrong_type_arg ("scm_to_string", 1, obj);
1215 @}
1216
1217 SCM
1218 scm_foo (SCM s1, SCM s2)
1219 @{
1220 char *c_s1, *c_s2, *c_res;
1221
1222 scm_frame_begin (0);
1223
1224 c_s1 = scm_to_string (s1);
1225 scm_frame_unwind_handler (free, c_s1, SCM_F_WIND_EXPLICITLY);
1226
1227 c_s2 = scm_to_string (s2);
1228 scm_frame_unwind_handler (free, c_s2, SCM_F_WIND_EXPLICITLY);
1229
1230 c_res = foo (c_s1, c_s2);
1231 if (c_res == NULL)
1232 scm_memory_error ("foo");
1233
1234 scm_frame_end ();
1235
1236 return scm_take0str (res);
1237 @}
1238 @end example
1239
1240 @deftp {C Type} scm_t_frame_flags
1241 This is an enumeration of several flags that modify the behavior of
1242 @code{scm_begin_frame}. The flags are listed in the following table.
1243
1244 @table @code
1245 @item SCM_F_FRAME_REWINDABLE
1246 The frame is @dfn{rewindable}. This means that it can be reentered
1247 non-locally (via the invokation of a continuation). The default is that
1248 a frame can not be reentered non-locally.
1249 @end table
1250
1251 @end deftp
1252
1253 @deftypefn {C Function} void scm_frame_begin (scm_t_frame_flags flags)
1254 The function @code{scm_begin_frame} starts a new frame and makes it the
1255 `current' one.
1256
1257 The @var{flags} argument determines the default behavior of the frame.
1258 For normal frames, use 0. This will result in a frame that can not be
1259 reentered with a captured continuation. When you are prepared to handle
1260 reentries, include @code{SCM_F_FRAME_REWINDABLE} in @var{flags}.
1261
1262 Being prepared for reentry means that the effects of unwind handlers
1263 can be undone on reentry. In the example above, we want to prevent a
1264 memory leak on non-local exit and thus register an unwind handler that
1265 frees the memory. But once the memory is freed, we can not get it
1266 back on reentry. Thus reentry can not be allowed.
1267
1268 The consequence is that continuations become less useful when
1269 non-reenterable frames are captured, but you don't need to worry about
1270 that too much.
1271
1272 The frame is ended either implicitly when a non-local exit happens, or
1273 explicitly with @code{scm_end_frame}. You must make sure that a frame
1274 is indeed ended properly. If you fail to call @code{scm_end_frame}
1275 for each @code{scm_begin_frame}, the behavior is undefined.
1276 @end deftypefn
1277
1278 @deftypefn {C Function} void scm_frame_end ()
1279 End the current frame explicitly and make the previous frame current.
1280 @end deftypefn
1281
1282 @deftp {C Type} scm_t_wind_flags
1283 This is an enumeration of several flags that modify the behavior of
1284 @code{scm_on_unwind_handler} and @code{scm_on_rewind_handler}. The
1285 flags are listed in the following table.
1286
1287 @table @code
1288 @item SCM_F_WIND_EXPLICITLY
1289 The registered action is also carried out when the frame is entered or
1290 left locally.
1291 @end table
1292 @end deftp
1293
1294 @deftypefn {C Function} void scm_frame_unwind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
1295 @deftypefnx {C Function} void scm_frame_unwind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
1296 Arranges for @var{func} to be called with @var{data} as its arguments
1297 when the current frame ends implicitly. If @var{flags} contains
1298 @code{SCM_F_WIND_EXPLICITLY}, @var{func} is also called when the frame
1299 ends explicitly with @code{scm_frame_end}.
1300
1301 The function @code{scm_frame_unwind_handler_with_scm} takes care that
1302 @var{data} is protected from garbage collection.
1303 @end deftypefn
1304
1305 @deftypefn {C Function} void scm_frame_rewind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
1306 @deftypefnx {C Function} void scm_frame_rewind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
1307 Arrange for @var{func} to be called with @var{data} as its argument when
1308 the current frame is restarted by rewinding the stack. When @var{flags}
1309 contains @code{SCM_F_WIND_EXPLICITLY}, @var{func} is called immediately
1310 as well.
1311
1312 The function @code{scm_frame_rewind_handler_with_scm} takes care that
1313 @var{data} is protected from garbage collection.
1314 @end deftypefn
1315
1316
1317 @node Handling Errors
1318 @section How to Handle Errors
1319
1320 Error handling is based on @code{catch} and @code{throw}. Errors are
1321 always thrown with a @var{key} and four arguments:
1322
1323 @itemize @bullet
1324 @item
1325 @var{key}: a symbol which indicates the type of error. The symbols used
1326 by libguile are listed below.
1327
1328 @item
1329 @var{subr}: the name of the procedure from which the error is thrown, or
1330 @code{#f}.
1331
1332 @item
1333 @var{message}: a string (possibly language and system dependent)
1334 describing the error. The tokens @code{~A} and @code{~S} can be
1335 embedded within the message: they will be replaced with members of the
1336 @var{args} list when the message is printed. @code{~A} indicates an
1337 argument printed using @code{display}, while @code{~S} indicates an
1338 argument printed using @code{write}. @var{message} can also be
1339 @code{#f}, to allow it to be derived from the @var{key} by the error
1340 handler (may be useful if the @var{key} is to be thrown from both C and
1341 Scheme).
1342
1343 @item
1344 @var{args}: a list of arguments to be used to expand @code{~A} and
1345 @code{~S} tokens in @var{message}. Can also be @code{#f} if no
1346 arguments are required.
1347
1348 @item
1349 @var{rest}: a list of any additional objects required. e.g., when the
1350 key is @code{'system-error}, this contains the C errno value. Can also
1351 be @code{#f} if no additional objects are required.
1352 @end itemize
1353
1354 In addition to @code{catch} and @code{throw}, the following Scheme
1355 facilities are available:
1356
1357 @deffn {Scheme Procedure} display-error stack port subr message args rest
1358 @deffnx {C Function} scm_display_error (stack, port, subr, message, args, rest)
1359 Display an error message to the output port @var{port}.
1360 @var{stack} is the saved stack for the error, @var{subr} is
1361 the name of the procedure in which the error occurred and
1362 @var{message} is the actual error message, which may contain
1363 formatting instructions. These will format the arguments in
1364 the list @var{args} accordingly. @var{rest} is currently
1365 ignored.
1366 @end deffn
1367
1368 The following are the error keys defined by libguile and the situations
1369 in which they are used:
1370
1371 @itemize @bullet
1372 @item
1373 @cindex @code{error-signal}
1374 @code{error-signal}: thrown after receiving an unhandled fatal signal
1375 such as SIGSEGV, SIGBUS, SIGFPE etc. The @var{rest} argument in the throw
1376 contains the coded signal number (at present this is not the same as the
1377 usual Unix signal number).
1378
1379 @item
1380 @cindex @code{system-error}
1381 @code{system-error}: thrown after the operating system indicates an
1382 error condition. The @var{rest} argument in the throw contains the
1383 errno value.
1384
1385 @item
1386 @cindex @code{numerical-overflow}
1387 @code{numerical-overflow}: numerical overflow.
1388
1389 @item
1390 @cindex @code{out-of-range}
1391 @code{out-of-range}: the arguments to a procedure do not fall within the
1392 accepted domain.
1393
1394 @item
1395 @cindex @code{wrong-type-arg}
1396 @code{wrong-type-arg}: an argument to a procedure has the wrong type.
1397
1398 @item
1399 @cindex @code{wrong-number-of-args}
1400 @code{wrong-number-of-args}: a procedure was called with the wrong number
1401 of arguments.
1402
1403 @item
1404 @cindex @code{memory-allocation-error}
1405 @code{memory-allocation-error}: memory allocation error.
1406
1407 @item
1408 @cindex @code{stack-overflow}
1409 @code{stack-overflow}: stack overflow error.
1410
1411 @item
1412 @cindex @code{regular-expression-syntax}
1413 @code{regular-expression-syntax}: errors generated by the regular
1414 expression library.
1415
1416 @item
1417 @cindex @code{misc-error}
1418 @code{misc-error}: other errors.
1419 @end itemize
1420
1421
1422 @subsection C Support
1423
1424 In the following C functions, @var{SUBR} and @var{MESSAGE} parameters
1425 can be @code{NULL} to give the effect of @code{#f} described above.
1426
1427 @deftypefn {C Function} SCM scm_error (SCM @var{key}, char *@var{subr}, char *@var{message}, SCM @var{args}, SCM @var{rest})
1428 Throw an error, as per @code{scm-error} above.
1429 @end deftypefn
1430
1431 @deftypefn {C Function} void scm_syserror (char *@var{subr})
1432 @deftypefnx {C Function} void scm_syserror_msg (char *@var{subr}, char *@var{message}, SCM @var{args})
1433 Throw an error with key @code{system-error} and supply @code{errno} in
1434 the @var{rest} argument. For @code{scm_syserror} the message is
1435 generated using @code{strerror}.
1436
1437 Care should be taken that any code in between the failing operation
1438 and the call to these routines doesn't change @code{errno}.
1439 @end deftypefn
1440
1441 @deftypefn {C Function} void scm_num_overflow (char *@var{subr})
1442 @deftypefnx {C Function} void scm_out_of_range (char *@var{subr}, SCM @var{bad_value})
1443 @deftypefnx {C Function} void scm_wrong_num_args (SCM @var{proc})
1444 @deftypefnx {C Function} void scm_wrong_type_arg (char *@var{subr}, int @var{argnum}, SCM @var{bad_value})
1445 @deftypefnx {C Function} void scm_memory_error (char *@var{subr})
1446 Throw an error with the various keys described above.
1447
1448 For @code{scm_wrong_num_args}, @var{proc} should be a Scheme symbol
1449 which is the name of the procedure incorrectly invoked.
1450 @end deftypefn
1451
1452
1453 @c Local Variables:
1454 @c TeX-master: "guile.texi"
1455 @c End: