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