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