Added P Pareit.
[bpt/guile.git] / doc / ref / scheme-control.texi
1 @page
2 @node Control Mechanisms
3 @chapter Controlling the Flow of Program Execution
4
5 @menu
6 * begin:: Evaluating a sequence of expressions.
7 * if cond case:: Simple conditional evaluation.
8 * and or:: Conditional evaluation of a sequence.
9 * while do:: Iteration mechanisms.
10 * Continuations:: Continuations.
11 * Multiple Values:: Returning and accepting multiple values.
12 * Exceptions:: Throwing and catching exceptions.
13 * Error Reporting:: Procedures for signaling errors.
14 * Dynamic Wind:: Guarding against non-local entrance/exit.
15 * Handling Errors:: How to handle errors in C code.
16 @end menu
17
18
19 @node begin
20 @section Evaluating a Sequence of Expressions
21
22 @c FIXME::martin: Review me!
23
24 @c FIXME::martin: Maybe add examples?
25
26 @cindex begin
27 @cindex sequencing
28 @cindex expression sequencing
29
30 @code{begin} is used for grouping several expression together so that
31 they syntactically are treated as if they were one expression. This is
32 particularly important when syntactic expressions are used which only
33 allow one expression, but the programmer wants to use more than one
34 expression in that place. As an example, consider the conditional
35 expression below:
36
37 @lisp
38 (if (> x 0)
39 (begin (display "greater") (newline)))
40 @end lisp
41
42 If the two calls to @code{display} and @code{newline} were not embedded
43 in a @code{begin}-statement, the call to @code{newline} would get
44 misinterpreted as the else-branch of the @code{if}-expression.
45
46 @deffn syntax begin expr1 expr2 @dots{}
47 The expression(s) are evaluated in left-to-right order and the value
48 of the last expression is returned as the value of the
49 @code{begin}-expression. This expression type is used when the
50 expressions before the last one are evaluated for their side effects.
51 @end deffn
52
53 @node if cond case
54 @section Simple Conditional Evaluation
55
56 @c FIXME::martin: Review me!
57
58 @c FIXME::martin: Maybe add examples?
59
60 @cindex conditional evaluation
61 @cindex if
62 @cindex case
63 @cindex cond
64
65 Guile provides three syntactic constructs for conditional evaluation.
66 @code{if} is the normal if-then-else expression (with an optional else
67 branch), @code{cond} is a conditional expression with multiple branches
68 and @code{case} branches if an expression has one of a set of constant
69 values.
70
71 @deffn syntax if test consequent [alternate]
72 All arguments may be arbitrary expressions. First, @var{test} is
73 evaluated. If it returns a true value, the expression @var{consequent}
74 is evaluated and @var{alternate} is ignored. If @var{test} evaluates to
75 @code{#f}, @var{alternate} is evaluated instead. The value of the
76 evaluated branch (@var{consequent} or @var{alternate}) is returned as
77 the value of the @code{if} expression.
78
79 When @var{alternate} is omitted and the @var{test} evaluates to
80 @code{#f}, the value of the expression is not specified.
81 @end deffn
82
83 @deffn syntax cond clause1 clause2 @dots{}
84 Each @code{cond}-clause must look like this:
85
86 @lisp
87 (@var{test} @var{expression} @dots{})
88 @end lisp
89
90 where @var{test} and @var{expression} are arbitrary expression, or like
91 this
92
93 @lisp
94 (@var{test} => @var{expression}
95 @end lisp
96
97 where @var{expression} must evaluate to a procedure.
98
99 The @var{test}s of the clauses are evaluated in order and as soon as one
100 of them evaluates to a true values, the corresponding @var{expression}s
101 are evaluated in order and the last value is returned as the value of
102 the @code{cond}-expression. For the @code{=>} clause type,
103 @var{expression} is evaluated and the resulting procedure is applied to
104 the value of @var{test}. The result of this procedure application is
105 then the result of the @code{cond}-expression.
106
107 The @var{test} of the last @var{clause} may be the keyword @code{else}.
108 Then, if none of the preceding @var{test}s is true, the @var{expression}s following the @code{else} are evaluated to produce the result of the @code{cond}-expression.
109 @end deffn
110
111 @deffn syntax case key clause1 clause2 @dots{}
112 @var{key} may be any expression, the @var{clause}s must have the form
113
114 @lisp
115 ((@var{datum1} @dots{}) @var{expr1} @var{expr2} @dots{})
116 @end lisp
117
118 and the last @var{clause} may have the form
119
120 @lisp
121 (else @var{expr1} @var{expr2} @dots{})
122 @end lisp
123
124 All @var{datum}s must be distinct. First, @var{key} is evaluated. The
125 the result of this evaluation is compared against all @var{datum}s using
126 @code{eqv?}. When this comparison succeeds, the expression(s) following
127 the @var{datum} are evaluated from left to right, returning the value of
128 the last expression as the result of the @code{case} expression.
129
130 If the @var{key} matches no @var{datum} and there is an
131 @code{else}-clause, the expressions following the @code{else} are
132 evaluated. If there is no such clause, the result of the expression is
133 unspecified.
134 @end deffn
135
136
137 @node and or
138 @section Conditional Evaluation of a Sequence of Expressions
139
140 @c FIXME::martin: Review me!
141
142 @c FIXME::martin: Maybe add examples?
143
144 @code{and} and @code{or} evaluate all their arguments, similar to
145 @code{begin}, but evaluation stops as soon as one of the expressions
146 evaluates to false or true, respectively.
147
148 @deffn syntax and expr @dots{}
149 Evaluate the @var{expr}s from left to right and stop evaluation as soon
150 as one expression evaluates to @code{#f}; the remaining expressions are
151 not evaluated. The value of the last evaluated expression is returned.
152 If no expression evaluates to @code{#f}, the value of the last
153 expression is returned.
154
155 If used without expressions, @code{#t} is returned.
156 @end deffn
157
158 @deffn syntax or expr @dots{}
159 Evaluate the @var{expr}s from left to right and stop evaluation as soon
160 as one expression evaluates to a true value (that is, a value different
161 from @code{#f}); the remaining expressions are not evaluated. The value
162 of the last evaluated expression is returned. If all expressions
163 evaluate to @code{#f}, @code{#f} is returned.
164
165 If used without expressions, @code{#f} is returned.
166 @end deffn
167
168
169 @node while do
170 @section Iteration mechanisms
171
172 @c FIXME::martin: Review me!
173
174 @c FIXME::martin: Maybe add examples?
175
176 @cindex iteration
177 @cindex looping
178 @cindex named let
179
180 Scheme has only few iteration mechanisms, mainly because iteration in
181 Scheme programs is normally expressed using recursion. Nevertheless,
182 R5RS defines a construct for programming loops, calling @code{do}. In
183 addition, Guile has an explicit looping syntax called @code{while}.
184
185 @deffn syntax do ((variable1 init1 step1) @dots{}) (test expr @dots{}) command @dots{}
186 The @var{init} expressions are evaluated and the @var{variables} are
187 bound to their values. Then looping starts with testing the @var{test}
188 expression. If @var{test} evaluates to a true value, the @var{expr}
189 following the @var{test} are evaluated and the value of the last
190 @var{expr} is returned as the value of the @code{do} expression. If
191 @var{test} evaluates to false, the @var{command}s are evaluated in
192 order, the @var{step}s are evaluated and stored into the @var{variables}
193 and the next iteration starts.
194
195 Any of the @var{step} expressions may be omitted, so that the
196 corresponding variable is not changed during looping.
197 @end deffn
198
199 @deffn syntax while cond body @dots{}
200 Evaluate all expressions in @var{body} in order, as long as @var{cond}
201 evaluates to a true value. The @var{cond} expression is tested before
202 every iteration, so that the body is not evaluated at all if @var{cond}
203 is @code{#f} right from the start.
204 @end deffn
205
206 @cindex named let
207 Another very common way of expressing iteration in Scheme programs is
208 the use of the so-called @dfn{named let}.
209
210 Named let is a variant of @code{let} which creates a procedure and calls
211 it in one step. Because of the newly created procedure, named let is
212 more powerful than @code{do}--it can be used for iteration, but also
213 for arbitrary recursion.
214
215 @deffn syntax let variable bindings body
216 For the definition of @var{bindings} see the documentation about
217 @code{let} (@pxref{Local Bindings}).
218
219 Named @code{let} works as follows:
220
221 @itemize @bullet
222 @item
223 A new procedure which accepts as many arguments as are in @var{bindings}
224 is created and bound locally (using @code{let}) to @var{variable}. The
225 new procedure's formal argument names are the name of the
226 @var{variables}.
227
228 @item
229 The @var{body} expressions are inserted into the newly created procedure.
230
231 @item
232 The procedure is called with the @var{init} expressions as the formal
233 arguments.
234 @end itemize
235
236 The next example implements a loop which iterates (by recursion) 1000
237 times.
238
239 @lisp
240 (let lp ((x 1000))
241 (if (positive? x)
242 (lp (- x 1))
243 x))
244 @result{}
245 0
246 @end lisp
247 @end deffn
248
249
250 @node Continuations
251 @section Continuations
252
253 @cindex call/cc
254 @cindex call-with-current-continuation
255 The ability to explicitly capture continuations using
256 @code{call-with-current-continuation} (also often called @code{call/cc}
257 for short), and to invoke such continuations later any number of times,
258 and from any other point in a program, provides maybe the most powerful
259 control structure known. All other control structures, such as loops
260 and coroutines, can be emulated using continuations.
261
262 @c NJFIXME - need a little something here about what continuations are
263 @c and what they do for you.
264
265 The implementation of continuations in Guile is not as efficient as one
266 might hope, because it is constrained by the fact that Guile is designed
267 to cooperate with programs written in other languages, such as C, which
268 do not know about continuations. So continuations should be used when
269 there is no other simple way of achieving the desired behaviour, or
270 where the advantages of the elegant continuation mechanism outweigh the
271 need for optimum performance. If you find yourself using @code{call/cc}
272 for escape procedures and your program is running too slow, you might
273 want to use exceptions (@pxref{Exceptions}) instead.
274
275 @rnindex call-with-current-continuation
276 @deffn {Scheme Procedure} call-with-current-continuation proc
277 Capture the current continuation and call @var{proc} with the captured
278 continuation as the single argument. This continuation can then be
279 called with arbitrarily many arguments. Such a call will work like a
280 goto to the invocation location of
281 @code{call-with-current-continuation}, passing the arguments in a way
282 that they are returned by the call to
283 @code{call-with-current-continuation}. Since it is legal to store the
284 captured continuation in a variable or to pass it to other procedures,
285 it is possible that a procedure returns more than once, even if it is
286 called only one time. This can be confusing at times.
287 @end deffn
288
289 @c FIXME::martin: Better example needed.
290 @lisp
291 (define kont #f)
292 (call-with-current-continuation
293 (lambda (k)
294 (set! kont k)
295 1))
296 @result{}
297 1
298
299 (kont 2)
300 @result{}
301 2
302 @end lisp
303
304
305 @node Multiple Values
306 @section Returning and Accepting Multiple Values
307
308 @c FIXME::martin: Review me!
309 @cindex multiple values
310 @cindex receive
311
312 Scheme allows a procedure to return more than one value to its caller.
313 This is quite different to other languages which only allow
314 single-value returns. Returning multiple values is different from
315 returning a list (or pair or vector) of values to the caller, because
316 conceptually not @emph{one} compound object is returned, but several
317 distinct values.
318
319 The primitive procedures for handling multiple values are @code{values}
320 and @code{call-with-values}. @code{values} is used for returning
321 multiple values from a procedure. This is done by placing a call to
322 @code{values} with zero or more arguments in tail position in a
323 procedure body. @code{call-with-values} combines a procedure returning
324 multiple values with a procedure which accepts these values as
325 parameters.
326
327 @rnindex values
328 @deffn {Scheme Procedure} values . args
329 @deffnx {C Function} scm_values (args)
330 Delivers all of its arguments to its continuation. Except for
331 continuations created by the @code{call-with-values} procedure,
332 all continuations take exactly one value. The effect of
333 passing no value or more than one value to continuations that
334 were not created by @code{call-with-values} is unspecified.
335 @end deffn
336
337 @rnindex call-with-values
338 @deffn {Scheme Procedure} call-with-values producer consumer
339 Calls its @var{producer} argument with no values and a
340 continuation that, when passed some values, calls the
341 @var{consumer} procedure with those values as arguments. The
342 continuation for the call to @var{consumer} is the continuation
343 of the call to @code{call-with-values}.
344
345 @example
346 (call-with-values (lambda () (values 4 5))
347 (lambda (a b) b))
348 ==> 5
349
350 @end example
351 @example
352 (call-with-values * -) ==> -1
353 @end example
354 @end deffn
355
356 In addition to the fundamental procedures described above, Guile has a
357 module which exports a syntax called @code{receive}, which is much more
358 convenient. If you want to use it in your programs, you have to load
359 the module @code{(ice-9 receive)} with the statement
360
361 @lisp
362 (use-modules (ice-9 receive))
363 @end lisp
364
365 @deffn {library syntax} receive formals expr body @dots{}
366 Evaluate the expression @var{expr}, and bind the result values (zero or
367 more) to the formal arguments in the formal argument list @var{formals}.
368 @var{formals} must have the same syntax like the formal argument list
369 used in @code{lambda} (@pxref{Lambda}). After binding the variables,
370 the expressions in @var{body} @dots{} are evaluated in order.
371 @end deffn
372
373
374 @node Exceptions
375 @section Exceptions
376 @cindex error handling
377 @cindex exception handling
378
379 A common requirement in applications is to want to jump
380 @dfn{non-locally} from the depths of a computation back to, say, the
381 application's main processing loop. Usually, the place that is the
382 target of the jump is somewhere in the calling stack of procedures that
383 called the procedure that wants to jump back. For example, typical
384 logic for a key press driven application might look something like this:
385
386 @example
387 main-loop:
388 read the next key press and call dispatch-key
389
390 dispatch-key:
391 lookup the key in a keymap and call an appropriate procedure,
392 say find-file
393
394 find-file:
395 interactively read the required file name, then call
396 find-specified-file
397
398 find-specified-file:
399 check whether file exists; if not, jump back to main-loop
400 @dots{}
401 @end example
402
403 The jump back to @code{main-loop} could be achieved by returning through
404 the stack one procedure at a time, using the return value of each
405 procedure to indicate the error condition, but Guile (like most modern
406 programming languages) provides an additional mechanism called
407 @dfn{exception handling} that can be used to implement such jumps much
408 more conveniently.
409
410 @menu
411 * Exception Terminology:: Different ways to say the same thing.
412 * Catch:: Setting up to catch exceptions.
413 * Throw:: Throwing an exception.
414 * Lazy Catch:: Catch without unwinding the stack.
415 * Exception Implementation:: How Guile implements exceptions.
416 @end menu
417
418
419 @node Exception Terminology
420 @subsection Exception Terminology
421
422 There are several variations on the terminology for dealing with
423 non-local jumps. It is useful to be aware of them, and to realize
424 that they all refer to the same basic mechanism.
425
426 @itemize @bullet
427 @item
428 Actually making a non-local jump may be called @dfn{raising an
429 exception}, @dfn{raising a signal}, @dfn{throwing an exception} or
430 @dfn{doing a long jump}. When the jump indicates an error condition,
431 people may talk about @dfn{signalling}, @dfn{raising} or @dfn{throwing}
432 @dfn{an error}.
433
434 @item
435 Handling the jump at its target may be referred to as @dfn{catching} or
436 @dfn{handling} the @dfn{exception}, @dfn{signal} or, where an error
437 condition is involved, @dfn{error}.
438 @end itemize
439
440 Where @dfn{signal} and @dfn{signalling} are used, special care is needed
441 to avoid the risk of confusion with POSIX signals. (Especially
442 considering that Guile handles POSIX signals by throwing a corresponding
443 kind of exception: REFFIXME.)
444
445 This manual prefers to speak of throwing and catching exceptions, since
446 this terminology matches the corresponding Guile primitives.
447
448
449 @node Catch
450 @subsection Catching Exceptions
451
452 @code{catch} is used to set up a target for a possible non-local jump.
453 The arguments of a @code{catch} expression are a @dfn{key}, which
454 restricts the set of exceptions to which this @code{catch} applies, a
455 thunk that specifies the @dfn{normal case} code --- i.e. what should
456 happen if no exceptions are thrown --- and a @dfn{handler} procedure
457 that says what to do if an exception is thrown. Note that if the
458 @dfn{normal case} thunk executes @dfn{normally}, which means without
459 throwing any exceptions, the handler procedure is not executed at all.
460
461 When an exception is thrown using the @code{throw} primitive, the first
462 argument of the @code{throw} is a symbol that indicates the type of the
463 exception. For example, Guile throws an exception using the symbol
464 @code{numerical-overflow} to indicate numerical overflow errors such as
465 division by zero:
466
467 @lisp
468 (/ 1 0)
469 @result{}
470 ABORT: (numerical-overflow)
471 @end lisp
472
473 The @var{key} argument in a @code{catch} expression corresponds to this
474 symbol. @var{key} may be a specific symbol, such as
475 @code{numerical-overflow}, in which case the @code{catch} applies
476 specifically to exceptions of that type; or it may be @code{#t}, which
477 means that the @code{catch} applies to all exceptions, irrespective of
478 their type.
479
480 The second argument of a @code{catch} expression should be a thunk
481 (i.e. a procedure that accepts no arguments) that specifies the normal
482 case code. The @code{catch} is active for the execution of this thunk,
483 including any code called directly or indirectly by the thunk's body.
484 Evaluation of the @code{catch} expression activates the catch and then
485 calls this thunk.
486
487 The third argument of a @code{catch} expression is a handler procedure.
488 If an exception is thrown, this procedure is called with exactly the
489 arguments specified by the @code{throw}. Therefore, the handler
490 procedure must be designed to accept a number of arguments that
491 corresponds to the number of arguments in all @code{throw} expressions
492 that can be caught by this @code{catch}.
493
494 @deffn {Scheme Procedure} catch key thunk handler
495 @deffnx {C Function} scm_catch (key, thunk, handler)
496 Invoke @var{thunk} in the dynamic context of @var{handler} for
497 exceptions matching @var{key}. If thunk throws to the symbol
498 @var{key}, then @var{handler} is invoked this way:
499 @lisp
500 (handler key args ...)
501 @end lisp
502
503 @var{key} is a symbol or @code{#t}.
504
505 @var{thunk} takes no arguments. If @var{thunk} returns
506 normally, that is the return value of @code{catch}.
507
508 Handler is invoked outside the scope of its own @code{catch}.
509 If @var{handler} again throws to the same key, a new handler
510 from further up the call chain is invoked.
511
512 If the key is @code{#t}, then a throw to @emph{any} symbol will
513 match this call to @code{catch}.
514 @end deffn
515
516 If the handler procedure needs to match a variety of @code{throw}
517 expressions with varying numbers of arguments, you should write it like
518 this:
519
520 @lisp
521 (lambda (key . args)
522 @dots{})
523 @end lisp
524
525 @noindent
526 The @var{key} argument is guaranteed always to be present, because a
527 @code{throw} without a @var{key} is not valid. The number and
528 interpretation of the @var{args} varies from one type of exception to
529 another, but should be specified by the documentation for each exception
530 type.
531
532 Note that, once the handler procedure is invoked, the catch that led to
533 the handler procedure being called is no longer active. Therefore, if
534 the handler procedure itself throws an exception, that exception can
535 only be caught by another active catch higher up the call stack, if
536 there is one.
537
538
539 @node Throw
540 @subsection Throwing Exceptions
541
542 The @code{throw} primitive is used to throw an exception. One argument,
543 the @var{key}, is mandatory, and must be a symbol; it indicates the type
544 of exception that is being thrown. Following the @var{key},
545 @code{throw} accepts any number of additional arguments, whose meaning
546 depends on the exception type. The documentation for each possible type
547 of exception should specify the additional arguments that are expected
548 for that kind of exception.
549
550 @deffn {Scheme Procedure} throw key . args
551 @deffnx {C Function} scm_throw (key, args)
552 Invoke the catch form matching @var{key}, passing @var{args} to the
553 @var{handler}.
554
555 @var{key} is a symbol. It will match catches of the same symbol or of
556 @code{#t}.
557
558 If there is no handler at all, Guile prints an error and then exits.
559 @end deffn
560
561 When an exception is thrown, it will be caught by the innermost
562 @code{catch} expression that applies to the type of the thrown
563 exception; in other words, the innermost @code{catch} whose @var{key} is
564 @code{#t} or is the same symbol as that used in the @code{throw}
565 expression. Once Guile has identified the appropriate @code{catch}, it
566 handles the exception by applying that @code{catch} expression's handler
567 procedure to the arguments of the @code{throw}.
568
569 If there is no appropriate @code{catch} for a thrown exception, Guile
570 prints an error to the current error port indicating an uncaught
571 exception, and then exits. In practice, it is quite difficult to
572 observe this behaviour, because Guile when used interactively installs a
573 top level @code{catch} handler that will catch all exceptions and print
574 an appropriate error message @emph{without} exiting. For example, this
575 is what happens if you try to throw an unhandled exception in the
576 standard Guile REPL; note that Guile's command loop continues after the
577 error message:
578
579 @lisp
580 guile> (throw 'badex)
581 <unnamed port>:3:1: In procedure gsubr-apply @dots{}
582 <unnamed port>:3:1: unhandled-exception: badex
583 ABORT: (misc-error)
584 guile>
585 @end lisp
586
587 The default uncaught exception behaviour can be observed by evaluating a
588 @code{throw} expression from the shell command line:
589
590 @example
591 $ guile -c "(begin (throw 'badex) (display \"here\\n\"))"
592 guile: uncaught throw to badex: ()
593 $
594 @end example
595
596 @noindent
597 That Guile exits immediately following the uncaught exception
598 is shown by the absence of any output from the @code{display}
599 expression, because Guile never gets to the point of evaluating that
600 expression.
601
602
603 @node Lazy Catch
604 @subsection Catch Without Unwinding
605
606 A @dfn{lazy catch} is used in the same way as a normal @code{catch},
607 with @var{key}, @var{thunk} and @var{handler} arguments specifying the
608 exception type, normal case code and handler procedure, but differs in
609 one important respect: the handler procedure is executed without
610 unwinding the call stack from the context of the @code{throw} expression
611 that caused the handler to be invoked.
612
613 @deffn {Scheme Procedure} lazy-catch key thunk handler
614 @deffnx {C Function} scm_lazy_catch (key, thunk, handler)
615 This behaves exactly like @code{catch}, except that it does
616 not unwind the stack before invoking @var{handler}.
617 The @var{handler} procedure is not allowed to return:
618 it must throw to another catch, or otherwise exit non-locally.
619 @end deffn
620
621 Typically, @var{handler} should save any desired state associated with
622 the stack at the point where the corresponding @code{throw} occurred,
623 and then throw an exception itself --- usually the same exception as the
624 one it caught. If @var{handler} is invoked and does @emph{not} throw an
625 exception, Guile itself throws an exception with key @code{misc-error}.
626
627 Not unwinding the stack means that throwing an exception that is caught
628 by a @code{lazy-catch} is @emph{almost} equivalent to calling the
629 @code{lazy-catch}'s handler inline instead of each @code{throw}, and
630 then omitting the surrounding @code{lazy-catch}. In other words,
631
632 @lisp
633 (lazy-catch 'key
634 (lambda () @dots{} (throw 'key args @dots{}) @dots{})
635 handler)
636 @end lisp
637
638 @noindent
639 is @emph{almost} equivalent to
640
641 @lisp
642 ((lambda () @dots{} (handler 'key args @dots{}) @dots{}))
643 @end lisp
644
645 @noindent
646 But why only @emph{almost}? The difference is that with
647 @code{lazy-catch} (as with normal @code{catch}), the dynamic context is
648 unwound back to just outside the @code{lazy-catch} expression before
649 invoking the handler. (For an introduction to what is meant by dynamic
650 context, @xref{Dynamic Wind}.)
651
652 Then, when the handler @emph{itself} throws an exception, that exception
653 must be caught by some kind of @code{catch} (including perhaps another
654 @code{lazy-catch}) higher up the call stack.
655
656 The dynamic context also includes @code{with-fluids} blocks (REFFIXME),
657 so the effect of unwinding the dynamic context can also be seen in fluid
658 variable values. This is illustrated by the following code, in which
659 the normal case thunk uses @code{with-fluids} to temporarily change the
660 value of a fluid:
661
662 @lisp
663 (define f (make-fluid))
664 (fluid-set! f "top level value")
665
666 (define (handler . args)
667 (cons (fluid-ref f) args))
668
669 (lazy-catch 'foo
670 (lambda ()
671 (with-fluids ((f "local value"))
672 (throw 'foo)))
673 handler)
674 @result{}
675 ("top level value" foo)
676
677 ((lambda ()
678 (with-fluids ((f "local value"))
679 (handler 'foo))))
680 @result{}
681 ("local value" foo)
682 @end lisp
683
684 @noindent
685 In the @code{lazy-catch} version, the unwinding of dynamic context
686 restores @code{f} to its value outside the @code{with-fluids} block
687 before the handler is invoked, so the handler's @code{(fluid-ref f)}
688 returns the external value.
689
690 @code{lazy-catch} is useful because it permits the implementation of
691 debuggers and other reflective programming tools that need to access the
692 state of the call stack at the exact point where an exception or an
693 error is thrown. For an example of this, see REFFIXME:stack-catch.
694
695
696 @node Exception Implementation
697 @subsection How Guile Implements Exceptions
698
699 It is traditional in Scheme to implement exception systems using
700 @code{call-with-current-continuation}. Continuations
701 (@pxref{Continuations}) are such a powerful concept that any other
702 control mechanism --- including @code{catch} and @code{throw} --- can be
703 implemented in terms of them.
704
705 Guile does not implement @code{catch} and @code{throw} like this,
706 though. Why not? Because Guile is specifically designed to be easy to
707 integrate with applications written in C. In a mixed Scheme/C
708 environment, the concept of @dfn{continuation} must logically include
709 ``what happens next'' in the C parts of the application as well as the
710 Scheme parts, and it turns out that the only reasonable way of
711 implementing continuations like this is to save and restore the complete
712 C stack.
713
714 So Guile's implementation of @code{call-with-current-continuation} is a
715 stack copying one. This allows it to interact well with ordinary C
716 code, but means that creating and calling a continuation is slowed down
717 by the time that it takes to copy the C stack.
718
719 The more targeted mechanism provided by @code{catch} and @code{throw}
720 does not need to save and restore the C stack because the @code{throw}
721 always jumps to a location higher up the stack of the code that executes
722 the @code{throw}. Therefore Guile implements the @code{catch} and
723 @code{throw} primitives independently of
724 @code{call-with-current-continuation}, in a way that takes advantage of
725 this @emph{upwards only} nature of exceptions.
726
727
728 @node Error Reporting
729 @section Procedures for Signaling Errors
730
731 Guile provides a set of convenience procedures for signaling error
732 conditions that are implemented on top of the exception primitives just
733 described.
734
735 @deffn {Scheme Procedure} error msg args @dots{}
736 Raise an error with key @code{misc-error} and a message constructed by
737 displaying @var{msg} and writing @var{args}.
738 @end deffn
739
740 @deffn {Scheme Procedure} scm-error key subr message args data
741 @deffnx {C Function} scm_error_scm (key, subr, message, args, data)
742 Raise an error with key @var{key}. @var{subr} can be a string
743 naming the procedure associated with the error, or @code{#f}.
744 @var{message} is the error message string, possibly containing
745 @code{~S} and @code{~A} escapes. When an error is reported,
746 these are replaced by formatting the corresponding members of
747 @var{args}: @code{~A} (was @code{%s} in older versions of
748 Guile) formats using @code{display} and @code{~S} (was
749 @code{%S}) formats using @code{write}. @var{data} is a list or
750 @code{#f} depending on @var{key}: if @var{key} is
751 @code{system-error} then it should be a list containing the
752 Unix @code{errno} value; If @var{key} is @code{signal} then it
753 should be a list containing the Unix signal number; otherwise
754 it will usually be @code{#f}.
755 @end deffn
756
757 @deffn {Scheme Procedure} strerror err
758 @deffnx {C Function} scm_strerror (err)
759 Return the Unix error message corresponding to @var{err}, which
760 must be an integer value.
761 @end deffn
762
763 @c begin (scm-doc-string "boot-9.scm" "false-if-exception")
764 @deffn syntax false-if-exception expr
765 Returns the result of evaluating its argument; however
766 if an exception occurs then @code{#f} is returned instead.
767 @end deffn
768 @c end
769
770
771 @node Dynamic Wind
772 @section Dynamic Wind
773
774 [FIXME: this is pasted in from Tom Lord's original guile.texi and should
775 be reviewed]
776
777 @rnindex dynamic-wind
778 @deffn {Scheme Procedure} dynamic-wind in_guard thunk out_guard
779 @deffnx {C Function} scm_dynamic_wind (in_guard, thunk, out_guard)
780 All three arguments must be 0-argument procedures.
781 @var{in_guard} is called, then @var{thunk}, then
782 @var{out_guard}.
783
784 If, any time during the execution of @var{thunk}, the
785 continuation of the @code{dynamic_wind} expression is escaped
786 non-locally, @var{out_guard} is called. If the continuation of
787 the dynamic-wind is re-entered, @var{in_guard} is called. Thus
788 @var{in_guard} and @var{out_guard} may be called any number of
789 times.
790 @lisp
791 (define x 'normal-binding)
792 @result{} x
793 (define a-cont (call-with-current-continuation
794 (lambda (escape)
795 (let ((old-x x))
796 (dynamic-wind
797 ;; in-guard:
798 ;;
799 (lambda () (set! x 'special-binding))
800
801 ;; thunk
802 ;;
803 (lambda () (display x) (newline)
804 (call-with-current-continuation escape)
805 (display x) (newline)
806 x)
807
808 ;; out-guard:
809 ;;
810 (lambda () (set! x old-x)))))))
811
812 ;; Prints:
813 special-binding
814 ;; Evaluates to:
815 @result{} a-cont
816 x
817 @result{} normal-binding
818 (a-cont #f)
819 ;; Prints:
820 special-binding
821 ;; Evaluates to:
822 @result{} a-cont ;; the value of the (define a-cont...)
823 x
824 @result{} normal-binding
825 a-cont
826 @result{} special-binding
827 @end lisp
828 @end deffn
829
830
831 @node Handling Errors
832 @section How to Handle Errors in C Code
833
834 Error handling is based on @code{catch} and @code{throw}. Errors are
835 always thrown with a @var{key} and four arguments:
836
837 @itemize @bullet
838 @item
839 @var{key}: a symbol which indicates the type of error. The symbols used
840 by libguile are listed below.
841
842 @item
843 @var{subr}: the name of the procedure from which the error is thrown, or
844 @code{#f}.
845
846 @item
847 @var{message}: a string (possibly language and system dependent)
848 describing the error. The tokens @code{~A} and @code{~S} can be
849 embedded within the message: they will be replaced with members of the
850 @var{args} list when the message is printed. @code{~A} indicates an
851 argument printed using @code{display}, while @code{~S} indicates an
852 argument printed using @code{write}. @var{message} can also be
853 @code{#f}, to allow it to be derived from the @var{key} by the error
854 handler (may be useful if the @var{key} is to be thrown from both C and
855 Scheme).
856
857 @item
858 @var{args}: a list of arguments to be used to expand @code{~A} and
859 @code{~S} tokens in @var{message}. Can also be @code{#f} if no
860 arguments are required.
861
862 @item
863 @var{rest}: a list of any additional objects required. e.g., when the
864 key is @code{'system-error}, this contains the C errno value. Can also
865 be @code{#f} if no additional objects are required.
866 @end itemize
867
868 In addition to @code{catch} and @code{throw}, the following Scheme
869 facilities are available:
870
871 @deffn {Scheme Procedure} scm-error key subr message args rest
872 Throw an error, with arguments
873 as described above.
874 @end deffn
875
876 @deffn {Scheme Procedure} error msg arg @dots{}
877 Throw an error using the key @code{'misc-error}. The error
878 message is created by displaying @var{msg} and writing the @var{args}.
879 @end deffn
880
881 @deffn {Scheme Procedure} display-error stack port subr message args rest
882 @deffnx {C Function} scm_display_error (stack, port, subr, message, args, rest)
883 Display an error message to the output port @var{port}.
884 @var{stack} is the saved stack for the error, @var{subr} is
885 the name of the procedure in which the error occurred and
886 @var{message} is the actual error message, which may contain
887 formatting instructions. These will format the arguments in
888 the list @var{args} accordingly. @var{rest} is currently
889 ignored.
890 @end deffn
891
892 The following are the error keys defined by libguile and the situations
893 in which they are used:
894
895 @itemize @bullet
896 @item
897 @code{error-signal}: thrown after receiving an unhandled fatal signal
898 such as SIGSEGV, SIGBUS, SIGFPE etc. The @var{rest} argument in the throw
899 contains the coded signal number (at present this is not the same as the
900 usual Unix signal number).
901
902 @item
903 @code{system-error}: thrown after the operating system indicates an
904 error condition. The @var{rest} argument in the throw contains the
905 errno value.
906
907 @item
908 @code{numerical-overflow}: numerical overflow.
909
910 @item
911 @code{out-of-range}: the arguments to a procedure do not fall within the
912 accepted domain.
913
914 @item
915 @code{wrong-type-arg}: an argument to a procedure has the wrong type.
916
917 @item
918 @code{wrong-number-of-args}: a procedure was called with the wrong number
919 of arguments.
920
921 @item
922 @code{memory-allocation-error}: memory allocation error.
923
924 @item
925 @code{stack-overflow}: stack overflow error.
926
927 @item
928 @code{regex-error}: errors generated by the regular expression library.
929
930 @item
931 @code{misc-error}: other errors.
932 @end itemize
933
934
935 @subsection C Support
936
937 SCM scm_error (SCM key, char *subr, char *message, SCM args, SCM rest)
938
939 Throws an error, after converting the char * arguments to Scheme strings.
940 subr is the Scheme name of the procedure, NULL is converted to #f.
941 Likewise a NULL message is converted to #f.
942
943 The following procedures invoke scm_error with various error keys and
944 arguments. The first three call scm_error with the system-error key
945 and automatically supply errno in the "rest" argument: scm_syserror
946 generates messages using strerror, scm_sysmissing is used when
947 facilities are not available. Care should be taken that the errno
948 value is not reset (e.g. due to an interrupt).
949
950 @itemize @bullet
951 @item
952 void scm_syserror (char *subr);
953 @item
954 void scm_syserror_msg (char *subr, char *message, SCM args);
955 @item
956 void scm_sysmissing (char *subr);
957 @item
958 void scm_num_overflow (char *subr);
959 @item
960 void scm_out_of_range (char *subr, SCM bad_value);
961 @item
962 void scm_wrong_num_args (SCM proc);
963 @item
964 void scm_wrong_type_arg (char *subr, int pos, SCM bad_value);
965 @item
966 void scm_memory_error (char *subr);
967 @item
968 static void scm_regex_error (char *subr, int code); (only used in rgx.c).
969 @end itemize
970
971 Exception handlers can also be installed from C, using
972 scm_internal_catch, scm_lazy_catch, or scm_stack_catch from
973 libguile/throw.c. These have not yet been documented, however the
974 source contains some useful comments.
975
976
977 @c Local Variables:
978 @c TeX-master: "guile.texi"
979 @c End: