Replace $letrec with $rec
[bpt/guile.git] / doc / ref / api-control.texi
CommitLineData
07d83abe
MV
1@c -*-texinfo-*-
2@c This is part of the GNU Guile Reference Manual.
183d2ace 3@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2009, 2010,
d9a4a1cd 4@c 2011, 2012, 2013, 2014 Free Software Foundation, Inc.
07d83abe
MV
5@c See the file guile.texi for copying conditions.
6
07d83abe
MV
7@node Control Mechanisms
8@section Controlling the Flow of Program Execution
9
10See @ref{Control Flow} for a discussion of how the more general control
11flow of Scheme affects C code.
12
13@menu
dc65d1cf 14* begin:: Sequencing and splicing.
9accf3d9 15* Conditionals:: If, when, unless, case, and cond.
07d83abe
MV
16* and or:: Conditional evaluation of a sequence.
17* while do:: Iteration mechanisms.
17ed90df
AW
18* Prompts:: Composable, delimited continuations.
19* Continuations:: Non-composable continuations.
07d83abe
MV
20* Multiple Values:: Returning and accepting multiple values.
21* Exceptions:: Throwing and catching exceptions.
22* Error Reporting:: Procedures for signaling errors.
661ae7ab 23* Dynamic Wind:: Dealing with non-local entrance/exit.
07d83abe 24* Handling Errors:: How to handle errors in C code.
ce2612cd 25* Continuation Barriers:: Protection from non-local control flow.
07d83abe
MV
26@end menu
27
28@node begin
dc65d1cf 29@subsection Sequencing and Splicing
07d83abe
MV
30
31@cindex begin
32@cindex sequencing
33@cindex expression sequencing
34
dc65d1cf
AW
35As an expression, the @code{begin} syntax is used to evaluate a sequence
36of sub-expressions in order. Consider the conditional expression below:
07d83abe
MV
37
38@lisp
39(if (> x 0)
40 (begin (display "greater") (newline)))
41@end lisp
42
dc65d1cf
AW
43If the test is true, we want to display ``greater'' to the current
44output port, then display a newline. We use @code{begin} to form a
45compound expression out of this sequence of sub-expressions.
07d83abe 46
df0a1002 47@deffn syntax begin expr @dots{}
dc65d1cf
AW
48The expression(s) are evaluated in left-to-right order and the value of
49the last expression is returned as the value of the
07d83abe
MV
50@code{begin}-expression. This expression type is used when the
51expressions before the last one are evaluated for their side effects.
07d83abe
MV
52@end deffn
53
dc65d1cf
AW
54@cindex splicing
55@cindex definition splicing
56
57The @code{begin} syntax has another role in definition context
58(@pxref{Internal Definitions}). A @code{begin} form in a definition
59context @dfn{splices} its subforms into its place. For example,
60consider the following procedure:
61
62@lisp
63(define (make-seal)
64 (define-sealant seal open)
65 (values seal open))
66@end lisp
67
68Let us assume the existence of a @code{define-sealant} macro that
69expands out to some definitions wrapped in a @code{begin}, like so:
70
71@lisp
72(define (make-seal)
73 (begin
74 (define seal-tag
75 (list 'seal))
76 (define (seal x)
77 (cons seal-tag x))
78 (define (sealed? x)
79 (and (pair? x) (eq? (car x) seal-tag)))
80 (define (open x)
81 (if (sealed? x)
82 (cdr x)
83 (error "Expected a sealed value:" x))))
84 (values seal open))
85@end lisp
86
87Here, because the @code{begin} is in definition context, its subforms
88are @dfn{spliced} into the place of the @code{begin}. This allows the
89definitions created by the macro to be visible to the following
90expression, the @code{values} form.
91
92It is a fine point, but splicing and sequencing are different. It can
93make sense to splice zero forms, because it can make sense to have zero
94internal definitions before the expressions in a procedure or lexical
95binding form. However it does not make sense to have a sequence of zero
96expressions, because in that case it would not be clear what the value
97of the sequence would be, because in a sequence of zero expressions,
98there can be no last value. Sequencing zero expressions is an error.
99
100It would be more elegant in some ways to eliminate splicing from the
101Scheme language, and without macros (@pxref{Macros}), that would be a
102good idea. But it is useful to be able to write macros that expand out
103to multiple definitions, as in @code{define-sealant} above, so Scheme
104abuses the @code{begin} form for these two tasks.
105
9accf3d9 106@node Conditionals
07d83abe
MV
107@subsection Simple Conditional Evaluation
108
109@cindex conditional evaluation
110@cindex if
9accf3d9
AW
111@cindex when
112@cindex unless
07d83abe
MV
113@cindex case
114@cindex cond
115
116Guile provides three syntactic constructs for conditional evaluation.
117@code{if} is the normal if-then-else expression (with an optional else
118branch), @code{cond} is a conditional expression with multiple branches
119and @code{case} branches if an expression has one of a set of constant
120values.
121
122@deffn syntax if test consequent [alternate]
123All arguments may be arbitrary expressions. First, @var{test} is
124evaluated. If it returns a true value, the expression @var{consequent}
125is evaluated and @var{alternate} is ignored. If @var{test} evaluates to
9accf3d9
AW
126@code{#f}, @var{alternate} is evaluated instead. The values of the
127evaluated branch (@var{consequent} or @var{alternate}) are returned as
128the values of the @code{if} expression.
07d83abe
MV
129
130When @var{alternate} is omitted and the @var{test} evaluates to
131@code{#f}, the value of the expression is not specified.
132@end deffn
133
9accf3d9
AW
134When you go to write an @code{if} without an alternate (a @dfn{one-armed
135@code{if}}), part of what you are expressing is that you don't care
136about the return value (or values) of the expression. As such, you are
137more interested in the @emph{effect} of evaluating the consequent
138expression. (By convention, we use the word @dfn{statement} to refer to
139an expression that is evaluated for effect, not for value).
140
141In such a case, it is considered more clear to express these intentions
142with these special forms, @code{when} and @code{unless}. As an added
143bonus, these forms accept multiple statements to evaluate, which are
144implicitly wrapped in a @code{begin}.
145
146@deffn {Scheme Syntax} when test statement1 statement2 ...
147@deffnx {Scheme Syntax} unless test statement1 statement2 ...
148The actual definitions of these forms are in many ways their most clear
149documentation:
150
151@example
152(define-syntax-rule (when test stmt stmt* ...)
153 (if test (begin stmt stmt* ...)))
154
155(define-syntax-rule (unless condition stmt stmt* ...)
156 (if (not test) (begin stmt stmt* ...)))
157@end example
158
159That is to say, @code{when} evaluates its consequent statements in order
160if @var{test} is true. @code{unless} is the opposite: it evaluates the
161statements if @var{test} is false.
162@end deffn
163
07d83abe
MV
164@deffn syntax cond clause1 clause2 @dots{}
165Each @code{cond}-clause must look like this:
166
167@lisp
168(@var{test} @var{expression} @dots{})
169@end lisp
170
171where @var{test} and @var{expression} are arbitrary expression, or like
172this
173
174@lisp
175(@var{test} => @var{expression})
176@end lisp
177
178where @var{expression} must evaluate to a procedure.
179
180The @var{test}s of the clauses are evaluated in order and as soon as one
181of them evaluates to a true values, the corresponding @var{expression}s
182are evaluated in order and the last value is returned as the value of
183the @code{cond}-expression. For the @code{=>} clause type,
184@var{expression} is evaluated and the resulting procedure is applied to
185the value of @var{test}. The result of this procedure application is
186then the result of the @code{cond}-expression.
187
43ed3b69
MV
188@cindex SRFI-61
189@cindex general cond clause
190@cindex multiple values and cond
191One additional @code{cond}-clause is available as an extension to
192standard Scheme:
193
194@lisp
195(@var{test} @var{guard} => @var{expression})
196@end lisp
197
198where @var{guard} and @var{expression} must evaluate to procedures.
199For this clause type, @var{test} may return multiple values, and
200@code{cond} ignores its boolean state; instead, @code{cond} evaluates
201@var{guard} and applies the resulting procedure to the value(s) of
202@var{test}, as if @var{guard} were the @var{consumer} argument of
a4b4fbbd 203@code{call-with-values}. If the result of that procedure call is a
43ed3b69
MV
204true value, it evaluates @var{expression} and applies the resulting
205procedure to the value(s) of @var{test}, in the same manner as the
206@var{guard} was called.
207
07d83abe
MV
208The @var{test} of the last @var{clause} may be the symbol @code{else}.
209Then, if none of the preceding @var{test}s is true, the
210@var{expression}s following the @code{else} are evaluated to produce the
211result of the @code{cond}-expression.
212@end deffn
213
214@deffn syntax case key clause1 clause2 @dots{}
e7cf0457 215@var{key} may be any expression, and the @var{clause}s must have the form
07d83abe
MV
216
217@lisp
218((@var{datum1} @dots{}) @var{expr1} @var{expr2} @dots{})
219@end lisp
220
e7cf0457
MW
221or
222
223@lisp
224((@var{datum1} @dots{}) => @var{expression})
225@end lisp
226
07d83abe
MV
227and the last @var{clause} may have the form
228
229@lisp
230(else @var{expr1} @var{expr2} @dots{})
231@end lisp
232
e7cf0457
MW
233or
234
235@lisp
236(else => @var{expression})
237@end lisp
238
07d83abe 239All @var{datum}s must be distinct. First, @var{key} is evaluated. The
ecb87335 240result of this evaluation is compared against all @var{datum} values using
07d83abe
MV
241@code{eqv?}. When this comparison succeeds, the expression(s) following
242the @var{datum} are evaluated from left to right, returning the value of
243the last expression as the result of the @code{case} expression.
244
245If the @var{key} matches no @var{datum} and there is an
246@code{else}-clause, the expressions following the @code{else} are
247evaluated. If there is no such clause, the result of the expression is
248unspecified.
e7cf0457
MW
249
250For the @code{=>} clause types, @var{expression} is evaluated and the
251resulting procedure is applied to the value of @var{key}. The result of
252this procedure application is then the result of the
253@code{case}-expression.
07d83abe
MV
254@end deffn
255
256
257@node and or
258@subsection Conditional Evaluation of a Sequence of Expressions
259
260@code{and} and @code{or} evaluate all their arguments in order, similar
261to @code{begin}, but evaluation stops as soon as one of the expressions
262evaluates to false or true, respectively.
263
264@deffn syntax and expr @dots{}
265Evaluate the @var{expr}s from left to right and stop evaluation as soon
266as one expression evaluates to @code{#f}; the remaining expressions are
267not evaluated. The value of the last evaluated expression is returned.
268If no expression evaluates to @code{#f}, the value of the last
269expression is returned.
270
271If used without expressions, @code{#t} is returned.
272@end deffn
273
274@deffn syntax or expr @dots{}
275Evaluate the @var{expr}s from left to right and stop evaluation as soon
276as one expression evaluates to a true value (that is, a value different
277from @code{#f}); the remaining expressions are not evaluated. The value
278of the last evaluated expression is returned. If all expressions
279evaluate to @code{#f}, @code{#f} is returned.
280
281If used without expressions, @code{#f} is returned.
282@end deffn
283
284
285@node while do
286@subsection Iteration mechanisms
287
288@cindex iteration
289@cindex looping
290@cindex named let
291
292Scheme has only few iteration mechanisms, mainly because iteration in
293Scheme programs is normally expressed using recursion. Nevertheless,
294R5RS defines a construct for programming loops, calling @code{do}. In
295addition, Guile has an explicit looping syntax called @code{while}.
296
df0a1002 297@deffn syntax do ((variable init [step]) @dots{}) (test expr @dots{}) body @dots{}
07d83abe
MV
298Bind @var{variable}s and evaluate @var{body} until @var{test} is true.
299The return value is the last @var{expr} after @var{test}, if given. A
300simple example will illustrate the basic form,
301
302@example
303(do ((i 1 (1+ i)))
304 ((> i 4))
305 (display i))
306@print{} 1234
307@end example
308
309@noindent
310Or with two variables and a final return value,
311
312@example
313(do ((i 1 (1+ i))
314 (p 3 (* 3 p)))
315 ((> i 4)
316 p)
317 (format #t "3**~s is ~s\n" i p))
318@print{}
3193**1 is 3
3203**2 is 9
3213**3 is 27
3223**4 is 81
323@result{}
324789
325@end example
326
327The @var{variable} bindings are established like a @code{let}, in that
328the expressions are all evaluated and then all bindings made. When
329iterating, the optional @var{step} expressions are evaluated with the
330previous bindings in scope, then new bindings all made.
331
332The @var{test} expression is a termination condition. Looping stops
333when the @var{test} is true. It's evaluated before running the
334@var{body} each time, so if it's true the first time then @var{body}
335is not run at all.
336
337The optional @var{expr}s after the @var{test} are evaluated at the end
338of looping, with the final @var{variable} bindings available. The
339last @var{expr} gives the return value, or if there are no @var{expr}s
340the return value is unspecified.
341
342Each iteration establishes bindings to fresh locations for the
343@var{variable}s, like a new @code{let} for each iteration. This is
344done for @var{variable}s without @var{step} expressions too. The
345following illustrates this, showing how a new @code{i} is captured by
346the @code{lambda} in each iteration (@pxref{About Closure,, The
347Concept of Closure}).
348
349@example
350(define lst '())
351(do ((i 1 (1+ i)))
352 ((> i 4))
353 (set! lst (cons (lambda () i) lst)))
354(map (lambda (proc) (proc)) lst)
355@result{}
356(4 3 2 1)
357@end example
358@end deffn
359
360@deffn syntax while cond body @dots{}
361Run a loop executing the @var{body} forms while @var{cond} is true.
362@var{cond} is tested at the start of each iteration, so if it's
91956a94 363@code{#f} the first time then @var{body} is not executed at all.
07d83abe
MV
364
365Within @code{while}, two extra bindings are provided, they can be used
366from both @var{cond} and @var{body}.
367
df0a1002 368@deffn {Scheme Procedure} break break-arg @dots{}
07d83abe
MV
369Break out of the @code{while} form.
370@end deffn
371
372@deffn {Scheme Procedure} continue
373Abandon the current iteration, go back to the start and test
374@var{cond} again, etc.
375@end deffn
376
91956a94
AW
377If the loop terminates normally, by the @var{cond} evaluating to
378@code{#f}, then the @code{while} expression as a whole evaluates to
379@code{#f}. If it terminates by a call to @code{break} with some number
380of arguments, those arguments are returned from the @code{while}
381expression, as multiple values. Otherwise if it terminates by a call to
382@code{break} with no arguments, then return value is @code{#t}.
383
384@example
385(while #f (error "not reached")) @result{} #f
386(while #t (break)) @result{} #t
80069014 387(while #t (break 1 2 3)) @result{} 1 2 3
91956a94
AW
388@end example
389
07d83abe
MV
390Each @code{while} form gets its own @code{break} and @code{continue}
391procedures, operating on that @code{while}. This means when loops are
392nested the outer @code{break} can be used to escape all the way out.
393For example,
394
395@example
396(while (test1)
397 (let ((outer-break break))
398 (while (test2)
399 (if (something)
400 (outer-break #f))
401 ...)))
402@end example
403
404Note that each @code{break} and @code{continue} procedure can only be
405used within the dynamic extent of its @code{while}. Outside the
406@code{while} their behaviour is unspecified.
407@end deffn
408
409@cindex named let
410Another very common way of expressing iteration in Scheme programs is
411the use of the so-called @dfn{named let}.
412
413Named let is a variant of @code{let} which creates a procedure and calls
414it in one step. Because of the newly created procedure, named let is
415more powerful than @code{do}--it can be used for iteration, but also
416for arbitrary recursion.
417
418@deffn syntax let variable bindings body
419For the definition of @var{bindings} see the documentation about
420@code{let} (@pxref{Local Bindings}).
421
422Named @code{let} works as follows:
423
424@itemize @bullet
425@item
426A new procedure which accepts as many arguments as are in @var{bindings}
427is created and bound locally (using @code{let}) to @var{variable}. The
428new procedure's formal argument names are the name of the
429@var{variables}.
430
431@item
432The @var{body} expressions are inserted into the newly created procedure.
433
434@item
435The procedure is called with the @var{init} expressions as the formal
436arguments.
437@end itemize
438
439The next example implements a loop which iterates (by recursion) 1000
440times.
441
442@lisp
443(let lp ((x 1000))
444 (if (positive? x)
445 (lp (- x 1))
446 x))
447@result{}
4480
449@end lisp
450@end deffn
451
452
17ed90df
AW
453@node Prompts
454@subsection Prompts
455@cindex prompts
456@cindex delimited continuations
457@cindex composable continuations
458@cindex non-local exit
459
460Prompts are control-flow barriers between different parts of a program. In the
461same way that a user sees a shell prompt (e.g., the Bash prompt) as a barrier
462between the operating system and her programs, Scheme prompts allow the Scheme
463programmer to treat parts of programs as if they were running in different
464operating systems.
465
466We use this roundabout explanation because, unless you're a functional
467programming junkie, you probably haven't heard the term, ``delimited, composable
468continuation''. That's OK; it's a relatively recent topic, but a very useful
469one to know about.
470
7b0a2576
AW
471@menu
472* Prompt Primitives:: Call-with-prompt and abort-to-prompt.
473* Shift and Reset:: The zoo of delimited control operators.
474@end menu
475
476@node Prompt Primitives
477@subsubsection Prompt Primitives
478
479Guile's primitive delimited control operators are
480@code{call-with-prompt} and @code{abort-to-prompt}.
481
17ed90df
AW
482@deffn {Scheme Procedure} call-with-prompt tag thunk handler
483Set up a prompt, and call @var{thunk} within that prompt.
484
485During the dynamic extent of the call to @var{thunk}, a prompt named @var{tag}
486will be present in the dynamic context, such that if a user calls
487@code{abort-to-prompt} (see below) with that tag, control rewinds back to the
488prompt, and the @var{handler} is run.
489
490@var{handler} must be a procedure. The first argument to @var{handler} will be
491the state of the computation begun when @var{thunk} was called, and ending with
492the call to @code{abort-to-prompt}. The remaining arguments to @var{handler} are
493those passed to @code{abort-to-prompt}.
494@end deffn
495
7b0a2576 496@deffn {Scheme Procedure} make-prompt-tag [stem]
283ab48d
AW
497Make a new prompt tag. A prompt tag is simply a unique object.
498Currently, a prompt tag is a fresh pair. This may change in some future
499Guile version.
7b0a2576
AW
500@end deffn
501
502@deffn {Scheme Procedure} default-prompt-tag
503Return the default prompt tag. Having a distinguished default prompt
504tag allows some useful prompt and abort idioms, discussed in the next
283ab48d
AW
505section. Note that @code{default-prompt-tag} is actually a parameter,
506and so may be dynamically rebound using @code{parameterize}.
507@xref{Parameters}.
7b0a2576
AW
508@end deffn
509
df0a1002 510@deffn {Scheme Procedure} abort-to-prompt tag val1 val2 @dots{}
17ed90df
AW
511Unwind the dynamic and control context to the nearest prompt named @var{tag},
512also passing the given values.
513@end deffn
514
515C programmers may recognize @code{call-with-prompt} and @code{abort-to-prompt}
516as a fancy kind of @code{setjmp} and @code{longjmp}, respectively. Prompts are
517indeed quite useful as non-local escape mechanisms. Guile's @code{catch} and
518@code{throw} are implemented in terms of prompts. Prompts are more convenient
519than @code{longjmp}, in that one has the opportunity to pass multiple values to
520the jump target.
521
522Also unlike @code{longjmp}, the prompt handler is given the full state of the
523process that was aborted, as the first argument to the prompt's handler. That
524state is the @dfn{continuation} of the computation wrapped by the prompt. It is
525a @dfn{delimited continuation}, because it is not the whole continuation of the
526program; rather, just the computation initiated by the call to
527@code{call-with-prompt}.
528
529The continuation is a procedure, and may be reinstated simply by invoking it,
530with any number of values. Here's where things get interesting, and complicated
531as well. Besides being described as delimited, continuations reified by prompts
532are also @dfn{composable}, because invoking a prompt-saved continuation composes
533that continuation with the current one.
534
535Imagine you have saved a continuation via call-with-prompt:
536
537@example
538(define cont
539 (call-with-prompt
540 ;; tag
541 'foo
542 ;; thunk
543 (lambda ()
544 (+ 34 (abort-to-prompt 'foo)))
545 ;; handler
546 (lambda (k) k)))
547@end example
548
549The resulting continuation is the addition of 34. It's as if you had written:
550
551@example
552(define cont
553 (lambda (x)
554 (+ 34 x)))
555@end example
556
557So, if we call @code{cont} with one numeric value, we get that number,
558incremented by 34:
559
560@example
561(cont 8)
562@result{} 42
563(* 2 (cont 8))
564@result{} 84
565@end example
566
567The last example illustrates what we mean when we say, "composes with the
568current continuation". We mean that there is a current continuation -- some
569remaining things to compute, like @code{(lambda (x) (* x 2))} -- and that
570calling the saved continuation doesn't wipe out the current continuation, it
571composes the saved continuation with the current one.
572
573We're belaboring the point here because traditional Scheme continuations, as
574discussed in the next section, aren't composable, and are actually less
575expressive than continuations captured by prompts. But there's a place for them
576both.
577
578Before moving on, we should mention that if the handler of a prompt is a
579@code{lambda} expression, and the first argument isn't referenced, an abort to
55e26a49 580that prompt will not cause a continuation to be reified. This can be an
17ed90df
AW
581important efficiency consideration to keep in mind.
582
55e26a49
LC
583@cindex continuation, escape
584One example where this optimization matters is @dfn{escape
585continuations}. Escape continuations are delimited continuations whose
586only use is to make a non-local exit---i.e., to escape from the current
587continuation. Such continuations are invoked only once, and for this
bc390109
LC
588reason they are sometimes called @dfn{one-shot continuations}. A common
589use of escape continuations is when throwing an exception
590(@pxref{Exceptions}).
55e26a49
LC
591
592The constructs below are syntactic sugar atop prompts to simplify the
593use of escape continuations.
594
595@deffn {Scheme Procedure} call-with-escape-continuation proc
596@deffnx {Scheme Procedure} call/ec proc
597Call @var{proc} with an escape continuation.
598
599In the example below, the @var{return} continuation is used to escape
600the continuation of the call to @code{fold}.
601
602@lisp
603(use-modules (ice-9 control)
604 (srfi srfi-1))
605
606(define (prefix x lst)
607 ;; Return all the elements before the first occurrence
608 ;; of X in LST.
609 (call/ec
610 (lambda (return)
611 (fold (lambda (element prefix)
612 (if (equal? element x)
613 (return (reverse prefix)) ; escape `fold'
614 (cons element prefix)))
615 '()
616 lst))))
617
618(prefix 'a '(0 1 2 a 3 4 5))
619@result{} (0 1 2)
620@end lisp
621@end deffn
622
623@deffn {Scheme Syntax} let-escape-continuation k body @dots{}
624@deffnx {Scheme Syntax} let/ec k body @dots{}
625Bind @var{k} within @var{body} to an escape continuation.
626
627This is equivalent to
628@code{(call/ec (lambda (@var{k}) @var{body} @dots{}))}.
629@end deffn
630
631
7b0a2576
AW
632@node Shift and Reset
633@subsubsection Shift, Reset, and All That
634
635There is a whole zoo of delimited control operators, and as it does not
636seem to be a bounded set, Guile implements support for them in a
637separate module:
638
639@example
640(use-modules (ice-9 control))
641@end example
642
643Firstly, we have a helpful abbreviation for the @code{call-with-prompt}
644operator.
645
646@deffn {Scheme Syntax} % expr
647@deffnx {Scheme Syntax} % expr handler
648@deffnx {Scheme Syntax} % tag expr handler
649Evaluate @var{expr} in a prompt, optionally specifying a tag and a
650handler. If no tag is given, the default prompt tag is used.
651
652If no handler is given, a default handler is installed. The default
653handler accepts a procedure of one argument, which will called on the
654captured continuation, within a prompt.
655
656Sometimes it's easier just to show code, as in this case:
657
658@example
659(define (default-prompt-handler k proc)
660 (% (default-prompt-tag)
661 (proc k)
662 default-prompt-handler))
663@end example
664
665The @code{%} symbol is chosen because it looks like a prompt.
666@end deffn
667
668Likewise there is an abbreviation for @code{abort-to-prompt}, which
669assumes the default prompt tag:
670
df0a1002
BT
671@deffn {Scheme Procedure} abort val1 val2 @dots{}
672Abort to the default prompt tag, passing @var{val1} @var{val2} @dots{}
673to the handler.
7b0a2576
AW
674@end deffn
675
676As mentioned before, @code{(ice-9 control)} also provides other
677delimited control operators. This section is a bit technical, and
678first-time users of delimited continuations should probably come back to
679it after some practice with @code{%}.
680
681Still here? So, when one implements a delimited control operator like
682@code{call-with-prompt}, one needs to make two decisions. Firstly, does
683the handler run within or outside the prompt? Having the handler run
684within the prompt allows an abort inside the handler to return to the
685same prompt handler, which is often useful. However it prevents tail
686calls from the handler, so it is less general.
687
688Similarly, does invoking a captured continuation reinstate a prompt?
689Again we have the tradeoff of convenience versus proper tail calls.
690
691These decisions are captured in the Felleisen @dfn{F} operator. If
692neither the continuations nor the handlers implicitly add a prompt, the
693operator is known as @dfn{--F--}. This is the case for Guile's
694@code{call-with-prompt} and @code{abort-to-prompt}.
695
696If both continuation and handler implicitly add prompts, then the
697operator is @dfn{+F+}. @code{shift} and @code{reset} are such
698operators.
699
df0a1002
BT
700@deffn {Scheme Syntax} reset body1 body2 @dots{}
701Establish a prompt, and evaluate @var{body1} @var{body2} @dots{} within
702that prompt.
7b0a2576
AW
703
704The prompt handler is designed to work with @code{shift}, described
705below.
706@end deffn
707
df0a1002
BT
708@deffn {Scheme Syntax} shift cont body1 body2 @dots{}
709Abort to the nearest @code{reset}, and evaluate @var{body1} @var{body2}
710@dots{} in a context in which the captured continuation is bound to
711@var{cont}.
7b0a2576 712
df0a1002
BT
713As mentioned above, taken together, the @var{body1} @var{body2} @dots{}
714expressions and the invocations of @var{cont} implicitly establish a
715prompt.
7b0a2576
AW
716@end deffn
717
718Interested readers are invited to explore Oleg Kiselyov's wonderful web
719site at @uref{http://okmij.org/ftp/}, for more information on these
720operators.
721
17ed90df 722
07d83abe
MV
723@node Continuations
724@subsection Continuations
725@cindex continuations
726
727A ``continuation'' is the code that will execute when a given function
728or expression returns. For example, consider
729
730@example
731(define (foo)
732 (display "hello\n")
733 (display (bar)) (newline)
734 (exit))
735@end example
736
737The continuation from the call to @code{bar} comprises a
738@code{display} of the value returned, a @code{newline} and an
739@code{exit}. This can be expressed as a function of one argument.
740
741@example
742(lambda (r)
743 (display r) (newline)
744 (exit))
745@end example
746
747In Scheme, continuations are represented as special procedures just
748like this. The special property is that when a continuation is called
749it abandons the current program location and jumps directly to that
750represented by the continuation.
751
752A continuation is like a dynamic label, capturing at run-time a point
753in program execution, including all the nested calls that have lead to
754it (or rather the code that will execute when those calls return).
755
756Continuations are created with the following functions.
757
758@deffn {Scheme Procedure} call-with-current-continuation proc
759@deffnx {Scheme Procedure} call/cc proc
760@rnindex call-with-current-continuation
761Capture the current continuation and call @code{(@var{proc}
762@var{cont})} with it. The return value is the value returned by
763@var{proc}, or when @code{(@var{cont} @var{value})} is later invoked,
764the return is the @var{value} passed.
765
766Normally @var{cont} should be called with one argument, but when the
767location resumed is expecting multiple values (@pxref{Multiple
768Values}) then they should be passed as multiple arguments, for
769instance @code{(@var{cont} @var{x} @var{y} @var{z})}.
770
b4fddbbe
MV
771@var{cont} may only be used from the same side of a continuation
772barrier as it was created (@pxref{Continuation Barriers}), and in a
773multi-threaded program only from the thread in which it was created.
07d83abe
MV
774
775The call to @var{proc} is not part of the continuation captured, it runs
776only when the continuation is created. Often a program will want to
777store @var{cont} somewhere for later use; this can be done in
778@var{proc}.
779
780The @code{call} in the name @code{call-with-current-continuation}
781refers to the way a call to @var{proc} gives the newly created
782continuation. It's not related to the way a call is used later to
783invoke that continuation.
784
785@code{call/cc} is an alias for @code{call-with-current-continuation}.
786This is in common use since the latter is rather long.
787@end deffn
788
07d83abe
MV
789@sp 1
790@noindent
791Here is a simple example,
792
793@example
794(define kont #f)
795(format #t "the return is ~a\n"
796 (call/cc (lambda (k)
797 (set! kont k)
798 1)))
799@result{} the return is 1
800
801(kont 2)
802@result{} the return is 2
803@end example
804
805@code{call/cc} captures a continuation in which the value returned is
806going to be displayed by @code{format}. The @code{lambda} stores this
807in @code{kont} and gives an initial return @code{1} which is
808displayed. The later invocation of @code{kont} resumes the captured
809point, but this time returning @code{2}, which is displayed.
810
811When Guile is run interactively, a call to @code{format} like this has
812an implicit return back to the read-eval-print loop. @code{call/cc}
813captures that like any other return, which is why interactively
814@code{kont} will come back to read more input.
815
816@sp 1
817C programmers may note that @code{call/cc} is like @code{setjmp} in
818the way it records at runtime a point in program execution. A call to
819a continuation is like a @code{longjmp} in that it abandons the
820present location and goes to the recorded one. Like @code{longjmp},
821the value passed to the continuation is the value returned by
822@code{call/cc} on resuming there. However @code{longjmp} can only go
823up the program stack, but the continuation mechanism can go anywhere.
824
825When a continuation is invoked, @code{call/cc} and subsequent code
826effectively ``returns'' a second time. It can be confusing to imagine
827a function returning more times than it was called. It may help
828instead to think of it being stealthily re-entered and then program
829flow going on as normal.
830
831@code{dynamic-wind} (@pxref{Dynamic Wind}) can be used to ensure setup
832and cleanup code is run when a program locus is resumed or abandoned
661ae7ab 833through the continuation mechanism.
07d83abe
MV
834
835@sp 1
836Continuations are a powerful mechanism, and can be used to implement
837almost any sort of control structure, such as loops, coroutines, or
838exception handlers.
839
840However the implementation of continuations in Guile is not as
841efficient as one might hope, because Guile is designed to cooperate
842with programs written in other languages, such as C, which do not know
843about continuations. Basically continuations are captured by a block
844copy of the stack, and resumed by copying back.
845
17ed90df
AW
846For this reason, continuations captured by @code{call/cc} should be used only
847when there is no other simple way to achieve the desired result, or when the
848elegance of the continuation mechanism outweighs the need for performance.
07d83abe
MV
849
850Escapes upwards from loops or nested functions are generally best
17ed90df 851handled with prompts (@pxref{Prompts}). Coroutines can be
07d83abe
MV
852efficiently implemented with cooperating threads (a thread holds a
853full program stack but doesn't copy it around the way continuations
854do).
855
856
857@node Multiple Values
858@subsection Returning and Accepting Multiple Values
859
860@cindex multiple values
861@cindex receive
862
863Scheme allows a procedure to return more than one value to its caller.
864This is quite different to other languages which only allow
865single-value returns. Returning multiple values is different from
866returning a list (or pair or vector) of values to the caller, because
867conceptually not @emph{one} compound object is returned, but several
868distinct values.
869
870The primitive procedures for handling multiple values are @code{values}
871and @code{call-with-values}. @code{values} is used for returning
872multiple values from a procedure. This is done by placing a call to
873@code{values} with zero or more arguments in tail position in a
874procedure body. @code{call-with-values} combines a procedure returning
875multiple values with a procedure which accepts these values as
876parameters.
877
878@rnindex values
df0a1002 879@deffn {Scheme Procedure} values arg @dots{}
07d83abe
MV
880@deffnx {C Function} scm_values (args)
881Delivers all of its arguments to its continuation. Except for
882continuations created by the @code{call-with-values} procedure,
883all continuations take exactly one value. The effect of
884passing no value or more than one value to continuations that
885were not created by @code{call-with-values} is unspecified.
886
887For @code{scm_values}, @var{args} is a list of arguments and the
888return is a multiple-values object which the caller can return. In
889the current implementation that object shares structure with
890@var{args}, so @var{args} should not be modified subsequently.
891@end deffn
892
e1c80e6b
AW
893@deftypefn {C Function} SCM scm_c_values (SCM *base, size_t n)
894@code{scm_c_values} is an alternative to @code{scm_values}. It creates
895a new values object, and copies into it the @var{n} values starting from
896@var{base}.
897
898Currently this creates a list and passes it to @code{scm_values}, but we
899expect that in the future we will be able to use more a efficient
900representation.
901@end deftypefn
902
903@deftypefn {C Function} size_t scm_c_nvalues (SCM obj)
904If @var{obj} is a multiple-values object, returns the number of values
905it contains. Otherwise returns 1.
906@end deftypefn
907
908@deftypefn {C Function} SCM scm_c_value_ref (SCM obj, size_t idx)
1ceeca0a 909Returns the value at the position specified by @var{idx} in
e1c80e6b 910@var{obj}. Note that @var{obj} will ordinarily be a
1ceeca0a
MW
911multiple-values object, but it need not be. Any other object
912represents a single value (itself), and is handled appropriately.
e1c80e6b 913@end deftypefn
1ceeca0a 914
07d83abe
MV
915@rnindex call-with-values
916@deffn {Scheme Procedure} call-with-values producer consumer
917Calls its @var{producer} argument with no values and a
918continuation that, when passed some values, calls the
919@var{consumer} procedure with those values as arguments. The
920continuation for the call to @var{consumer} is the continuation
921of the call to @code{call-with-values}.
922
923@example
924(call-with-values (lambda () (values 4 5))
925 (lambda (a b) b))
926@result{} 5
927
928@end example
929@example
930(call-with-values * -)
931@result{} -1
932@end example
933@end deffn
934
935In addition to the fundamental procedures described above, Guile has a
23f2b9a3
KR
936module which exports a syntax called @code{receive}, which is much
937more convenient. This is in the @code{(ice-9 receive)} and is the
938same as specified by SRFI-8 (@pxref{SRFI-8}).
07d83abe
MV
939
940@lisp
941(use-modules (ice-9 receive))
942@end lisp
943
944@deffn {library syntax} receive formals expr body @dots{}
23f2b9a3
KR
945Evaluate the expression @var{expr}, and bind the result values (zero
946or more) to the formal arguments in @var{formals}. @var{formals} is a
947list of symbols, like the argument list in a @code{lambda}
948(@pxref{Lambda}). After binding the variables, the expressions in
949@var{body} @dots{} are evaluated in order, the return value is the
950result from the last expression.
951
952For example getting results from @code{partition} in SRFI-1
953(@pxref{SRFI-1}),
954
955@example
956(receive (odds evens)
957 (partition odd? '(7 4 2 8 3))
958 (display odds)
959 (display " and ")
960 (display evens))
961@print{} (7 3) and (4 2 8)
962@end example
963
07d83abe
MV
964@end deffn
965
966
967@node Exceptions
968@subsection Exceptions
969@cindex error handling
970@cindex exception handling
971
972A common requirement in applications is to want to jump
973@dfn{non-locally} from the depths of a computation back to, say, the
974application's main processing loop. Usually, the place that is the
975target of the jump is somewhere in the calling stack of procedures that
976called the procedure that wants to jump back. For example, typical
977logic for a key press driven application might look something like this:
978
979@example
980main-loop:
981 read the next key press and call dispatch-key
982
983dispatch-key:
984 lookup the key in a keymap and call an appropriate procedure,
985 say find-file
986
987find-file:
988 interactively read the required file name, then call
989 find-specified-file
990
991find-specified-file:
992 check whether file exists; if not, jump back to main-loop
993 @dots{}
994@end example
995
996The jump back to @code{main-loop} could be achieved by returning through
997the stack one procedure at a time, using the return value of each
998procedure to indicate the error condition, but Guile (like most modern
999programming languages) provides an additional mechanism called
1000@dfn{exception handling} that can be used to implement such jumps much
1001more conveniently.
1002
1003@menu
1004* Exception Terminology:: Different ways to say the same thing.
1005* Catch:: Setting up to catch exceptions.
e10cf6b9 1006* Throw Handlers:: Handling exceptions before unwinding the stack.
7b4c914e 1007* Throw:: Throwing an exception.
07d83abe
MV
1008* Exception Implementation:: How Guile implements exceptions.
1009@end menu
1010
1011
1012@node Exception Terminology
1013@subsubsection Exception Terminology
1014
1015There are several variations on the terminology for dealing with
1016non-local jumps. It is useful to be aware of them, and to realize
1017that they all refer to the same basic mechanism.
1018
1019@itemize @bullet
1020@item
1021Actually making a non-local jump may be called @dfn{raising an
1022exception}, @dfn{raising a signal}, @dfn{throwing an exception} or
1023@dfn{doing a long jump}. When the jump indicates an error condition,
1024people may talk about @dfn{signalling}, @dfn{raising} or @dfn{throwing}
1025@dfn{an error}.
1026
1027@item
1028Handling the jump at its target may be referred to as @dfn{catching} or
1029@dfn{handling} the @dfn{exception}, @dfn{signal} or, where an error
1030condition is involved, @dfn{error}.
1031@end itemize
1032
1033Where @dfn{signal} and @dfn{signalling} are used, special care is needed
1034to avoid the risk of confusion with POSIX signals.
1035
1036This manual prefers to speak of throwing and catching exceptions, since
1037this terminology matches the corresponding Guile primitives.
1038
bc390109
LC
1039The exception mechanism described in this section has connections with
1040@dfn{delimited continuations} (@pxref{Prompts}). In particular,
1041throwing an exception is akin to invoking an @dfn{escape continuation}
1042(@pxref{Prompt Primitives, @code{call/ec}}).
1043
07d83abe
MV
1044
1045@node Catch
1046@subsubsection Catching Exceptions
1047
1048@code{catch} is used to set up a target for a possible non-local jump.
1049The arguments of a @code{catch} expression are a @dfn{key}, which
1050restricts the set of exceptions to which this @code{catch} applies, a
7b4c914e
NJ
1051thunk that specifies the code to execute and one or two @dfn{handler}
1052procedures that say what to do if an exception is thrown while executing
1053the code. If the execution thunk executes @dfn{normally}, which means
1054without throwing any exceptions, the handler procedures are not called
1055at all.
07d83abe
MV
1056
1057When an exception is thrown using the @code{throw} function, the first
1058argument of the @code{throw} is a symbol that indicates the type of the
1059exception. For example, Guile throws an exception using the symbol
1060@code{numerical-overflow} to indicate numerical overflow errors such as
1061division by zero:
1062
1063@lisp
1064(/ 1 0)
1065@result{}
1066ABORT: (numerical-overflow)
1067@end lisp
1068
1069The @var{key} argument in a @code{catch} expression corresponds to this
1070symbol. @var{key} may be a specific symbol, such as
1071@code{numerical-overflow}, in which case the @code{catch} applies
1072specifically to exceptions of that type; or it may be @code{#t}, which
1073means that the @code{catch} applies to all exceptions, irrespective of
1074their type.
1075
1076The second argument of a @code{catch} expression should be a thunk
679cceed 1077(i.e.@: a procedure that accepts no arguments) that specifies the normal
07d83abe
MV
1078case code. The @code{catch} is active for the execution of this thunk,
1079including any code called directly or indirectly by the thunk's body.
1080Evaluation of the @code{catch} expression activates the catch and then
1081calls this thunk.
1082
1083The third argument of a @code{catch} expression is a handler procedure.
1084If an exception is thrown, this procedure is called with exactly the
1085arguments specified by the @code{throw}. Therefore, the handler
1086procedure must be designed to accept a number of arguments that
1087corresponds to the number of arguments in all @code{throw} expressions
1088that can be caught by this @code{catch}.
1089
7b4c914e
NJ
1090The fourth, optional argument of a @code{catch} expression is another
1091handler procedure, called the @dfn{pre-unwind} handler. It differs from
1092the third argument in that if an exception is thrown, it is called,
1093@emph{before} the third argument handler, in exactly the dynamic context
1094of the @code{throw} expression that threw the exception. This means
1095that it is useful for capturing or displaying the stack at the point of
1096the @code{throw}, or for examining other aspects of the dynamic context,
1097such as fluid values, before the context is unwound back to that of the
1098prevailing @code{catch}.
1099
1100@deffn {Scheme Procedure} catch key thunk handler [pre-unwind-handler]
1101@deffnx {C Function} scm_catch_with_pre_unwind_handler (key, thunk, handler, pre_unwind_handler)
07d83abe
MV
1102@deffnx {C Function} scm_catch (key, thunk, handler)
1103Invoke @var{thunk} in the dynamic context of @var{handler} for
1104exceptions matching @var{key}. If thunk throws to the symbol
1105@var{key}, then @var{handler} is invoked this way:
1106@lisp
1107(handler key args ...)
1108@end lisp
1109
1110@var{key} is a symbol or @code{#t}.
1111
1112@var{thunk} takes no arguments. If @var{thunk} returns
1113normally, that is the return value of @code{catch}.
1114
1115Handler is invoked outside the scope of its own @code{catch}.
1116If @var{handler} again throws to the same key, a new handler
1117from further up the call chain is invoked.
1118
1119If the key is @code{#t}, then a throw to @emph{any} symbol will
1120match this call to @code{catch}.
7b4c914e
NJ
1121
1122If a @var{pre-unwind-handler} is given and @var{thunk} throws
1123an exception that matches @var{key}, Guile calls the
1124@var{pre-unwind-handler} before unwinding the dynamic state and
1125invoking the main @var{handler}. @var{pre-unwind-handler} should
1126be a procedure with the same signature as @var{handler}, that
1127is @code{(lambda (key . args))}. It is typically used to save
1128the stack at the point where the exception occurred, but can also
1129query other parts of the dynamic state at that point, such as
1130fluid values.
1131
1132A @var{pre-unwind-handler} can exit either normally or non-locally.
1133If it exits normally, Guile unwinds the stack and dynamic context
1134and then calls the normal (third argument) handler. If it exits
1135non-locally, that exit determines the continuation.
07d83abe
MV
1136@end deffn
1137
7b4c914e 1138If a handler procedure needs to match a variety of @code{throw}
07d83abe
MV
1139expressions with varying numbers of arguments, you should write it like
1140this:
1141
1142@lisp
1143(lambda (key . args)
1144 @dots{})
1145@end lisp
1146
1147@noindent
1148The @var{key} argument is guaranteed always to be present, because a
1149@code{throw} without a @var{key} is not valid. The number and
1150interpretation of the @var{args} varies from one type of exception to
1151another, but should be specified by the documentation for each exception
1152type.
1153
7b4c914e
NJ
1154Note that, once the normal (post-unwind) handler procedure is invoked,
1155the catch that led to the handler procedure being called is no longer
1156active. Therefore, if the handler procedure itself throws an exception,
1157that exception can only be caught by another active catch higher up the
1158call stack, if there is one.
07d83abe
MV
1159
1160@sp 1
7b4c914e
NJ
1161@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)
1162@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)
1163The above @code{scm_catch_with_pre_unwind_handler} and @code{scm_catch}
1164take Scheme procedures as body and handler arguments.
1165@code{scm_c_catch} and @code{scm_internal_catch} are equivalents taking
1166C functions.
1167
1168@var{body} is called as @code{@var{body} (@var{body_data})} with a catch
1169on exceptions of the given @var{tag} type. If an exception is caught,
1170@var{pre_unwind_handler} and @var{handler} are called as
1171@code{@var{handler} (@var{handler_data}, @var{key}, @var{args})}.
1172@var{key} and @var{args} are the @code{SCM} key and argument list from
1173the @code{throw}.
07d83abe
MV
1174
1175@tpindex scm_t_catch_body
1176@tpindex scm_t_catch_handler
1177@var{body} and @var{handler} should have the following prototypes.
1178@code{scm_t_catch_body} and @code{scm_t_catch_handler} are pointer
1179typedefs for these.
1180
1181@example
1182SCM body (void *data);
1183SCM handler (void *data, SCM key, SCM args);
1184@end example
1185
1186The @var{body_data} and @var{handler_data} parameters are passed to
1187the respective calls so an application can communicate extra
1188information to those functions.
1189
d9a4a1cd
AW
1190If the data consists of an @code{SCM} object, care should be taken that
1191it isn't garbage collected while still required. If the @code{SCM} is a
1192local C variable, one way to protect it is to pass a pointer to that
1193variable as the data parameter, since the C compiler will then know the
1194value must be held on the stack. Another way is to use
1195@code{scm_remember_upto_here_1} (@pxref{Foreign Object Memory
1196Management}).
07d83abe
MV
1197@end deftypefn
1198
1199
7b4c914e
NJ
1200@node Throw Handlers
1201@subsubsection Throw Handlers
07d83abe 1202
7b4c914e 1203It's sometimes useful to be able to intercept an exception that is being
e10cf6b9
AW
1204thrown before the stack is unwound. This could be to clean up some
1205related state, to print a backtrace, or to pass information about the
1206exception to a debugger, for example. The @code{with-throw-handler}
1207procedure provides a way to do this.
07d83abe 1208
7b4c914e
NJ
1209@deffn {Scheme Procedure} with-throw-handler key thunk handler
1210@deffnx {C Function} scm_with_throw_handler (key, thunk, handler)
1211Add @var{handler} to the dynamic context as a throw handler
1212for key @var{key}, then invoke @var{thunk}.
e10cf6b9
AW
1213
1214This behaves exactly like @code{catch}, except that it does not unwind
1215the stack before invoking @var{handler}. If the @var{handler} procedure
1216returns normally, Guile rethrows the same exception again to the next
1217innermost catch or throw handler. @var{handler} may exit nonlocally, of
1218course, via an explicit throw or via invoking a continuation.
07d83abe
MV
1219@end deffn
1220
e10cf6b9
AW
1221Typically @var{handler} is used to display a backtrace of the stack at
1222the point where the corresponding @code{throw} occurred, or to save off
1223this information for possible display later.
1224
1225Not unwinding the stack means that throwing an exception that is handled
1226via a throw handler is equivalent to calling the throw handler handler
1227inline instead of each @code{throw}, and then omitting the surrounding
1228@code{with-throw-handler}. In other words,
1229
1230@lisp
1231(with-throw-handler 'key
1232 (lambda () @dots{} (throw 'key args @dots{}) @dots{})
1233 handler)
1234@end lisp
1235
1236@noindent
1237is mostly equivalent to
1238
1239@lisp
1240((lambda () @dots{} (handler 'key args @dots{}) @dots{}))
1241@end lisp
1242
1243In particular, the dynamic context when @var{handler} is invoked is that
1244of the site where @code{throw} is called. The examples are not quite
1245equivalent, because the body of a @code{with-throw-handler} is not in
1246tail position with respect to the @code{with-throw-handler}, and if
1247@var{handler} exits normally, Guile arranges to rethrow the error, but
1248hopefully the intention is clear. (For an introduction to what is meant
1249by dynamic context, @xref{Dynamic Wind}.)
1250
7b4c914e
NJ
1251@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)
1252The above @code{scm_with_throw_handler} takes Scheme procedures as body
1253(thunk) and handler arguments. @code{scm_c_with_throw_handler} is an
1254equivalent taking C functions. See @code{scm_c_catch} (@pxref{Catch})
1255for a description of the parameters, the behaviour however of course
1256follows @code{with-throw-handler}.
1257@end deftypefn
07d83abe 1258
7b4c914e
NJ
1259If @var{thunk} throws an exception, Guile handles that exception by
1260invoking the innermost @code{catch} or throw handler whose key matches
1261that of the exception. When the innermost thing is a throw handler,
1262Guile calls the specified handler procedure using @code{(apply
1263@var{handler} key args)}. The handler procedure may either return
1264normally or exit non-locally. If it returns normally, Guile passes the
1265exception on to the next innermost @code{catch} or throw handler. If it
1266exits non-locally, that exit determines the continuation.
1267
1268The behaviour of a throw handler is very similar to that of a
1269@code{catch} expression's optional pre-unwind handler. In particular, a
1270throw handler's handler procedure is invoked in the exact dynamic
1271context of the @code{throw} expression, just as a pre-unwind handler is.
1272@code{with-throw-handler} may be seen as a half-@code{catch}: it does
1273everything that a @code{catch} would do until the point where
1274@code{catch} would start unwinding the stack and dynamic context, but
1275then it rethrows to the next innermost @code{catch} or throw handler
1276instead.
07d83abe 1277
e10cf6b9
AW
1278Note also that since the dynamic context is not unwound, if a
1279@code{with-throw-handler} handler throws to a key that does not match
1280the @code{with-throw-handler} expression's @var{key}, the new throw may
1281be handled by a @code{catch} or throw handler that is @emph{closer} to
1282the throw than the first @code{with-throw-handler}.
07d83abe 1283
e10cf6b9 1284Here is an example to illustrate this behavior:
7b4c914e
NJ
1285
1286@lisp
1287(catch 'a
1288 (lambda ()
1289 (with-throw-handler 'b
1290 (lambda ()
1291 (catch 'a
1292 (lambda ()
1293 (throw 'b))
1294 inner-handler))
1295 (lambda (key . args)
1296 (throw 'a))))
1297 outer-handler)
1298@end lisp
1299
1300@noindent
1301This code will call @code{inner-handler} and then continue with the
e10cf6b9 1302continuation of the inner @code{catch}.
7b4c914e
NJ
1303
1304
1305@node Throw
1306@subsubsection Throwing Exceptions
1307
1308The @code{throw} primitive is used to throw an exception. One argument,
1309the @var{key}, is mandatory, and must be a symbol; it indicates the type
1310of exception that is being thrown. Following the @var{key},
1311@code{throw} accepts any number of additional arguments, whose meaning
1312depends on the exception type. The documentation for each possible type
1313of exception should specify the additional arguments that are expected
1314for that kind of exception.
1315
df0a1002 1316@deffn {Scheme Procedure} throw key arg @dots{}
7b4c914e 1317@deffnx {C Function} scm_throw (key, args)
df0a1002
BT
1318Invoke the catch form matching @var{key}, passing @var{arg} @dots{} to
1319the @var{handler}.
7b4c914e
NJ
1320
1321@var{key} is a symbol. It will match catches of the same symbol or of
1322@code{#t}.
1323
1324If there is no handler at all, Guile prints an error and then exits.
1325@end deffn
1326
1327When an exception is thrown, it will be caught by the innermost
1328@code{catch} or throw handler that applies to the type of the thrown
1329exception; in other words, whose @var{key} is either @code{#t} or the
1330same symbol as that used in the @code{throw} expression. Once Guile has
1331identified the appropriate @code{catch} or throw handler, it handles the
1332exception by applying the relevant handler procedure(s) to the arguments
1333of the @code{throw}.
1334
1335If there is no appropriate @code{catch} or throw handler for a thrown
1336exception, Guile prints an error to the current error port indicating an
1337uncaught exception, and then exits. In practice, it is quite difficult
1338to observe this behaviour, because Guile when used interactively
1339installs a top level @code{catch} handler that will catch all exceptions
1340and print an appropriate error message @emph{without} exiting. For
1341example, this is what happens if you try to throw an unhandled exception
1342in the standard Guile REPL; note that Guile's command loop continues
1343after the error message:
1344
1345@lisp
1346guile> (throw 'badex)
1347<unnamed port>:3:1: In procedure gsubr-apply @dots{}
1348<unnamed port>:3:1: unhandled-exception: badex
1349ABORT: (misc-error)
1350guile>
1351@end lisp
1352
1353The default uncaught exception behaviour can be observed by evaluating a
1354@code{throw} expression from the shell command line:
1355
1356@example
1357$ guile -c "(begin (throw 'badex) (display \"here\\n\"))"
1358guile: uncaught throw to badex: ()
1359$
1360@end example
1361
1362@noindent
1363That Guile exits immediately following the uncaught exception
1364is shown by the absence of any output from the @code{display}
1365expression, because Guile never gets to the point of evaluating that
1366expression.
1367
07d83abe
MV
1368
1369@node Exception Implementation
1370@subsubsection How Guile Implements Exceptions
1371
1372It is traditional in Scheme to implement exception systems using
1373@code{call-with-current-continuation}. Continuations
1374(@pxref{Continuations}) are such a powerful concept that any other
1375control mechanism --- including @code{catch} and @code{throw} --- can be
1376implemented in terms of them.
1377
1378Guile does not implement @code{catch} and @code{throw} like this,
1379though. Why not? Because Guile is specifically designed to be easy to
1380integrate with applications written in C. In a mixed Scheme/C
1381environment, the concept of @dfn{continuation} must logically include
1382``what happens next'' in the C parts of the application as well as the
1383Scheme parts, and it turns out that the only reasonable way of
1384implementing continuations like this is to save and restore the complete
1385C stack.
1386
1387So Guile's implementation of @code{call-with-current-continuation} is a
1388stack copying one. This allows it to interact well with ordinary C
1389code, but means that creating and calling a continuation is slowed down
1390by the time that it takes to copy the C stack.
1391
1392The more targeted mechanism provided by @code{catch} and @code{throw}
1393does not need to save and restore the C stack because the @code{throw}
1394always jumps to a location higher up the stack of the code that executes
1395the @code{throw}. Therefore Guile implements the @code{catch} and
1396@code{throw} primitives independently of
1397@code{call-with-current-continuation}, in a way that takes advantage of
1398this @emph{upwards only} nature of exceptions.
1399
1400
1401@node Error Reporting
1402@subsection Procedures for Signaling Errors
1403
1404Guile provides a set of convenience procedures for signaling error
1405conditions that are implemented on top of the exception primitives just
1406described.
1407
df0a1002 1408@deffn {Scheme Procedure} error msg arg @dots{}
07d83abe 1409Raise an error with key @code{misc-error} and a message constructed by
df0a1002 1410displaying @var{msg} and writing @var{arg} @enddots{}.
07d83abe
MV
1411@end deffn
1412
1413@deffn {Scheme Procedure} scm-error key subr message args data
1414@deffnx {C Function} scm_error_scm (key, subr, message, args, data)
1415Raise an error with key @var{key}. @var{subr} can be a string
1416naming the procedure associated with the error, or @code{#f}.
1417@var{message} is the error message string, possibly containing
1418@code{~S} and @code{~A} escapes. When an error is reported,
1419these are replaced by formatting the corresponding members of
1420@var{args}: @code{~A} (was @code{%s} in older versions of
1421Guile) formats using @code{display} and @code{~S} (was
1422@code{%S}) formats using @code{write}. @var{data} is a list or
1423@code{#f} depending on @var{key}: if @var{key} is
1424@code{system-error} then it should be a list containing the
1425Unix @code{errno} value; If @var{key} is @code{signal} then it
7cd44c6d 1426should be a list containing the Unix signal number; If
4af0d97e
LC
1427@var{key} is @code{out-of-range}, @code{wrong-type-arg},
1428or @code{keyword-argument-error},
7cd44c6d 1429it is a list containing the bad value; otherwise
07d83abe
MV
1430it will usually be @code{#f}.
1431@end deffn
1432
1433@deffn {Scheme Procedure} strerror err
1434@deffnx {C Function} scm_strerror (err)
44ba562e
KR
1435Return the Unix error message corresponding to @var{err}, an integer
1436@code{errno} value.
1437
1438When @code{setlocale} has been called (@pxref{Locales}), the message
1439is in the language and charset of @code{LC_MESSAGES}. (This is done
1440by the C library.)
07d83abe
MV
1441@end deffn
1442
1443@c begin (scm-doc-string "boot-9.scm" "false-if-exception")
1444@deffn syntax false-if-exception expr
1445Returns the result of evaluating its argument; however
1446if an exception occurs then @code{#f} is returned instead.
1447@end deffn
1448@c end
1449
1450
1451@node Dynamic Wind
1452@subsection Dynamic Wind
1453
661ae7ab
MV
1454For Scheme code, the fundamental procedure to react to non-local entry
1455and exits of dynamic contexts is @code{dynamic-wind}. C code could
1456use @code{scm_internal_dynamic_wind}, but since C does not allow the
1457convenient construction of anonymous procedures that close over
1458lexical variables, this will be, well, inconvenient.
1459
1460Therefore, Guile offers the functions @code{scm_dynwind_begin} and
1461@code{scm_dynwind_end} to delimit a dynamic extent. Within this
a1ef7406 1462dynamic extent, which is called a @dfn{dynwind context}, you can
661ae7ab
MV
1463perform various @dfn{dynwind actions} that control what happens when
1464the dynwind context is entered or left. For example, you can register
1465a cleanup routine with @code{scm_dynwind_unwind_handler} that is
1466executed when the context is left. There are several other more
1467specialized dynwind actions as well, for example to temporarily block
1468the execution of asyncs or to temporarily change the current output
1469port. They are described elsewhere in this manual.
1470
1471Here is an example that shows how to prevent memory leaks.
1472
1473@example
1474
1475/* Suppose there is a function called FOO in some library that you
1476 would like to make available to Scheme code (or to C code that
1477 follows the Scheme conventions).
1478
1479 FOO takes two C strings and returns a new string. When an error has
1480 occurred in FOO, it returns NULL.
1481*/
1482
1483char *foo (char *s1, char *s2);
1484
1485/* SCM_FOO interfaces the C function FOO to the Scheme way of life.
1486 It takes care to free up all temporary strings in the case of
1487 non-local exits.
1488 */
1489
1490SCM
1491scm_foo (SCM s1, SCM s2)
1492@{
1493 char *c_s1, *c_s2, *c_res;
1494
1495 scm_dynwind_begin (0);
1496
1497 c_s1 = scm_to_locale_string (s1);
1498
1499 /* Call 'free (c_s1)' when the dynwind context is left.
1500 */
1501 scm_dynwind_unwind_handler (free, c_s1, SCM_F_WIND_EXPLICITLY);
1502
1503 c_s2 = scm_to_locale_string (s2);
1504
1505 /* Same as above, but more concisely.
1506 */
1507 scm_dynwind_free (c_s2);
1508
1509 c_res = foo (c_s1, c_s2);
1510 if (c_res == NULL)
1511 scm_memory_error ("foo");
1512
1513 scm_dynwind_end ();
1514
1515 return scm_take_locale_string (res);
1516@}
1517@end example
1518
07d83abe
MV
1519@rnindex dynamic-wind
1520@deffn {Scheme Procedure} dynamic-wind in_guard thunk out_guard
1521@deffnx {C Function} scm_dynamic_wind (in_guard, thunk, out_guard)
1522All three arguments must be 0-argument procedures.
1523@var{in_guard} is called, then @var{thunk}, then
1524@var{out_guard}.
1525
1526If, any time during the execution of @var{thunk}, the
1527dynamic extent of the @code{dynamic-wind} expression is escaped
1528non-locally, @var{out_guard} is called. If the dynamic extent of
1529the dynamic-wind is re-entered, @var{in_guard} is called. Thus
1530@var{in_guard} and @var{out_guard} may be called any number of
1531times.
40296bab 1532
07d83abe
MV
1533@lisp
1534(define x 'normal-binding)
1535@result{} x
40296bab
KR
1536(define a-cont
1537 (call-with-current-continuation
1538 (lambda (escape)
1539 (let ((old-x x))
1540 (dynamic-wind
1541 ;; in-guard:
1542 ;;
1543 (lambda () (set! x 'special-binding))
1544
1545 ;; thunk
1546 ;;
1547 (lambda () (display x) (newline)
1548 (call-with-current-continuation escape)
1549 (display x) (newline)
1550 x)
1551
1552 ;; out-guard:
1553 ;;
1554 (lambda () (set! x old-x)))))))
07d83abe
MV
1555;; Prints:
1556special-binding
1557;; Evaluates to:
1558@result{} a-cont
1559x
1560@result{} normal-binding
1561(a-cont #f)
1562;; Prints:
1563special-binding
1564;; Evaluates to:
1565@result{} a-cont ;; the value of the (define a-cont...)
1566x
1567@result{} normal-binding
1568a-cont
1569@result{} special-binding
1570@end lisp
1571@end deffn
1572
98241dc5
NJ
1573@deftp {C Type} scm_t_dynwind_flags
1574This is an enumeration of several flags that modify the behavior of
1575@code{scm_dynwind_begin}. The flags are listed in the following
1576table.
1577
1578@table @code
1579@item SCM_F_DYNWIND_REWINDABLE
1580The dynamic context is @dfn{rewindable}. This means that it can be
72b3aa56 1581reentered non-locally (via the invocation of a continuation). The
98241dc5
NJ
1582default is that a dynwind context can not be reentered non-locally.
1583@end table
1584
1585@end deftp
1586
1587@deftypefn {C Function} void scm_dynwind_begin (scm_t_dynwind_flags flags)
661ae7ab
MV
1588The function @code{scm_dynwind_begin} starts a new dynamic context and
1589makes it the `current' one.
07d83abe 1590
661ae7ab
MV
1591The @var{flags} argument determines the default behavior of the
1592context. Normally, use 0. This will result in a context that can not
1593be reentered with a captured continuation. When you are prepared to
1594handle reentries, include @code{SCM_F_DYNWIND_REWINDABLE} in
1595@var{flags}.
07d83abe
MV
1596
1597Being prepared for reentry means that the effects of unwind handlers
1598can be undone on reentry. In the example above, we want to prevent a
1599memory leak on non-local exit and thus register an unwind handler that
1600frees the memory. But once the memory is freed, we can not get it
1601back on reentry. Thus reentry can not be allowed.
1602
1603The consequence is that continuations become less useful when
ecb87335 1604non-reentrant contexts are captured, but you don't need to worry
661ae7ab
MV
1605about that too much.
1606
1607The context is ended either implicitly when a non-local exit happens,
1608or explicitly with @code{scm_dynwind_end}. You must make sure that a
1609dynwind context is indeed ended properly. If you fail to call
1610@code{scm_dynwind_end} for each @code{scm_dynwind_begin}, the behavior
1611is undefined.
07d83abe
MV
1612@end deftypefn
1613
661ae7ab
MV
1614@deftypefn {C Function} void scm_dynwind_end ()
1615End the current dynamic context explicitly and make the previous one
1616current.
07d83abe
MV
1617@end deftypefn
1618
98241dc5
NJ
1619@deftp {C Type} scm_t_wind_flags
1620This is an enumeration of several flags that modify the behavior of
1621@code{scm_dynwind_unwind_handler} and
1622@code{scm_dynwind_rewind_handler}. The flags are listed in the
1623following table.
1624
1625@table @code
1626@item SCM_F_WIND_EXPLICITLY
1627@vindex SCM_F_WIND_EXPLICITLY
1628The registered action is also carried out when the dynwind context is
1629entered or left locally.
1630@end table
1631@end deftp
1632
1633@deftypefn {C Function} void scm_dynwind_unwind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
1634@deftypefnx {C Function} void scm_dynwind_unwind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
07d83abe 1635Arranges for @var{func} to be called with @var{data} as its arguments
661ae7ab
MV
1636when the current context ends implicitly. If @var{flags} contains
1637@code{SCM_F_WIND_EXPLICITLY}, @var{func} is also called when the
1638context ends explicitly with @code{scm_dynwind_end}.
07d83abe 1639
661ae7ab 1640The function @code{scm_dynwind_unwind_handler_with_scm} takes care that
07d83abe
MV
1641@var{data} is protected from garbage collection.
1642@end deftypefn
1643
98241dc5
NJ
1644@deftypefn {C Function} void scm_dynwind_rewind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
1645@deftypefnx {C Function} void scm_dynwind_rewind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
07d83abe 1646Arrange for @var{func} to be called with @var{data} as its argument when
661ae7ab 1647the current context is restarted by rewinding the stack. When @var{flags}
07d83abe
MV
1648contains @code{SCM_F_WIND_EXPLICITLY}, @var{func} is called immediately
1649as well.
1650
661ae7ab 1651The function @code{scm_dynwind_rewind_handler_with_scm} takes care that
07d83abe
MV
1652@var{data} is protected from garbage collection.
1653@end deftypefn
1654
9f1ba6a9
NJ
1655@deftypefn {C Function} void scm_dynwind_free (void *mem)
1656Arrange for @var{mem} to be freed automatically whenever the current
1657context is exited, whether normally or non-locally.
1658@code{scm_dynwind_free (mem)} is an equivalent shorthand for
1659@code{scm_dynwind_unwind_handler (free, mem, SCM_F_WIND_EXPLICITLY)}.
1660@end deftypefn
1661
07d83abe
MV
1662
1663@node Handling Errors
1664@subsection How to Handle Errors
1665
1666Error handling is based on @code{catch} and @code{throw}. Errors are
1667always thrown with a @var{key} and four arguments:
1668
1669@itemize @bullet
1670@item
1671@var{key}: a symbol which indicates the type of error. The symbols used
1672by libguile are listed below.
1673
1674@item
1675@var{subr}: the name of the procedure from which the error is thrown, or
1676@code{#f}.
1677
1678@item
1679@var{message}: a string (possibly language and system dependent)
1680describing the error. The tokens @code{~A} and @code{~S} can be
1681embedded within the message: they will be replaced with members of the
1682@var{args} list when the message is printed. @code{~A} indicates an
1683argument printed using @code{display}, while @code{~S} indicates an
1684argument printed using @code{write}. @var{message} can also be
1685@code{#f}, to allow it to be derived from the @var{key} by the error
1686handler (may be useful if the @var{key} is to be thrown from both C and
1687Scheme).
1688
1689@item
1690@var{args}: a list of arguments to be used to expand @code{~A} and
1691@code{~S} tokens in @var{message}. Can also be @code{#f} if no
1692arguments are required.
1693
1694@item
1695@var{rest}: a list of any additional objects required. e.g., when the
1696key is @code{'system-error}, this contains the C errno value. Can also
1697be @code{#f} if no additional objects are required.
1698@end itemize
1699
1700In addition to @code{catch} and @code{throw}, the following Scheme
1701facilities are available:
1702
7545ddd4
AW
1703@deffn {Scheme Procedure} display-error frame port subr message args rest
1704@deffnx {C Function} scm_display_error (frame, port, subr, message, args, rest)
07d83abe 1705Display an error message to the output port @var{port}.
7545ddd4 1706@var{frame} is the frame in which the error occurred, @var{subr} is
07d83abe
MV
1707the name of the procedure in which the error occurred and
1708@var{message} is the actual error message, which may contain
1709formatting instructions. These will format the arguments in
1710the list @var{args} accordingly. @var{rest} is currently
1711ignored.
1712@end deffn
1713
1714The following are the error keys defined by libguile and the situations
1715in which they are used:
1716
1717@itemize @bullet
1718@item
1719@cindex @code{error-signal}
1720@code{error-signal}: thrown after receiving an unhandled fatal signal
1721such as SIGSEGV, SIGBUS, SIGFPE etc. The @var{rest} argument in the throw
1722contains the coded signal number (at present this is not the same as the
1723usual Unix signal number).
1724
1725@item
1726@cindex @code{system-error}
1727@code{system-error}: thrown after the operating system indicates an
1728error condition. The @var{rest} argument in the throw contains the
1729errno value.
1730
1731@item
1732@cindex @code{numerical-overflow}
1733@code{numerical-overflow}: numerical overflow.
1734
1735@item
1736@cindex @code{out-of-range}
1737@code{out-of-range}: the arguments to a procedure do not fall within the
1738accepted domain.
1739
1740@item
1741@cindex @code{wrong-type-arg}
1742@code{wrong-type-arg}: an argument to a procedure has the wrong type.
1743
1744@item
1745@cindex @code{wrong-number-of-args}
1746@code{wrong-number-of-args}: a procedure was called with the wrong number
1747of arguments.
1748
1749@item
1750@cindex @code{memory-allocation-error}
1751@code{memory-allocation-error}: memory allocation error.
1752
1753@item
1754@cindex @code{stack-overflow}
1755@code{stack-overflow}: stack overflow error.
1756
1757@item
1758@cindex @code{regular-expression-syntax}
1759@code{regular-expression-syntax}: errors generated by the regular
1760expression library.
1761
1762@item
1763@cindex @code{misc-error}
1764@code{misc-error}: other errors.
1765@end itemize
1766
1767
1768@subsubsection C Support
1769
1770In the following C functions, @var{SUBR} and @var{MESSAGE} parameters
1771can be @code{NULL} to give the effect of @code{#f} described above.
1772
1773@deftypefn {C Function} SCM scm_error (SCM @var{key}, char *@var{subr}, char *@var{message}, SCM @var{args}, SCM @var{rest})
9a18d8d4 1774Throw an error, as per @code{scm-error} (@pxref{Error Reporting}).
07d83abe
MV
1775@end deftypefn
1776
1777@deftypefn {C Function} void scm_syserror (char *@var{subr})
1778@deftypefnx {C Function} void scm_syserror_msg (char *@var{subr}, char *@var{message}, SCM @var{args})
1779Throw an error with key @code{system-error} and supply @code{errno} in
1780the @var{rest} argument. For @code{scm_syserror} the message is
1781generated using @code{strerror}.
1782
1783Care should be taken that any code in between the failing operation
1784and the call to these routines doesn't change @code{errno}.
1785@end deftypefn
1786
1787@deftypefn {C Function} void scm_num_overflow (char *@var{subr})
1788@deftypefnx {C Function} void scm_out_of_range (char *@var{subr}, SCM @var{bad_value})
1789@deftypefnx {C Function} void scm_wrong_num_args (SCM @var{proc})
1790@deftypefnx {C Function} void scm_wrong_type_arg (char *@var{subr}, int @var{argnum}, SCM @var{bad_value})
58228cc6 1791@deftypefnx {C Function} void scm_wrong_type_arg_msg (char *@var{subr}, int @var{argnum}, SCM @var{bad_value}, const char *@var{expected})
07d83abe 1792@deftypefnx {C Function} void scm_memory_error (char *@var{subr})
9dfcd9e2 1793@deftypefnx {C Function} void scm_misc_error (const char *@var{subr}, const char *@var{message}, SCM @var{args})
183d2ace 1794Throw an error with the various keys described above.
07d83abe 1795
9dfcd9e2 1796In @code{scm_wrong_num_args}, @var{proc} should be a Scheme symbol
58228cc6
NJ
1797which is the name of the procedure incorrectly invoked. The other
1798routines take the name of the invoked procedure as a C string.
1799
1800In @code{scm_wrong_type_arg_msg}, @var{expected} is a C string
1801describing the type of argument that was expected.
9dfcd9e2
LC
1802
1803In @code{scm_misc_error}, @var{message} is the error message string,
1804possibly containing @code{simple-format} escapes (@pxref{Writing}), and
1805the corresponding arguments in the @var{args} list.
07d83abe
MV
1806@end deftypefn
1807
1808
0f7e6c56
AW
1809@subsubsection Signalling Type Errors
1810
1811Every function visible at the Scheme level should aggressively check the
1812types of its arguments, to avoid misinterpreting a value, and perhaps
1813causing a segmentation fault. Guile provides some macros to make this
1814easier.
1815
1816@deftypefn Macro void SCM_ASSERT (int @var{test}, SCM @var{obj}, unsigned int @var{position}, const char *@var{subr})
b2c4c3e5 1817@deftypefnx Macro void SCM_ASSERT_TYPE (int @var{test}, SCM @var{obj}, unsigned int @var{position}, const char *@var{subr}, const char *@var{expected})
0f7e6c56
AW
1818If @var{test} is zero, signal a ``wrong type argument'' error,
1819attributed to the subroutine named @var{subr}, operating on the value
1820@var{obj}, which is the @var{position}'th argument of @var{subr}.
b2c4c3e5
MG
1821
1822In @code{SCM_ASSERT_TYPE}, @var{expected} is a C string describing the
1823type of argument that was expected.
0f7e6c56
AW
1824@end deftypefn
1825
1826@deftypefn Macro int SCM_ARG1
1827@deftypefnx Macro int SCM_ARG2
1828@deftypefnx Macro int SCM_ARG3
1829@deftypefnx Macro int SCM_ARG4
1830@deftypefnx Macro int SCM_ARG5
1831@deftypefnx Macro int SCM_ARG6
1832@deftypefnx Macro int SCM_ARG7
1833One of the above values can be used for @var{position} to indicate the
1834number of the argument of @var{subr} which is being checked.
1835Alternatively, a positive integer number can be used, which allows to
1836check arguments after the seventh. However, for parameter numbers up to
1837seven it is preferable to use @code{SCM_ARGN} instead of the
1838corresponding raw number, since it will make the code easier to
1839understand.
1840@end deftypefn
1841
1842@deftypefn Macro int SCM_ARGn
1843Passing a value of zero or @code{SCM_ARGn} for @var{position} allows to
1844leave it unspecified which argument's type is incorrect. Again,
1845@code{SCM_ARGn} should be preferred over a raw zero constant.
1846@end deftypefn
1847
ce2612cd
NJ
1848@node Continuation Barriers
1849@subsection Continuation Barriers
1850
1851The non-local flow of control caused by continuations might sometimes
56664c08
AW
1852not be wanted. You can use @code{with-continuation-barrier} to erect
1853fences that continuations can not pass.
ce2612cd
NJ
1854
1855@deffn {Scheme Procedure} with-continuation-barrier proc
1856@deffnx {C Function} scm_with_continuation_barrier (proc)
1857Call @var{proc} and return its result. Do not allow the invocation of
1858continuations that would leave or enter the dynamic extent of the call
1859to @code{with-continuation-barrier}. Such an attempt causes an error
1860to be signaled.
1861
1862Throws (such as errors) that are not caught from within @var{proc} are
1863caught by @code{with-continuation-barrier}. In that case, a short
1864message is printed to the current error port and @code{#f} is returned.
1865
1866Thus, @code{with-continuation-barrier} returns exactly once.
1867@end deffn
1868
1869@deftypefn {C Function} {void *} scm_c_with_continuation_barrier (void *(*func) (void *), void *data)
1870Like @code{scm_with_continuation_barrier} but call @var{func} on
1871@var{data}. When an error is caught, @code{NULL} is returned.
1872@end deftypefn
1873
1874
07d83abe
MV
1875@c Local Variables:
1876@c TeX-master: "guile.texi"
1877@c End: