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