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