2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2009, 2010, 2011
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
7 @node Control Mechanisms
8 @section Controlling the Flow of Program Execution
10 See @ref{Control Flow} for a discussion of how the more general control
11 flow of Scheme affects C code.
14 * begin:: Sequencing and splicing.
15 * if cond case:: Simple conditional evaluation.
16 * and or:: Conditional evaluation of a sequence.
17 * while do:: Iteration mechanisms.
18 * Prompts:: Composable, delimited continuations.
19 * Continuations:: Non-composable continuations.
20 * Multiple Values:: Returning and accepting multiple values.
21 * Exceptions:: Throwing and catching exceptions.
22 * Error Reporting:: Procedures for signaling errors.
23 * Dynamic Wind:: Dealing with non-local entrance/exit.
24 * Handling Errors:: How to handle errors in C code.
25 * Continuation Barriers:: Protection from non-local control flow.
29 @subsection Sequencing and Splicing
33 @cindex expression sequencing
35 As an expression, the @code{begin} syntax is used to evaluate a sequence
36 of sub-expressions in order. Consider the conditional expression below:
40 (begin (display "greater") (newline)))
43 If the test is true, we want to display ``greater'' to the current
44 output port, then display a newline. We use @code{begin} to form a
45 compound expression out of this sequence of sub-expressions.
47 @deffn syntax begin expr1 expr2 @dots{}
48 The expression(s) are evaluated in left-to-right order and the value of
49 the last expression is returned as the value of the
50 @code{begin}-expression. This expression type is used when the
51 expressions before the last one are evaluated for their side effects.
55 @cindex definition splicing
57 The @code{begin} syntax has another role in definition context
58 (@pxref{Internal Definitions}). A @code{begin} form in a definition
59 context @dfn{splices} its subforms into its place. For example,
60 consider the following procedure:
64 (define-sealant seal open)
68 Let us assume the existence of a @code{define-sealant} macro that
69 expands out to some definitions wrapped in a @code{begin}, like so:
79 (and (pair? x) (eq? (car x) seal-tag)))
83 (error "Expected a sealed value:" x))))
87 Here, because the @code{begin} is in definition context, its subforms
88 are @dfn{spliced} into the place of the @code{begin}. This allows the
89 definitions created by the macro to be visible to the following
90 expression, the @code{values} form.
92 It is a fine point, but splicing and sequencing are different. It can
93 make sense to splice zero forms, because it can make sense to have zero
94 internal definitions before the expressions in a procedure or lexical
95 binding form. However it does not make sense to have a sequence of zero
96 expressions, because in that case it would not be clear what the value
97 of the sequence would be, because in a sequence of zero expressions,
98 there can be no last value. Sequencing zero expressions is an error.
100 It would be more elegant in some ways to eliminate splicing from the
101 Scheme language, and without macros (@pxref{Macros}), that would be a
102 good idea. But it is useful to be able to write macros that expand out
103 to multiple definitions, as in @code{define-sealant} above, so Scheme
104 abuses the @code{begin} form for these two tasks.
107 @subsection Simple Conditional Evaluation
109 @cindex conditional evaluation
114 Guile provides three syntactic constructs for conditional evaluation.
115 @code{if} is the normal if-then-else expression (with an optional else
116 branch), @code{cond} is a conditional expression with multiple branches
117 and @code{case} branches if an expression has one of a set of constant
120 @deffn syntax if test consequent [alternate]
121 All arguments may be arbitrary expressions. First, @var{test} is
122 evaluated. If it returns a true value, the expression @var{consequent}
123 is evaluated and @var{alternate} is ignored. If @var{test} evaluates to
124 @code{#f}, @var{alternate} is evaluated instead. The value of the
125 evaluated branch (@var{consequent} or @var{alternate}) is returned as
126 the value of the @code{if} expression.
128 When @var{alternate} is omitted and the @var{test} evaluates to
129 @code{#f}, the value of the expression is not specified.
132 @deffn syntax cond clause1 clause2 @dots{}
133 Each @code{cond}-clause must look like this:
136 (@var{test} @var{expression} @dots{})
139 where @var{test} and @var{expression} are arbitrary expression, or like
143 (@var{test} => @var{expression})
146 where @var{expression} must evaluate to a procedure.
148 The @var{test}s of the clauses are evaluated in order and as soon as one
149 of them evaluates to a true values, the corresponding @var{expression}s
150 are evaluated in order and the last value is returned as the value of
151 the @code{cond}-expression. For the @code{=>} clause type,
152 @var{expression} is evaluated and the resulting procedure is applied to
153 the value of @var{test}. The result of this procedure application is
154 then the result of the @code{cond}-expression.
157 @cindex general cond clause
158 @cindex multiple values and cond
159 One additional @code{cond}-clause is available as an extension to
163 (@var{test} @var{guard} => @var{expression})
166 where @var{guard} and @var{expression} must evaluate to procedures.
167 For this clause type, @var{test} may return multiple values, and
168 @code{cond} ignores its boolean state; instead, @code{cond} evaluates
169 @var{guard} and applies the resulting procedure to the value(s) of
170 @var{test}, as if @var{guard} were the @var{consumer} argument of
171 @code{call-with-values}. Iff the result of that procedure call is a
172 true value, it evaluates @var{expression} and applies the resulting
173 procedure to the value(s) of @var{test}, in the same manner as the
174 @var{guard} was called.
176 The @var{test} of the last @var{clause} may be the symbol @code{else}.
177 Then, if none of the preceding @var{test}s is true, the
178 @var{expression}s following the @code{else} are evaluated to produce the
179 result of the @code{cond}-expression.
182 @deffn syntax case key clause1 clause2 @dots{}
183 @var{key} may be any expression, the @var{clause}s must have the form
186 ((@var{datum1} @dots{}) @var{expr1} @var{expr2} @dots{})
189 and the last @var{clause} may have the form
192 (else @var{expr1} @var{expr2} @dots{})
195 All @var{datum}s must be distinct. First, @var{key} is evaluated. The
196 result of this evaluation is compared against all @var{datum} values using
197 @code{eqv?}. When this comparison succeeds, the expression(s) following
198 the @var{datum} are evaluated from left to right, returning the value of
199 the last expression as the result of the @code{case} expression.
201 If the @var{key} matches no @var{datum} and there is an
202 @code{else}-clause, the expressions following the @code{else} are
203 evaluated. If there is no such clause, the result of the expression is
209 @subsection Conditional Evaluation of a Sequence of Expressions
211 @code{and} and @code{or} evaluate all their arguments in order, similar
212 to @code{begin}, but evaluation stops as soon as one of the expressions
213 evaluates to false or true, respectively.
215 @deffn syntax and expr @dots{}
216 Evaluate the @var{expr}s from left to right and stop evaluation as soon
217 as one expression evaluates to @code{#f}; the remaining expressions are
218 not evaluated. The value of the last evaluated expression is returned.
219 If no expression evaluates to @code{#f}, the value of the last
220 expression is returned.
222 If used without expressions, @code{#t} is returned.
225 @deffn syntax or expr @dots{}
226 Evaluate the @var{expr}s from left to right and stop evaluation as soon
227 as one expression evaluates to a true value (that is, a value different
228 from @code{#f}); the remaining expressions are not evaluated. The value
229 of the last evaluated expression is returned. If all expressions
230 evaluate to @code{#f}, @code{#f} is returned.
232 If used without expressions, @code{#f} is returned.
237 @subsection Iteration mechanisms
243 Scheme has only few iteration mechanisms, mainly because iteration in
244 Scheme programs is normally expressed using recursion. Nevertheless,
245 R5RS defines a construct for programming loops, calling @code{do}. In
246 addition, Guile has an explicit looping syntax called @code{while}.
248 @deffn syntax do ((variable init [step]) @dots{}) (test [expr @dots{}]) body @dots{}
249 Bind @var{variable}s and evaluate @var{body} until @var{test} is true.
250 The return value is the last @var{expr} after @var{test}, if given. A
251 simple example will illustrate the basic form,
261 Or with two variables and a final return value,
268 (format #t "3**~s is ~s\n" i p))
278 The @var{variable} bindings are established like a @code{let}, in that
279 the expressions are all evaluated and then all bindings made. When
280 iterating, the optional @var{step} expressions are evaluated with the
281 previous bindings in scope, then new bindings all made.
283 The @var{test} expression is a termination condition. Looping stops
284 when the @var{test} is true. It's evaluated before running the
285 @var{body} each time, so if it's true the first time then @var{body}
288 The optional @var{expr}s after the @var{test} are evaluated at the end
289 of looping, with the final @var{variable} bindings available. The
290 last @var{expr} gives the return value, or if there are no @var{expr}s
291 the return value is unspecified.
293 Each iteration establishes bindings to fresh locations for the
294 @var{variable}s, like a new @code{let} for each iteration. This is
295 done for @var{variable}s without @var{step} expressions too. The
296 following illustrates this, showing how a new @code{i} is captured by
297 the @code{lambda} in each iteration (@pxref{About Closure,, The
298 Concept of Closure}).
304 (set! lst (cons (lambda () i) lst)))
305 (map (lambda (proc) (proc)) lst)
311 @deffn syntax while cond body @dots{}
312 Run a loop executing the @var{body} forms while @var{cond} is true.
313 @var{cond} is tested at the start of each iteration, so if it's
314 @code{#f} the first time then @var{body} is not executed at all.
316 Within @code{while}, two extra bindings are provided, they can be used
317 from both @var{cond} and @var{body}.
319 @deffn {Scheme Procedure} break break-arg...
320 Break out of the @code{while} form.
323 @deffn {Scheme Procedure} continue
324 Abandon the current iteration, go back to the start and test
325 @var{cond} again, etc.
328 If the loop terminates normally, by the @var{cond} evaluating to
329 @code{#f}, then the @code{while} expression as a whole evaluates to
330 @code{#f}. If it terminates by a call to @code{break} with some number
331 of arguments, those arguments are returned from the @code{while}
332 expression, as multiple values. Otherwise if it terminates by a call to
333 @code{break} with no arguments, then return value is @code{#t}.
336 (while #f (error "not reached")) @result{} #f
337 (while #t (break)) @result{} #t
338 (while #t (break 1 2 3)) @result{} 1 2 3
341 Each @code{while} form gets its own @code{break} and @code{continue}
342 procedures, operating on that @code{while}. This means when loops are
343 nested the outer @code{break} can be used to escape all the way out.
348 (let ((outer-break break))
355 Note that each @code{break} and @code{continue} procedure can only be
356 used within the dynamic extent of its @code{while}. Outside the
357 @code{while} their behaviour is unspecified.
361 Another very common way of expressing iteration in Scheme programs is
362 the use of the so-called @dfn{named let}.
364 Named let is a variant of @code{let} which creates a procedure and calls
365 it in one step. Because of the newly created procedure, named let is
366 more powerful than @code{do}--it can be used for iteration, but also
367 for arbitrary recursion.
369 @deffn syntax let variable bindings body
370 For the definition of @var{bindings} see the documentation about
371 @code{let} (@pxref{Local Bindings}).
373 Named @code{let} works as follows:
377 A new procedure which accepts as many arguments as are in @var{bindings}
378 is created and bound locally (using @code{let}) to @var{variable}. The
379 new procedure's formal argument names are the name of the
383 The @var{body} expressions are inserted into the newly created procedure.
386 The procedure is called with the @var{init} expressions as the formal
390 The next example implements a loop which iterates (by recursion) 1000
407 @cindex delimited continuations
408 @cindex composable continuations
409 @cindex non-local exit
411 Prompts are control-flow barriers between different parts of a program. In the
412 same way that a user sees a shell prompt (e.g., the Bash prompt) as a barrier
413 between the operating system and her programs, Scheme prompts allow the Scheme
414 programmer to treat parts of programs as if they were running in different
417 We use this roundabout explanation because, unless you're a functional
418 programming junkie, you probably haven't heard the term, ``delimited, composable
419 continuation''. That's OK; it's a relatively recent topic, but a very useful
423 * Prompt Primitives:: Call-with-prompt and abort-to-prompt.
424 * Shift and Reset:: The zoo of delimited control operators.
427 @node Prompt Primitives
428 @subsubsection Prompt Primitives
430 Guile's primitive delimited control operators are
431 @code{call-with-prompt} and @code{abort-to-prompt}.
433 @deffn {Scheme Procedure} call-with-prompt tag thunk handler
434 Set up a prompt, and call @var{thunk} within that prompt.
436 During the dynamic extent of the call to @var{thunk}, a prompt named @var{tag}
437 will be present in the dynamic context, such that if a user calls
438 @code{abort-to-prompt} (see below) with that tag, control rewinds back to the
439 prompt, and the @var{handler} is run.
441 @var{handler} must be a procedure. The first argument to @var{handler} will be
442 the state of the computation begun when @var{thunk} was called, and ending with
443 the call to @code{abort-to-prompt}. The remaining arguments to @var{handler} are
444 those passed to @code{abort-to-prompt}.
447 @deffn {Scheme Procedure} make-prompt-tag [stem]
448 Make a new prompt tag. Currently prompt tags are generated symbols.
449 This may change in some future Guile version.
452 @deffn {Scheme Procedure} default-prompt-tag
453 Return the default prompt tag. Having a distinguished default prompt
454 tag allows some useful prompt and abort idioms, discussed in the next
458 @deffn {Scheme Procedure} abort-to-prompt tag val ...
459 Unwind the dynamic and control context to the nearest prompt named @var{tag},
460 also passing the given values.
463 C programmers may recognize @code{call-with-prompt} and @code{abort-to-prompt}
464 as a fancy kind of @code{setjmp} and @code{longjmp}, respectively. Prompts are
465 indeed quite useful as non-local escape mechanisms. Guile's @code{catch} and
466 @code{throw} are implemented in terms of prompts. Prompts are more convenient
467 than @code{longjmp}, in that one has the opportunity to pass multiple values to
470 Also unlike @code{longjmp}, the prompt handler is given the full state of the
471 process that was aborted, as the first argument to the prompt's handler. That
472 state is the @dfn{continuation} of the computation wrapped by the prompt. It is
473 a @dfn{delimited continuation}, because it is not the whole continuation of the
474 program; rather, just the computation initiated by the call to
475 @code{call-with-prompt}.
477 The continuation is a procedure, and may be reinstated simply by invoking it,
478 with any number of values. Here's where things get interesting, and complicated
479 as well. Besides being described as delimited, continuations reified by prompts
480 are also @dfn{composable}, because invoking a prompt-saved continuation composes
481 that continuation with the current one.
483 Imagine you have saved a continuation via call-with-prompt:
492 (+ 34 (abort-to-prompt 'foo)))
497 The resulting continuation is the addition of 34. It's as if you had written:
505 So, if we call @code{cont} with one numeric value, we get that number,
515 The last example illustrates what we mean when we say, "composes with the
516 current continuation". We mean that there is a current continuation -- some
517 remaining things to compute, like @code{(lambda (x) (* x 2))} -- and that
518 calling the saved continuation doesn't wipe out the current continuation, it
519 composes the saved continuation with the current one.
521 We're belaboring the point here because traditional Scheme continuations, as
522 discussed in the next section, aren't composable, and are actually less
523 expressive than continuations captured by prompts. But there's a place for them
526 Before moving on, we should mention that if the handler of a prompt is a
527 @code{lambda} expression, and the first argument isn't referenced, an abort to
528 that prompt will not cause a continuation to be reified. This can be an
529 important efficiency consideration to keep in mind.
531 @node Shift and Reset
532 @subsubsection Shift, Reset, and All That
534 There is a whole zoo of delimited control operators, and as it does not
535 seem to be a bounded set, Guile implements support for them in a
539 (use-modules (ice-9 control))
542 Firstly, we have a helpful abbreviation for the @code{call-with-prompt}
545 @deffn {Scheme Syntax} % expr
546 @deffnx {Scheme Syntax} % expr handler
547 @deffnx {Scheme Syntax} % tag expr handler
548 Evaluate @var{expr} in a prompt, optionally specifying a tag and a
549 handler. If no tag is given, the default prompt tag is used.
551 If no handler is given, a default handler is installed. The default
552 handler accepts a procedure of one argument, which will called on the
553 captured continuation, within a prompt.
555 Sometimes it's easier just to show code, as in this case:
558 (define (default-prompt-handler k proc)
559 (% (default-prompt-tag)
561 default-prompt-handler))
564 The @code{%} symbol is chosen because it looks like a prompt.
567 Likewise there is an abbreviation for @code{abort-to-prompt}, which
568 assumes the default prompt tag:
570 @deffn {Scheme Procedure} abort val...
571 Abort to the default prompt tag, passing @var{val...} to the handler.
574 As mentioned before, @code{(ice-9 control)} also provides other
575 delimited control operators. This section is a bit technical, and
576 first-time users of delimited continuations should probably come back to
577 it after some practice with @code{%}.
579 Still here? So, when one implements a delimited control operator like
580 @code{call-with-prompt}, one needs to make two decisions. Firstly, does
581 the handler run within or outside the prompt? Having the handler run
582 within the prompt allows an abort inside the handler to return to the
583 same prompt handler, which is often useful. However it prevents tail
584 calls from the handler, so it is less general.
586 Similarly, does invoking a captured continuation reinstate a prompt?
587 Again we have the tradeoff of convenience versus proper tail calls.
589 These decisions are captured in the Felleisen @dfn{F} operator. If
590 neither the continuations nor the handlers implicitly add a prompt, the
591 operator is known as @dfn{--F--}. This is the case for Guile's
592 @code{call-with-prompt} and @code{abort-to-prompt}.
594 If both continuation and handler implicitly add prompts, then the
595 operator is @dfn{+F+}. @code{shift} and @code{reset} are such
598 @deffn {Scheme Syntax} reset body...
599 Establish a prompt, and evaluate @var{body...} within that prompt.
601 The prompt handler is designed to work with @code{shift}, described
605 @deffn {Scheme Syntax} shift cont body...
606 Abort to the nearest @code{reset}, and evaluate @var{body...} in a
607 context in which the captured continuation is bound to @var{cont}.
609 As mentioned above, both the @var{body...} expression and invocations of
610 @var{cont} implicitly establish a prompt.
613 Interested readers are invited to explore Oleg Kiselyov's wonderful web
614 site at @uref{http://okmij.org/ftp/}, for more information on these
619 @subsection Continuations
620 @cindex continuations
622 A ``continuation'' is the code that will execute when a given function
623 or expression returns. For example, consider
628 (display (bar)) (newline)
632 The continuation from the call to @code{bar} comprises a
633 @code{display} of the value returned, a @code{newline} and an
634 @code{exit}. This can be expressed as a function of one argument.
638 (display r) (newline)
642 In Scheme, continuations are represented as special procedures just
643 like this. The special property is that when a continuation is called
644 it abandons the current program location and jumps directly to that
645 represented by the continuation.
647 A continuation is like a dynamic label, capturing at run-time a point
648 in program execution, including all the nested calls that have lead to
649 it (or rather the code that will execute when those calls return).
651 Continuations are created with the following functions.
653 @deffn {Scheme Procedure} call-with-current-continuation proc
654 @deffnx {Scheme Procedure} call/cc proc
655 @rnindex call-with-current-continuation
656 Capture the current continuation and call @code{(@var{proc}
657 @var{cont})} with it. The return value is the value returned by
658 @var{proc}, or when @code{(@var{cont} @var{value})} is later invoked,
659 the return is the @var{value} passed.
661 Normally @var{cont} should be called with one argument, but when the
662 location resumed is expecting multiple values (@pxref{Multiple
663 Values}) then they should be passed as multiple arguments, for
664 instance @code{(@var{cont} @var{x} @var{y} @var{z})}.
666 @var{cont} may only be used from the same side of a continuation
667 barrier as it was created (@pxref{Continuation Barriers}), and in a
668 multi-threaded program only from the thread in which it was created.
670 The call to @var{proc} is not part of the continuation captured, it runs
671 only when the continuation is created. Often a program will want to
672 store @var{cont} somewhere for later use; this can be done in
675 The @code{call} in the name @code{call-with-current-continuation}
676 refers to the way a call to @var{proc} gives the newly created
677 continuation. It's not related to the way a call is used later to
678 invoke that continuation.
680 @code{call/cc} is an alias for @code{call-with-current-continuation}.
681 This is in common use since the latter is rather long.
686 Here is a simple example,
690 (format #t "the return is ~a\n"
694 @result{} the return is 1
697 @result{} the return is 2
700 @code{call/cc} captures a continuation in which the value returned is
701 going to be displayed by @code{format}. The @code{lambda} stores this
702 in @code{kont} and gives an initial return @code{1} which is
703 displayed. The later invocation of @code{kont} resumes the captured
704 point, but this time returning @code{2}, which is displayed.
706 When Guile is run interactively, a call to @code{format} like this has
707 an implicit return back to the read-eval-print loop. @code{call/cc}
708 captures that like any other return, which is why interactively
709 @code{kont} will come back to read more input.
712 C programmers may note that @code{call/cc} is like @code{setjmp} in
713 the way it records at runtime a point in program execution. A call to
714 a continuation is like a @code{longjmp} in that it abandons the
715 present location and goes to the recorded one. Like @code{longjmp},
716 the value passed to the continuation is the value returned by
717 @code{call/cc} on resuming there. However @code{longjmp} can only go
718 up the program stack, but the continuation mechanism can go anywhere.
720 When a continuation is invoked, @code{call/cc} and subsequent code
721 effectively ``returns'' a second time. It can be confusing to imagine
722 a function returning more times than it was called. It may help
723 instead to think of it being stealthily re-entered and then program
724 flow going on as normal.
726 @code{dynamic-wind} (@pxref{Dynamic Wind}) can be used to ensure setup
727 and cleanup code is run when a program locus is resumed or abandoned
728 through the continuation mechanism.
731 Continuations are a powerful mechanism, and can be used to implement
732 almost any sort of control structure, such as loops, coroutines, or
735 However the implementation of continuations in Guile is not as
736 efficient as one might hope, because Guile is designed to cooperate
737 with programs written in other languages, such as C, which do not know
738 about continuations. Basically continuations are captured by a block
739 copy of the stack, and resumed by copying back.
741 For this reason, continuations captured by @code{call/cc} should be used only
742 when there is no other simple way to achieve the desired result, or when the
743 elegance of the continuation mechanism outweighs the need for performance.
745 Escapes upwards from loops or nested functions are generally best
746 handled with prompts (@pxref{Prompts}). Coroutines can be
747 efficiently implemented with cooperating threads (a thread holds a
748 full program stack but doesn't copy it around the way continuations
752 @node Multiple Values
753 @subsection Returning and Accepting Multiple Values
755 @cindex multiple values
758 Scheme allows a procedure to return more than one value to its caller.
759 This is quite different to other languages which only allow
760 single-value returns. Returning multiple values is different from
761 returning a list (or pair or vector) of values to the caller, because
762 conceptually not @emph{one} compound object is returned, but several
765 The primitive procedures for handling multiple values are @code{values}
766 and @code{call-with-values}. @code{values} is used for returning
767 multiple values from a procedure. This is done by placing a call to
768 @code{values} with zero or more arguments in tail position in a
769 procedure body. @code{call-with-values} combines a procedure returning
770 multiple values with a procedure which accepts these values as
774 @deffn {Scheme Procedure} values arg1 @dots{} argN
775 @deffnx {C Function} scm_values (args)
776 Delivers all of its arguments to its continuation. Except for
777 continuations created by the @code{call-with-values} procedure,
778 all continuations take exactly one value. The effect of
779 passing no value or more than one value to continuations that
780 were not created by @code{call-with-values} is unspecified.
782 For @code{scm_values}, @var{args} is a list of arguments and the
783 return is a multiple-values object which the caller can return. In
784 the current implementation that object shares structure with
785 @var{args}, so @var{args} should not be modified subsequently.
788 @rnindex call-with-values
789 @deffn {Scheme Procedure} call-with-values producer consumer
790 Calls its @var{producer} argument with no values and a
791 continuation that, when passed some values, calls the
792 @var{consumer} procedure with those values as arguments. The
793 continuation for the call to @var{consumer} is the continuation
794 of the call to @code{call-with-values}.
797 (call-with-values (lambda () (values 4 5))
803 (call-with-values * -)
808 In addition to the fundamental procedures described above, Guile has a
809 module which exports a syntax called @code{receive}, which is much
810 more convenient. This is in the @code{(ice-9 receive)} and is the
811 same as specified by SRFI-8 (@pxref{SRFI-8}).
814 (use-modules (ice-9 receive))
817 @deffn {library syntax} receive formals expr body @dots{}
818 Evaluate the expression @var{expr}, and bind the result values (zero
819 or more) to the formal arguments in @var{formals}. @var{formals} is a
820 list of symbols, like the argument list in a @code{lambda}
821 (@pxref{Lambda}). After binding the variables, the expressions in
822 @var{body} @dots{} are evaluated in order, the return value is the
823 result from the last expression.
825 For example getting results from @code{partition} in SRFI-1
829 (receive (odds evens)
830 (partition odd? '(7 4 2 8 3))
834 @print{} (7 3) and (4 2 8)
841 @subsection Exceptions
842 @cindex error handling
843 @cindex exception handling
845 A common requirement in applications is to want to jump
846 @dfn{non-locally} from the depths of a computation back to, say, the
847 application's main processing loop. Usually, the place that is the
848 target of the jump is somewhere in the calling stack of procedures that
849 called the procedure that wants to jump back. For example, typical
850 logic for a key press driven application might look something like this:
854 read the next key press and call dispatch-key
857 lookup the key in a keymap and call an appropriate procedure,
861 interactively read the required file name, then call
865 check whether file exists; if not, jump back to main-loop
869 The jump back to @code{main-loop} could be achieved by returning through
870 the stack one procedure at a time, using the return value of each
871 procedure to indicate the error condition, but Guile (like most modern
872 programming languages) provides an additional mechanism called
873 @dfn{exception handling} that can be used to implement such jumps much
877 * Exception Terminology:: Different ways to say the same thing.
878 * Catch:: Setting up to catch exceptions.
879 * Throw Handlers:: Handling exceptions before unwinding the stack.
880 * Throw:: Throwing an exception.
881 * Exception Implementation:: How Guile implements exceptions.
885 @node Exception Terminology
886 @subsubsection Exception Terminology
888 There are several variations on the terminology for dealing with
889 non-local jumps. It is useful to be aware of them, and to realize
890 that they all refer to the same basic mechanism.
894 Actually making a non-local jump may be called @dfn{raising an
895 exception}, @dfn{raising a signal}, @dfn{throwing an exception} or
896 @dfn{doing a long jump}. When the jump indicates an error condition,
897 people may talk about @dfn{signalling}, @dfn{raising} or @dfn{throwing}
901 Handling the jump at its target may be referred to as @dfn{catching} or
902 @dfn{handling} the @dfn{exception}, @dfn{signal} or, where an error
903 condition is involved, @dfn{error}.
906 Where @dfn{signal} and @dfn{signalling} are used, special care is needed
907 to avoid the risk of confusion with POSIX signals.
909 This manual prefers to speak of throwing and catching exceptions, since
910 this terminology matches the corresponding Guile primitives.
914 @subsubsection Catching Exceptions
916 @code{catch} is used to set up a target for a possible non-local jump.
917 The arguments of a @code{catch} expression are a @dfn{key}, which
918 restricts the set of exceptions to which this @code{catch} applies, a
919 thunk that specifies the code to execute and one or two @dfn{handler}
920 procedures that say what to do if an exception is thrown while executing
921 the code. If the execution thunk executes @dfn{normally}, which means
922 without throwing any exceptions, the handler procedures are not called
925 When an exception is thrown using the @code{throw} function, the first
926 argument of the @code{throw} is a symbol that indicates the type of the
927 exception. For example, Guile throws an exception using the symbol
928 @code{numerical-overflow} to indicate numerical overflow errors such as
934 ABORT: (numerical-overflow)
937 The @var{key} argument in a @code{catch} expression corresponds to this
938 symbol. @var{key} may be a specific symbol, such as
939 @code{numerical-overflow}, in which case the @code{catch} applies
940 specifically to exceptions of that type; or it may be @code{#t}, which
941 means that the @code{catch} applies to all exceptions, irrespective of
944 The second argument of a @code{catch} expression should be a thunk
945 (i.e.@: a procedure that accepts no arguments) that specifies the normal
946 case code. The @code{catch} is active for the execution of this thunk,
947 including any code called directly or indirectly by the thunk's body.
948 Evaluation of the @code{catch} expression activates the catch and then
951 The third argument of a @code{catch} expression is a handler procedure.
952 If an exception is thrown, this procedure is called with exactly the
953 arguments specified by the @code{throw}. Therefore, the handler
954 procedure must be designed to accept a number of arguments that
955 corresponds to the number of arguments in all @code{throw} expressions
956 that can be caught by this @code{catch}.
958 The fourth, optional argument of a @code{catch} expression is another
959 handler procedure, called the @dfn{pre-unwind} handler. It differs from
960 the third argument in that if an exception is thrown, it is called,
961 @emph{before} the third argument handler, in exactly the dynamic context
962 of the @code{throw} expression that threw the exception. This means
963 that it is useful for capturing or displaying the stack at the point of
964 the @code{throw}, or for examining other aspects of the dynamic context,
965 such as fluid values, before the context is unwound back to that of the
966 prevailing @code{catch}.
968 @deffn {Scheme Procedure} catch key thunk handler [pre-unwind-handler]
969 @deffnx {C Function} scm_catch_with_pre_unwind_handler (key, thunk, handler, pre_unwind_handler)
970 @deffnx {C Function} scm_catch (key, thunk, handler)
971 Invoke @var{thunk} in the dynamic context of @var{handler} for
972 exceptions matching @var{key}. If thunk throws to the symbol
973 @var{key}, then @var{handler} is invoked this way:
975 (handler key args ...)
978 @var{key} is a symbol or @code{#t}.
980 @var{thunk} takes no arguments. If @var{thunk} returns
981 normally, that is the return value of @code{catch}.
983 Handler is invoked outside the scope of its own @code{catch}.
984 If @var{handler} again throws to the same key, a new handler
985 from further up the call chain is invoked.
987 If the key is @code{#t}, then a throw to @emph{any} symbol will
988 match this call to @code{catch}.
990 If a @var{pre-unwind-handler} is given and @var{thunk} throws
991 an exception that matches @var{key}, Guile calls the
992 @var{pre-unwind-handler} before unwinding the dynamic state and
993 invoking the main @var{handler}. @var{pre-unwind-handler} should
994 be a procedure with the same signature as @var{handler}, that
995 is @code{(lambda (key . args))}. It is typically used to save
996 the stack at the point where the exception occurred, but can also
997 query other parts of the dynamic state at that point, such as
1000 A @var{pre-unwind-handler} can exit either normally or non-locally.
1001 If it exits normally, Guile unwinds the stack and dynamic context
1002 and then calls the normal (third argument) handler. If it exits
1003 non-locally, that exit determines the continuation.
1006 If a handler procedure needs to match a variety of @code{throw}
1007 expressions with varying numbers of arguments, you should write it like
1011 (lambda (key . args)
1016 The @var{key} argument is guaranteed always to be present, because a
1017 @code{throw} without a @var{key} is not valid. The number and
1018 interpretation of the @var{args} varies from one type of exception to
1019 another, but should be specified by the documentation for each exception
1022 Note that, once the normal (post-unwind) handler procedure is invoked,
1023 the catch that led to the handler procedure being called is no longer
1024 active. Therefore, if the handler procedure itself throws an exception,
1025 that exception can only be caught by another active catch higher up the
1026 call stack, if there is one.
1029 @deftypefn {C Function} SCM scm_c_catch (SCM tag, scm_t_catch_body body, void *body_data, scm_t_catch_handler handler, void *handler_data, scm_t_catch_handler pre_unwind_handler, void *pre_unwind_handler_data)
1030 @deftypefnx {C Function} SCM scm_internal_catch (SCM tag, scm_t_catch_body body, void *body_data, scm_t_catch_handler handler, void *handler_data)
1031 The above @code{scm_catch_with_pre_unwind_handler} and @code{scm_catch}
1032 take Scheme procedures as body and handler arguments.
1033 @code{scm_c_catch} and @code{scm_internal_catch} are equivalents taking
1036 @var{body} is called as @code{@var{body} (@var{body_data})} with a catch
1037 on exceptions of the given @var{tag} type. If an exception is caught,
1038 @var{pre_unwind_handler} and @var{handler} are called as
1039 @code{@var{handler} (@var{handler_data}, @var{key}, @var{args})}.
1040 @var{key} and @var{args} are the @code{SCM} key and argument list from
1043 @tpindex scm_t_catch_body
1044 @tpindex scm_t_catch_handler
1045 @var{body} and @var{handler} should have the following prototypes.
1046 @code{scm_t_catch_body} and @code{scm_t_catch_handler} are pointer
1050 SCM body (void *data);
1051 SCM handler (void *data, SCM key, SCM args);
1054 The @var{body_data} and @var{handler_data} parameters are passed to
1055 the respective calls so an application can communicate extra
1056 information to those functions.
1058 If the data consists of an @code{SCM} object, care should be taken
1059 that it isn't garbage collected while still required. If the
1060 @code{SCM} is a local C variable, one way to protect it is to pass a
1061 pointer to that variable as the data parameter, since the C compiler
1062 will then know the value must be held on the stack. Another way is to
1063 use @code{scm_remember_upto_here_1} (@pxref{Remembering During
1068 @node Throw Handlers
1069 @subsubsection Throw Handlers
1071 It's sometimes useful to be able to intercept an exception that is being
1072 thrown before the stack is unwound. This could be to clean up some
1073 related state, to print a backtrace, or to pass information about the
1074 exception to a debugger, for example. The @code{with-throw-handler}
1075 procedure provides a way to do this.
1077 @deffn {Scheme Procedure} with-throw-handler key thunk handler
1078 @deffnx {C Function} scm_with_throw_handler (key, thunk, handler)
1079 Add @var{handler} to the dynamic context as a throw handler
1080 for key @var{key}, then invoke @var{thunk}.
1082 This behaves exactly like @code{catch}, except that it does not unwind
1083 the stack before invoking @var{handler}. If the @var{handler} procedure
1084 returns normally, Guile rethrows the same exception again to the next
1085 innermost catch or throw handler. @var{handler} may exit nonlocally, of
1086 course, via an explicit throw or via invoking a continuation.
1089 Typically @var{handler} is used to display a backtrace of the stack at
1090 the point where the corresponding @code{throw} occurred, or to save off
1091 this information for possible display later.
1093 Not unwinding the stack means that throwing an exception that is handled
1094 via a throw handler is equivalent to calling the throw handler handler
1095 inline instead of each @code{throw}, and then omitting the surrounding
1096 @code{with-throw-handler}. In other words,
1099 (with-throw-handler 'key
1100 (lambda () @dots{} (throw 'key args @dots{}) @dots{})
1105 is mostly equivalent to
1108 ((lambda () @dots{} (handler 'key args @dots{}) @dots{}))
1111 In particular, the dynamic context when @var{handler} is invoked is that
1112 of the site where @code{throw} is called. The examples are not quite
1113 equivalent, because the body of a @code{with-throw-handler} is not in
1114 tail position with respect to the @code{with-throw-handler}, and if
1115 @var{handler} exits normally, Guile arranges to rethrow the error, but
1116 hopefully the intention is clear. (For an introduction to what is meant
1117 by dynamic context, @xref{Dynamic Wind}.)
1119 @deftypefn {C Function} SCM scm_c_with_throw_handler (SCM tag, scm_t_catch_body body, void *body_data, scm_t_catch_handler handler, void *handler_data, int lazy_catch_p)
1120 The above @code{scm_with_throw_handler} takes Scheme procedures as body
1121 (thunk) and handler arguments. @code{scm_c_with_throw_handler} is an
1122 equivalent taking C functions. See @code{scm_c_catch} (@pxref{Catch})
1123 for a description of the parameters, the behaviour however of course
1124 follows @code{with-throw-handler}.
1127 If @var{thunk} throws an exception, Guile handles that exception by
1128 invoking the innermost @code{catch} or throw handler whose key matches
1129 that of the exception. When the innermost thing is a throw handler,
1130 Guile calls the specified handler procedure using @code{(apply
1131 @var{handler} key args)}. The handler procedure may either return
1132 normally or exit non-locally. If it returns normally, Guile passes the
1133 exception on to the next innermost @code{catch} or throw handler. If it
1134 exits non-locally, that exit determines the continuation.
1136 The behaviour of a throw handler is very similar to that of a
1137 @code{catch} expression's optional pre-unwind handler. In particular, a
1138 throw handler's handler procedure is invoked in the exact dynamic
1139 context of the @code{throw} expression, just as a pre-unwind handler is.
1140 @code{with-throw-handler} may be seen as a half-@code{catch}: it does
1141 everything that a @code{catch} would do until the point where
1142 @code{catch} would start unwinding the stack and dynamic context, but
1143 then it rethrows to the next innermost @code{catch} or throw handler
1146 Note also that since the dynamic context is not unwound, if a
1147 @code{with-throw-handler} handler throws to a key that does not match
1148 the @code{with-throw-handler} expression's @var{key}, the new throw may
1149 be handled by a @code{catch} or throw handler that is @emph{closer} to
1150 the throw than the first @code{with-throw-handler}.
1152 Here is an example to illustrate this behavior:
1157 (with-throw-handler 'b
1163 (lambda (key . args)
1169 This code will call @code{inner-handler} and then continue with the
1170 continuation of the inner @code{catch}.
1174 @subsubsection Throwing Exceptions
1176 The @code{throw} primitive is used to throw an exception. One argument,
1177 the @var{key}, is mandatory, and must be a symbol; it indicates the type
1178 of exception that is being thrown. Following the @var{key},
1179 @code{throw} accepts any number of additional arguments, whose meaning
1180 depends on the exception type. The documentation for each possible type
1181 of exception should specify the additional arguments that are expected
1182 for that kind of exception.
1184 @deffn {Scheme Procedure} throw key . args
1185 @deffnx {C Function} scm_throw (key, args)
1186 Invoke the catch form matching @var{key}, passing @var{args} to the
1189 @var{key} is a symbol. It will match catches of the same symbol or of
1192 If there is no handler at all, Guile prints an error and then exits.
1195 When an exception is thrown, it will be caught by the innermost
1196 @code{catch} or throw handler that applies to the type of the thrown
1197 exception; in other words, whose @var{key} is either @code{#t} or the
1198 same symbol as that used in the @code{throw} expression. Once Guile has
1199 identified the appropriate @code{catch} or throw handler, it handles the
1200 exception by applying the relevant handler procedure(s) to the arguments
1201 of the @code{throw}.
1203 If there is no appropriate @code{catch} or throw handler for a thrown
1204 exception, Guile prints an error to the current error port indicating an
1205 uncaught exception, and then exits. In practice, it is quite difficult
1206 to observe this behaviour, because Guile when used interactively
1207 installs a top level @code{catch} handler that will catch all exceptions
1208 and print an appropriate error message @emph{without} exiting. For
1209 example, this is what happens if you try to throw an unhandled exception
1210 in the standard Guile REPL; note that Guile's command loop continues
1211 after the error message:
1214 guile> (throw 'badex)
1215 <unnamed port>:3:1: In procedure gsubr-apply @dots{}
1216 <unnamed port>:3:1: unhandled-exception: badex
1221 The default uncaught exception behaviour can be observed by evaluating a
1222 @code{throw} expression from the shell command line:
1225 $ guile -c "(begin (throw 'badex) (display \"here\\n\"))"
1226 guile: uncaught throw to badex: ()
1231 That Guile exits immediately following the uncaught exception
1232 is shown by the absence of any output from the @code{display}
1233 expression, because Guile never gets to the point of evaluating that
1237 @node Exception Implementation
1238 @subsubsection How Guile Implements Exceptions
1240 It is traditional in Scheme to implement exception systems using
1241 @code{call-with-current-continuation}. Continuations
1242 (@pxref{Continuations}) are such a powerful concept that any other
1243 control mechanism --- including @code{catch} and @code{throw} --- can be
1244 implemented in terms of them.
1246 Guile does not implement @code{catch} and @code{throw} like this,
1247 though. Why not? Because Guile is specifically designed to be easy to
1248 integrate with applications written in C. In a mixed Scheme/C
1249 environment, the concept of @dfn{continuation} must logically include
1250 ``what happens next'' in the C parts of the application as well as the
1251 Scheme parts, and it turns out that the only reasonable way of
1252 implementing continuations like this is to save and restore the complete
1255 So Guile's implementation of @code{call-with-current-continuation} is a
1256 stack copying one. This allows it to interact well with ordinary C
1257 code, but means that creating and calling a continuation is slowed down
1258 by the time that it takes to copy the C stack.
1260 The more targeted mechanism provided by @code{catch} and @code{throw}
1261 does not need to save and restore the C stack because the @code{throw}
1262 always jumps to a location higher up the stack of the code that executes
1263 the @code{throw}. Therefore Guile implements the @code{catch} and
1264 @code{throw} primitives independently of
1265 @code{call-with-current-continuation}, in a way that takes advantage of
1266 this @emph{upwards only} nature of exceptions.
1269 @node Error Reporting
1270 @subsection Procedures for Signaling Errors
1272 Guile provides a set of convenience procedures for signaling error
1273 conditions that are implemented on top of the exception primitives just
1276 @deffn {Scheme Procedure} error msg args @dots{}
1277 Raise an error with key @code{misc-error} and a message constructed by
1278 displaying @var{msg} and writing @var{args}.
1281 @deffn {Scheme Procedure} scm-error key subr message args data
1282 @deffnx {C Function} scm_error_scm (key, subr, message, args, data)
1283 Raise an error with key @var{key}. @var{subr} can be a string
1284 naming the procedure associated with the error, or @code{#f}.
1285 @var{message} is the error message string, possibly containing
1286 @code{~S} and @code{~A} escapes. When an error is reported,
1287 these are replaced by formatting the corresponding members of
1288 @var{args}: @code{~A} (was @code{%s} in older versions of
1289 Guile) formats using @code{display} and @code{~S} (was
1290 @code{%S}) formats using @code{write}. @var{data} is a list or
1291 @code{#f} depending on @var{key}: if @var{key} is
1292 @code{system-error} then it should be a list containing the
1293 Unix @code{errno} value; If @var{key} is @code{signal} then it
1294 should be a list containing the Unix signal number; If
1295 @var{key} is @code{out-of-range} or @code{wrong-type-arg},
1296 it is a list containing the bad value; otherwise
1297 it will usually be @code{#f}.
1300 @deffn {Scheme Procedure} strerror err
1301 @deffnx {C Function} scm_strerror (err)
1302 Return the Unix error message corresponding to @var{err}, an integer
1305 When @code{setlocale} has been called (@pxref{Locales}), the message
1306 is in the language and charset of @code{LC_MESSAGES}. (This is done
1310 @c begin (scm-doc-string "boot-9.scm" "false-if-exception")
1311 @deffn syntax false-if-exception expr
1312 Returns the result of evaluating its argument; however
1313 if an exception occurs then @code{#f} is returned instead.
1319 @subsection Dynamic Wind
1321 For Scheme code, the fundamental procedure to react to non-local entry
1322 and exits of dynamic contexts is @code{dynamic-wind}. C code could
1323 use @code{scm_internal_dynamic_wind}, but since C does not allow the
1324 convenient construction of anonymous procedures that close over
1325 lexical variables, this will be, well, inconvenient.
1327 Therefore, Guile offers the functions @code{scm_dynwind_begin} and
1328 @code{scm_dynwind_end} to delimit a dynamic extent. Within this
1329 dynamic extent, which is called a @dfn{dynwind context}, you can
1330 perform various @dfn{dynwind actions} that control what happens when
1331 the dynwind context is entered or left. For example, you can register
1332 a cleanup routine with @code{scm_dynwind_unwind_handler} that is
1333 executed when the context is left. There are several other more
1334 specialized dynwind actions as well, for example to temporarily block
1335 the execution of asyncs or to temporarily change the current output
1336 port. They are described elsewhere in this manual.
1338 Here is an example that shows how to prevent memory leaks.
1342 /* Suppose there is a function called FOO in some library that you
1343 would like to make available to Scheme code (or to C code that
1344 follows the Scheme conventions).
1346 FOO takes two C strings and returns a new string. When an error has
1347 occurred in FOO, it returns NULL.
1350 char *foo (char *s1, char *s2);
1352 /* SCM_FOO interfaces the C function FOO to the Scheme way of life.
1353 It takes care to free up all temporary strings in the case of
1358 scm_foo (SCM s1, SCM s2)
1360 char *c_s1, *c_s2, *c_res;
1362 scm_dynwind_begin (0);
1364 c_s1 = scm_to_locale_string (s1);
1366 /* Call 'free (c_s1)' when the dynwind context is left.
1368 scm_dynwind_unwind_handler (free, c_s1, SCM_F_WIND_EXPLICITLY);
1370 c_s2 = scm_to_locale_string (s2);
1372 /* Same as above, but more concisely.
1374 scm_dynwind_free (c_s2);
1376 c_res = foo (c_s1, c_s2);
1378 scm_memory_error ("foo");
1382 return scm_take_locale_string (res);
1386 @rnindex dynamic-wind
1387 @deffn {Scheme Procedure} dynamic-wind in_guard thunk out_guard
1388 @deffnx {C Function} scm_dynamic_wind (in_guard, thunk, out_guard)
1389 All three arguments must be 0-argument procedures.
1390 @var{in_guard} is called, then @var{thunk}, then
1393 If, any time during the execution of @var{thunk}, the
1394 dynamic extent of the @code{dynamic-wind} expression is escaped
1395 non-locally, @var{out_guard} is called. If the dynamic extent of
1396 the dynamic-wind is re-entered, @var{in_guard} is called. Thus
1397 @var{in_guard} and @var{out_guard} may be called any number of
1401 (define x 'normal-binding)
1404 (call-with-current-continuation
1410 (lambda () (set! x 'special-binding))
1414 (lambda () (display x) (newline)
1415 (call-with-current-continuation escape)
1416 (display x) (newline)
1421 (lambda () (set! x old-x)))))))
1427 @result{} normal-binding
1432 @result{} a-cont ;; the value of the (define a-cont...)
1434 @result{} normal-binding
1436 @result{} special-binding
1440 @deftp {C Type} scm_t_dynwind_flags
1441 This is an enumeration of several flags that modify the behavior of
1442 @code{scm_dynwind_begin}. The flags are listed in the following
1446 @item SCM_F_DYNWIND_REWINDABLE
1447 The dynamic context is @dfn{rewindable}. This means that it can be
1448 reentered non-locally (via the invocation of a continuation). The
1449 default is that a dynwind context can not be reentered non-locally.
1454 @deftypefn {C Function} void scm_dynwind_begin (scm_t_dynwind_flags flags)
1455 The function @code{scm_dynwind_begin} starts a new dynamic context and
1456 makes it the `current' one.
1458 The @var{flags} argument determines the default behavior of the
1459 context. Normally, use 0. This will result in a context that can not
1460 be reentered with a captured continuation. When you are prepared to
1461 handle reentries, include @code{SCM_F_DYNWIND_REWINDABLE} in
1464 Being prepared for reentry means that the effects of unwind handlers
1465 can be undone on reentry. In the example above, we want to prevent a
1466 memory leak on non-local exit and thus register an unwind handler that
1467 frees the memory. But once the memory is freed, we can not get it
1468 back on reentry. Thus reentry can not be allowed.
1470 The consequence is that continuations become less useful when
1471 non-reentrant contexts are captured, but you don't need to worry
1472 about that too much.
1474 The context is ended either implicitly when a non-local exit happens,
1475 or explicitly with @code{scm_dynwind_end}. You must make sure that a
1476 dynwind context is indeed ended properly. If you fail to call
1477 @code{scm_dynwind_end} for each @code{scm_dynwind_begin}, the behavior
1481 @deftypefn {C Function} void scm_dynwind_end ()
1482 End the current dynamic context explicitly and make the previous one
1486 @deftp {C Type} scm_t_wind_flags
1487 This is an enumeration of several flags that modify the behavior of
1488 @code{scm_dynwind_unwind_handler} and
1489 @code{scm_dynwind_rewind_handler}. The flags are listed in the
1493 @item SCM_F_WIND_EXPLICITLY
1494 @vindex SCM_F_WIND_EXPLICITLY
1495 The registered action is also carried out when the dynwind context is
1496 entered or left locally.
1500 @deftypefn {C Function} void scm_dynwind_unwind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
1501 @deftypefnx {C Function} void scm_dynwind_unwind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
1502 Arranges for @var{func} to be called with @var{data} as its arguments
1503 when the current context ends implicitly. If @var{flags} contains
1504 @code{SCM_F_WIND_EXPLICITLY}, @var{func} is also called when the
1505 context ends explicitly with @code{scm_dynwind_end}.
1507 The function @code{scm_dynwind_unwind_handler_with_scm} takes care that
1508 @var{data} is protected from garbage collection.
1511 @deftypefn {C Function} void scm_dynwind_rewind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
1512 @deftypefnx {C Function} void scm_dynwind_rewind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
1513 Arrange for @var{func} to be called with @var{data} as its argument when
1514 the current context is restarted by rewinding the stack. When @var{flags}
1515 contains @code{SCM_F_WIND_EXPLICITLY}, @var{func} is called immediately
1518 The function @code{scm_dynwind_rewind_handler_with_scm} takes care that
1519 @var{data} is protected from garbage collection.
1522 @deftypefn {C Function} void scm_dynwind_free (void *mem)
1523 Arrange for @var{mem} to be freed automatically whenever the current
1524 context is exited, whether normally or non-locally.
1525 @code{scm_dynwind_free (mem)} is an equivalent shorthand for
1526 @code{scm_dynwind_unwind_handler (free, mem, SCM_F_WIND_EXPLICITLY)}.
1530 @node Handling Errors
1531 @subsection How to Handle Errors
1533 Error handling is based on @code{catch} and @code{throw}. Errors are
1534 always thrown with a @var{key} and four arguments:
1538 @var{key}: a symbol which indicates the type of error. The symbols used
1539 by libguile are listed below.
1542 @var{subr}: the name of the procedure from which the error is thrown, or
1546 @var{message}: a string (possibly language and system dependent)
1547 describing the error. The tokens @code{~A} and @code{~S} can be
1548 embedded within the message: they will be replaced with members of the
1549 @var{args} list when the message is printed. @code{~A} indicates an
1550 argument printed using @code{display}, while @code{~S} indicates an
1551 argument printed using @code{write}. @var{message} can also be
1552 @code{#f}, to allow it to be derived from the @var{key} by the error
1553 handler (may be useful if the @var{key} is to be thrown from both C and
1557 @var{args}: a list of arguments to be used to expand @code{~A} and
1558 @code{~S} tokens in @var{message}. Can also be @code{#f} if no
1559 arguments are required.
1562 @var{rest}: a list of any additional objects required. e.g., when the
1563 key is @code{'system-error}, this contains the C errno value. Can also
1564 be @code{#f} if no additional objects are required.
1567 In addition to @code{catch} and @code{throw}, the following Scheme
1568 facilities are available:
1570 @deffn {Scheme Procedure} display-error frame port subr message args rest
1571 @deffnx {C Function} scm_display_error (frame, port, subr, message, args, rest)
1572 Display an error message to the output port @var{port}.
1573 @var{frame} is the frame in which the error occurred, @var{subr} is
1574 the name of the procedure in which the error occurred and
1575 @var{message} is the actual error message, which may contain
1576 formatting instructions. These will format the arguments in
1577 the list @var{args} accordingly. @var{rest} is currently
1581 The following are the error keys defined by libguile and the situations
1582 in which they are used:
1586 @cindex @code{error-signal}
1587 @code{error-signal}: thrown after receiving an unhandled fatal signal
1588 such as SIGSEGV, SIGBUS, SIGFPE etc. The @var{rest} argument in the throw
1589 contains the coded signal number (at present this is not the same as the
1590 usual Unix signal number).
1593 @cindex @code{system-error}
1594 @code{system-error}: thrown after the operating system indicates an
1595 error condition. The @var{rest} argument in the throw contains the
1599 @cindex @code{numerical-overflow}
1600 @code{numerical-overflow}: numerical overflow.
1603 @cindex @code{out-of-range}
1604 @code{out-of-range}: the arguments to a procedure do not fall within the
1608 @cindex @code{wrong-type-arg}
1609 @code{wrong-type-arg}: an argument to a procedure has the wrong type.
1612 @cindex @code{wrong-number-of-args}
1613 @code{wrong-number-of-args}: a procedure was called with the wrong number
1617 @cindex @code{memory-allocation-error}
1618 @code{memory-allocation-error}: memory allocation error.
1621 @cindex @code{stack-overflow}
1622 @code{stack-overflow}: stack overflow error.
1625 @cindex @code{regular-expression-syntax}
1626 @code{regular-expression-syntax}: errors generated by the regular
1630 @cindex @code{misc-error}
1631 @code{misc-error}: other errors.
1635 @subsubsection C Support
1637 In the following C functions, @var{SUBR} and @var{MESSAGE} parameters
1638 can be @code{NULL} to give the effect of @code{#f} described above.
1640 @deftypefn {C Function} SCM scm_error (SCM @var{key}, char *@var{subr}, char *@var{message}, SCM @var{args}, SCM @var{rest})
1641 Throw an error, as per @code{scm-error} (@pxref{Error Reporting}).
1644 @deftypefn {C Function} void scm_syserror (char *@var{subr})
1645 @deftypefnx {C Function} void scm_syserror_msg (char *@var{subr}, char *@var{message}, SCM @var{args})
1646 Throw an error with key @code{system-error} and supply @code{errno} in
1647 the @var{rest} argument. For @code{scm_syserror} the message is
1648 generated using @code{strerror}.
1650 Care should be taken that any code in between the failing operation
1651 and the call to these routines doesn't change @code{errno}.
1654 @deftypefn {C Function} void scm_num_overflow (char *@var{subr})
1655 @deftypefnx {C Function} void scm_out_of_range (char *@var{subr}, SCM @var{bad_value})
1656 @deftypefnx {C Function} void scm_wrong_num_args (SCM @var{proc})
1657 @deftypefnx {C Function} void scm_wrong_type_arg (char *@var{subr}, int @var{argnum}, SCM @var{bad_value})
1658 @deftypefnx {C Function} void scm_wrong_type_arg_msg (char *@var{subr}, int @var{argnum}, SCM @var{bad_value}, const char *@var{expected})
1659 @deftypefnx {C Function} void scm_memory_error (char *@var{subr})
1660 Throw an error with the various keys described above.
1661 @deftypefnx {C Function} void scm_misc_error (const char *@var{subr}, const char *@var{message}, SCM @var{args})
1663 In @code{scm_wrong_num_args}, @var{proc} should be a Scheme symbol
1664 which is the name of the procedure incorrectly invoked. The other
1665 routines take the name of the invoked procedure as a C string.
1667 In @code{scm_wrong_type_arg_msg}, @var{expected} is a C string
1668 describing the type of argument that was expected.
1670 In @code{scm_misc_error}, @var{message} is the error message string,
1671 possibly containing @code{simple-format} escapes (@pxref{Writing}), and
1672 the corresponding arguments in the @var{args} list.
1676 @subsubsection Signalling Type Errors
1678 Every function visible at the Scheme level should aggressively check the
1679 types of its arguments, to avoid misinterpreting a value, and perhaps
1680 causing a segmentation fault. Guile provides some macros to make this
1683 @deftypefn Macro void SCM_ASSERT (int @var{test}, SCM @var{obj}, unsigned int @var{position}, const char *@var{subr})
1684 @deftypefnx Macro void SCM_ASSERT_TYPE (int @var{test}, SCM @var{obj}, unsigned int @var{position}, const char *@var{subr}, const char *@var{expected})
1685 If @var{test} is zero, signal a ``wrong type argument'' error,
1686 attributed to the subroutine named @var{subr}, operating on the value
1687 @var{obj}, which is the @var{position}'th argument of @var{subr}.
1689 In @code{SCM_ASSERT_TYPE}, @var{expected} is a C string describing the
1690 type of argument that was expected.
1693 @deftypefn Macro int SCM_ARG1
1694 @deftypefnx Macro int SCM_ARG2
1695 @deftypefnx Macro int SCM_ARG3
1696 @deftypefnx Macro int SCM_ARG4
1697 @deftypefnx Macro int SCM_ARG5
1698 @deftypefnx Macro int SCM_ARG6
1699 @deftypefnx Macro int SCM_ARG7
1700 One of the above values can be used for @var{position} to indicate the
1701 number of the argument of @var{subr} which is being checked.
1702 Alternatively, a positive integer number can be used, which allows to
1703 check arguments after the seventh. However, for parameter numbers up to
1704 seven it is preferable to use @code{SCM_ARGN} instead of the
1705 corresponding raw number, since it will make the code easier to
1709 @deftypefn Macro int SCM_ARGn
1710 Passing a value of zero or @code{SCM_ARGn} for @var{position} allows to
1711 leave it unspecified which argument's type is incorrect. Again,
1712 @code{SCM_ARGn} should be preferred over a raw zero constant.
1715 The @code{SCM_ASRTGO} macro provides another strategy for handling
1718 @deftypefn Macro void SCM_ASRTGO (int @var{test}, label)
1719 If @var{test} is zero, use @code{goto} to jump to the given @var{label}.
1720 @var{label} must appear within the current function.
1723 @node Continuation Barriers
1724 @subsection Continuation Barriers
1726 The non-local flow of control caused by continuations might sometimes
1727 not be wanted. You can use @code{with-continuation-barrier} to erect
1728 fences that continuations can not pass.
1730 @deffn {Scheme Procedure} with-continuation-barrier proc
1731 @deffnx {C Function} scm_with_continuation_barrier (proc)
1732 Call @var{proc} and return its result. Do not allow the invocation of
1733 continuations that would leave or enter the dynamic extent of the call
1734 to @code{with-continuation-barrier}. Such an attempt causes an error
1737 Throws (such as errors) that are not caught from within @var{proc} are
1738 caught by @code{with-continuation-barrier}. In that case, a short
1739 message is printed to the current error port and @code{#f} is returned.
1741 Thus, @code{with-continuation-barrier} returns exactly once.
1744 @deftypefn {C Function} {void *} scm_c_with_continuation_barrier (void *(*func) (void *), void *data)
1745 Like @code{scm_with_continuation_barrier} but call @var{func} on
1746 @var{data}. When an error is caught, @code{NULL} is returned.
1751 @c TeX-master: "guile.texi"