avoid gensym when making labels in psyntax
[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, 2012
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 @deffn {C Function} scm_c_value_ref (values, idx)
789 Returns the value at the position specified by @var{idx} in
790 @var{values}. Note that @var{values} will ordinarily be a
791 multiple-values object, but it need not be. Any other object
792 represents a single value (itself), and is handled appropriately.
793 @end deffn
794
795 @rnindex call-with-values
796 @deffn {Scheme Procedure} call-with-values producer consumer
797 Calls its @var{producer} argument with no values and a
798 continuation that, when passed some values, calls the
799 @var{consumer} procedure with those values as arguments. The
800 continuation for the call to @var{consumer} is the continuation
801 of 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
815 In addition to the fundamental procedures described above, Guile has a
816 module which exports a syntax called @code{receive}, which is much
817 more convenient. This is in the @code{(ice-9 receive)} and is the
818 same as specified by SRFI-8 (@pxref{SRFI-8}).
819
820 @lisp
821 (use-modules (ice-9 receive))
822 @end lisp
823
824 @deffn {library syntax} receive formals expr body @dots{}
825 Evaluate the expression @var{expr}, and bind the result values (zero
826 or more) to the formal arguments in @var{formals}. @var{formals} is a
827 list 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
830 result from the last expression.
831
832 For 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
844 @end deffn
845
846
847 @node Exceptions
848 @subsection Exceptions
849 @cindex error handling
850 @cindex exception handling
851
852 A common requirement in applications is to want to jump
853 @dfn{non-locally} from the depths of a computation back to, say, the
854 application's main processing loop. Usually, the place that is the
855 target of the jump is somewhere in the calling stack of procedures that
856 called the procedure that wants to jump back. For example, typical
857 logic for a key press driven application might look something like this:
858
859 @example
860 main-loop:
861 read the next key press and call dispatch-key
862
863 dispatch-key:
864 lookup the key in a keymap and call an appropriate procedure,
865 say find-file
866
867 find-file:
868 interactively read the required file name, then call
869 find-specified-file
870
871 find-specified-file:
872 check whether file exists; if not, jump back to main-loop
873 @dots{}
874 @end example
875
876 The jump back to @code{main-loop} could be achieved by returning through
877 the stack one procedure at a time, using the return value of each
878 procedure to indicate the error condition, but Guile (like most modern
879 programming languages) provides an additional mechanism called
880 @dfn{exception handling} that can be used to implement such jumps much
881 more conveniently.
882
883 @menu
884 * Exception Terminology:: Different ways to say the same thing.
885 * Catch:: Setting up to catch exceptions.
886 * Throw Handlers:: Handling exceptions before unwinding the stack.
887 * Throw:: Throwing an exception.
888 * Exception Implementation:: How Guile implements exceptions.
889 @end menu
890
891
892 @node Exception Terminology
893 @subsubsection Exception Terminology
894
895 There are several variations on the terminology for dealing with
896 non-local jumps. It is useful to be aware of them, and to realize
897 that they all refer to the same basic mechanism.
898
899 @itemize @bullet
900 @item
901 Actually making a non-local jump may be called @dfn{raising an
902 exception}, @dfn{raising a signal}, @dfn{throwing an exception} or
903 @dfn{doing a long jump}. When the jump indicates an error condition,
904 people may talk about @dfn{signalling}, @dfn{raising} or @dfn{throwing}
905 @dfn{an error}.
906
907 @item
908 Handling 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
910 condition is involved, @dfn{error}.
911 @end itemize
912
913 Where @dfn{signal} and @dfn{signalling} are used, special care is needed
914 to avoid the risk of confusion with POSIX signals.
915
916 This manual prefers to speak of throwing and catching exceptions, since
917 this 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.
924 The arguments of a @code{catch} expression are a @dfn{key}, which
925 restricts the set of exceptions to which this @code{catch} applies, a
926 thunk that specifies the code to execute and one or two @dfn{handler}
927 procedures that say what to do if an exception is thrown while executing
928 the code. If the execution thunk executes @dfn{normally}, which means
929 without throwing any exceptions, the handler procedures are not called
930 at all.
931
932 When an exception is thrown using the @code{throw} function, the first
933 argument of the @code{throw} is a symbol that indicates the type of the
934 exception. For example, Guile throws an exception using the symbol
935 @code{numerical-overflow} to indicate numerical overflow errors such as
936 division by zero:
937
938 @lisp
939 (/ 1 0)
940 @result{}
941 ABORT: (numerical-overflow)
942 @end lisp
943
944 The @var{key} argument in a @code{catch} expression corresponds to this
945 symbol. @var{key} may be a specific symbol, such as
946 @code{numerical-overflow}, in which case the @code{catch} applies
947 specifically to exceptions of that type; or it may be @code{#t}, which
948 means that the @code{catch} applies to all exceptions, irrespective of
949 their type.
950
951 The second argument of a @code{catch} expression should be a thunk
952 (i.e.@: a procedure that accepts no arguments) that specifies the normal
953 case code. The @code{catch} is active for the execution of this thunk,
954 including any code called directly or indirectly by the thunk's body.
955 Evaluation of the @code{catch} expression activates the catch and then
956 calls this thunk.
957
958 The third argument of a @code{catch} expression is a handler procedure.
959 If an exception is thrown, this procedure is called with exactly the
960 arguments specified by the @code{throw}. Therefore, the handler
961 procedure must be designed to accept a number of arguments that
962 corresponds to the number of arguments in all @code{throw} expressions
963 that can be caught by this @code{catch}.
964
965 The fourth, optional argument of a @code{catch} expression is another
966 handler procedure, called the @dfn{pre-unwind} handler. It differs from
967 the third argument in that if an exception is thrown, it is called,
968 @emph{before} the third argument handler, in exactly the dynamic context
969 of the @code{throw} expression that threw the exception. This means
970 that it is useful for capturing or displaying the stack at the point of
971 the @code{throw}, or for examining other aspects of the dynamic context,
972 such as fluid values, before the context is unwound back to that of the
973 prevailing @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)
977 @deffnx {C Function} scm_catch (key, thunk, handler)
978 Invoke @var{thunk} in the dynamic context of @var{handler} for
979 exceptions 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
988 normally, that is the return value of @code{catch}.
989
990 Handler is invoked outside the scope of its own @code{catch}.
991 If @var{handler} again throws to the same key, a new handler
992 from further up the call chain is invoked.
993
994 If the key is @code{#t}, then a throw to @emph{any} symbol will
995 match this call to @code{catch}.
996
997 If a @var{pre-unwind-handler} is given and @var{thunk} throws
998 an exception that matches @var{key}, Guile calls the
999 @var{pre-unwind-handler} before unwinding the dynamic state and
1000 invoking the main @var{handler}. @var{pre-unwind-handler} should
1001 be a procedure with the same signature as @var{handler}, that
1002 is @code{(lambda (key . args))}. It is typically used to save
1003 the stack at the point where the exception occurred, but can also
1004 query other parts of the dynamic state at that point, such as
1005 fluid values.
1006
1007 A @var{pre-unwind-handler} can exit either normally or non-locally.
1008 If it exits normally, Guile unwinds the stack and dynamic context
1009 and then calls the normal (third argument) handler. If it exits
1010 non-locally, that exit determines the continuation.
1011 @end deffn
1012
1013 If a handler procedure needs to match a variety of @code{throw}
1014 expressions with varying numbers of arguments, you should write it like
1015 this:
1016
1017 @lisp
1018 (lambda (key . args)
1019 @dots{})
1020 @end lisp
1021
1022 @noindent
1023 The @var{key} argument is guaranteed always to be present, because a
1024 @code{throw} without a @var{key} is not valid. The number and
1025 interpretation of the @var{args} varies from one type of exception to
1026 another, but should be specified by the documentation for each exception
1027 type.
1028
1029 Note that, once the normal (post-unwind) handler procedure is invoked,
1030 the catch that led to the handler procedure being called is no longer
1031 active. Therefore, if the handler procedure itself throws an exception,
1032 that exception can only be caught by another active catch higher up the
1033 call stack, if there is one.
1034
1035 @sp 1
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)
1038 The above @code{scm_catch_with_pre_unwind_handler} and @code{scm_catch}
1039 take Scheme procedures as body and handler arguments.
1040 @code{scm_c_catch} and @code{scm_internal_catch} are equivalents taking
1041 C functions.
1042
1043 @var{body} is called as @code{@var{body} (@var{body_data})} with a catch
1044 on 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
1048 the @code{throw}.
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
1054 typedefs for these.
1055
1056 @example
1057 SCM body (void *data);
1058 SCM handler (void *data, SCM key, SCM args);
1059 @end example
1060
1061 The @var{body_data} and @var{handler_data} parameters are passed to
1062 the respective calls so an application can communicate extra
1063 information to those functions.
1064
1065 If the data consists of an @code{SCM} object, care should be taken
1066 that 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
1068 pointer to that variable as the data parameter, since the C compiler
1069 will then know the value must be held on the stack. Another way is to
1070 use @code{scm_remember_upto_here_1} (@pxref{Remembering During
1071 Operations}).
1072 @end deftypefn
1073
1074
1075 @node Throw Handlers
1076 @subsubsection Throw Handlers
1077
1078 It's sometimes useful to be able to intercept an exception that is being
1079 thrown before the stack is unwound. This could be to clean up some
1080 related state, to print a backtrace, or to pass information about the
1081 exception to a debugger, for example. The @code{with-throw-handler}
1082 procedure provides a way to do this.
1083
1084 @deffn {Scheme Procedure} with-throw-handler key thunk handler
1085 @deffnx {C Function} scm_with_throw_handler (key, thunk, handler)
1086 Add @var{handler} to the dynamic context as a throw handler
1087 for key @var{key}, then invoke @var{thunk}.
1088
1089 This behaves exactly like @code{catch}, except that it does not unwind
1090 the stack before invoking @var{handler}. If the @var{handler} procedure
1091 returns normally, Guile rethrows the same exception again to the next
1092 innermost catch or throw handler. @var{handler} may exit nonlocally, of
1093 course, via an explicit throw or via invoking a continuation.
1094 @end deffn
1095
1096 Typically @var{handler} is used to display a backtrace of the stack at
1097 the point where the corresponding @code{throw} occurred, or to save off
1098 this information for possible display later.
1099
1100 Not unwinding the stack means that throwing an exception that is handled
1101 via a throw handler is equivalent to calling the throw handler handler
1102 inline 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
1112 is mostly equivalent to
1113
1114 @lisp
1115 ((lambda () @dots{} (handler 'key args @dots{}) @dots{}))
1116 @end lisp
1117
1118 In particular, the dynamic context when @var{handler} is invoked is that
1119 of the site where @code{throw} is called. The examples are not quite
1120 equivalent, because the body of a @code{with-throw-handler} is not in
1121 tail position with respect to the @code{with-throw-handler}, and if
1122 @var{handler} exits normally, Guile arranges to rethrow the error, but
1123 hopefully the intention is clear. (For an introduction to what is meant
1124 by dynamic context, @xref{Dynamic Wind}.)
1125
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)
1127 The above @code{scm_with_throw_handler} takes Scheme procedures as body
1128 (thunk) and handler arguments. @code{scm_c_with_throw_handler} is an
1129 equivalent taking C functions. See @code{scm_c_catch} (@pxref{Catch})
1130 for a description of the parameters, the behaviour however of course
1131 follows @code{with-throw-handler}.
1132 @end deftypefn
1133
1134 If @var{thunk} throws an exception, Guile handles that exception by
1135 invoking the innermost @code{catch} or throw handler whose key matches
1136 that of the exception. When the innermost thing is a throw handler,
1137 Guile calls the specified handler procedure using @code{(apply
1138 @var{handler} key args)}. The handler procedure may either return
1139 normally or exit non-locally. If it returns normally, Guile passes the
1140 exception on to the next innermost @code{catch} or throw handler. If it
1141 exits non-locally, that exit determines the continuation.
1142
1143 The behaviour of a throw handler is very similar to that of a
1144 @code{catch} expression's optional pre-unwind handler. In particular, a
1145 throw handler's handler procedure is invoked in the exact dynamic
1146 context 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
1148 everything that a @code{catch} would do until the point where
1149 @code{catch} would start unwinding the stack and dynamic context, but
1150 then it rethrows to the next innermost @code{catch} or throw handler
1151 instead.
1152
1153 Note 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
1155 the @code{with-throw-handler} expression's @var{key}, the new throw may
1156 be handled by a @code{catch} or throw handler that is @emph{closer} to
1157 the throw than the first @code{with-throw-handler}.
1158
1159 Here is an example to illustrate this behavior:
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
1176 This code will call @code{inner-handler} and then continue with the
1177 continuation of the inner @code{catch}.
1178
1179
1180 @node Throw
1181 @subsubsection Throwing Exceptions
1182
1183 The @code{throw} primitive is used to throw an exception. One argument,
1184 the @var{key}, is mandatory, and must be a symbol; it indicates the type
1185 of exception that is being thrown. Following the @var{key},
1186 @code{throw} accepts any number of additional arguments, whose meaning
1187 depends on the exception type. The documentation for each possible type
1188 of exception should specify the additional arguments that are expected
1189 for that kind of exception.
1190
1191 @deffn {Scheme Procedure} throw key . args
1192 @deffnx {C Function} scm_throw (key, args)
1193 Invoke 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
1199 If there is no handler at all, Guile prints an error and then exits.
1200 @end deffn
1201
1202 When 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
1204 exception; in other words, whose @var{key} is either @code{#t} or the
1205 same symbol as that used in the @code{throw} expression. Once Guile has
1206 identified the appropriate @code{catch} or throw handler, it handles the
1207 exception by applying the relevant handler procedure(s) to the arguments
1208 of the @code{throw}.
1209
1210 If there is no appropriate @code{catch} or throw handler for a thrown
1211 exception, Guile prints an error to the current error port indicating an
1212 uncaught exception, and then exits. In practice, it is quite difficult
1213 to observe this behaviour, because Guile when used interactively
1214 installs a top level @code{catch} handler that will catch all exceptions
1215 and print an appropriate error message @emph{without} exiting. For
1216 example, this is what happens if you try to throw an unhandled exception
1217 in the standard Guile REPL; note that Guile's command loop continues
1218 after the error message:
1219
1220 @lisp
1221 guile> (throw 'badex)
1222 <unnamed port>:3:1: In procedure gsubr-apply @dots{}
1223 <unnamed port>:3:1: unhandled-exception: badex
1224 ABORT: (misc-error)
1225 guile>
1226 @end lisp
1227
1228 The 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\"))"
1233 guile: uncaught throw to badex: ()
1234 $
1235 @end example
1236
1237 @noindent
1238 That Guile exits immediately following the uncaught exception
1239 is shown by the absence of any output from the @code{display}
1240 expression, because Guile never gets to the point of evaluating that
1241 expression.
1242
1243
1244 @node Exception Implementation
1245 @subsubsection How Guile Implements Exceptions
1246
1247 It 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
1250 control mechanism --- including @code{catch} and @code{throw} --- can be
1251 implemented in terms of them.
1252
1253 Guile does not implement @code{catch} and @code{throw} like this,
1254 though. Why not? Because Guile is specifically designed to be easy to
1255 integrate with applications written in C. In a mixed Scheme/C
1256 environment, the concept of @dfn{continuation} must logically include
1257 ``what happens next'' in the C parts of the application as well as the
1258 Scheme parts, and it turns out that the only reasonable way of
1259 implementing continuations like this is to save and restore the complete
1260 C stack.
1261
1262 So Guile's implementation of @code{call-with-current-continuation} is a
1263 stack copying one. This allows it to interact well with ordinary C
1264 code, but means that creating and calling a continuation is slowed down
1265 by the time that it takes to copy the C stack.
1266
1267 The more targeted mechanism provided by @code{catch} and @code{throw}
1268 does not need to save and restore the C stack because the @code{throw}
1269 always jumps to a location higher up the stack of the code that executes
1270 the @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
1273 this @emph{upwards only} nature of exceptions.
1274
1275
1276 @node Error Reporting
1277 @subsection Procedures for Signaling Errors
1278
1279 Guile provides a set of convenience procedures for signaling error
1280 conditions that are implemented on top of the exception primitives just
1281 described.
1282
1283 @deffn {Scheme Procedure} error msg args @dots{}
1284 Raise an error with key @code{misc-error} and a message constructed by
1285 displaying @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)
1290 Raise an error with key @var{key}. @var{subr} can be a string
1291 naming 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,
1294 these are replaced by formatting the corresponding members of
1295 @var{args}: @code{~A} (was @code{%s} in older versions of
1296 Guile) 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
1300 Unix @code{errno} value; If @var{key} is @code{signal} then it
1301 should be a list containing the Unix signal number; If
1302 @var{key} is @code{out-of-range} or @code{wrong-type-arg},
1303 it is a list containing the bad value; otherwise
1304 it will usually be @code{#f}.
1305 @end deffn
1306
1307 @deffn {Scheme Procedure} strerror err
1308 @deffnx {C Function} scm_strerror (err)
1309 Return the Unix error message corresponding to @var{err}, an integer
1310 @code{errno} value.
1311
1312 When @code{setlocale} has been called (@pxref{Locales}), the message
1313 is in the language and charset of @code{LC_MESSAGES}. (This is done
1314 by the C library.)
1315 @end deffn
1316
1317 @c begin (scm-doc-string "boot-9.scm" "false-if-exception")
1318 @deffn syntax false-if-exception expr
1319 Returns the result of evaluating its argument; however
1320 if 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
1328 For Scheme code, the fundamental procedure to react to non-local entry
1329 and exits of dynamic contexts is @code{dynamic-wind}. C code could
1330 use @code{scm_internal_dynamic_wind}, but since C does not allow the
1331 convenient construction of anonymous procedures that close over
1332 lexical variables, this will be, well, inconvenient.
1333
1334 Therefore, Guile offers the functions @code{scm_dynwind_begin} and
1335 @code{scm_dynwind_end} to delimit a dynamic extent. Within this
1336 dynamic extent, which is called a @dfn{dynwind context}, you can
1337 perform various @dfn{dynwind actions} that control what happens when
1338 the dynwind context is entered or left. For example, you can register
1339 a cleanup routine with @code{scm_dynwind_unwind_handler} that is
1340 executed when the context is left. There are several other more
1341 specialized dynwind actions as well, for example to temporarily block
1342 the execution of asyncs or to temporarily change the current output
1343 port. They are described elsewhere in this manual.
1344
1345 Here 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
1357 char *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
1364 SCM
1365 scm_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
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)
1396 All three arguments must be 0-argument procedures.
1397 @var{in_guard} is called, then @var{thunk}, then
1398 @var{out_guard}.
1399
1400 If, any time during the execution of @var{thunk}, the
1401 dynamic extent of the @code{dynamic-wind} expression is escaped
1402 non-locally, @var{out_guard} is called. If the dynamic extent of
1403 the 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
1405 times.
1406
1407 @lisp
1408 (define x 'normal-binding)
1409 @result{} x
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)))))))
1429 ;; Prints:
1430 special-binding
1431 ;; Evaluates to:
1432 @result{} a-cont
1433 x
1434 @result{} normal-binding
1435 (a-cont #f)
1436 ;; Prints:
1437 special-binding
1438 ;; Evaluates to:
1439 @result{} a-cont ;; the value of the (define a-cont...)
1440 x
1441 @result{} normal-binding
1442 a-cont
1443 @result{} special-binding
1444 @end lisp
1445 @end deffn
1446
1447 @deftp {C Type} scm_t_dynwind_flags
1448 This is an enumeration of several flags that modify the behavior of
1449 @code{scm_dynwind_begin}. The flags are listed in the following
1450 table.
1451
1452 @table @code
1453 @item SCM_F_DYNWIND_REWINDABLE
1454 The dynamic context is @dfn{rewindable}. This means that it can be
1455 reentered non-locally (via the invocation of a continuation). The
1456 default 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)
1462 The function @code{scm_dynwind_begin} starts a new dynamic context and
1463 makes it the `current' one.
1464
1465 The @var{flags} argument determines the default behavior of the
1466 context. Normally, use 0. This will result in a context that can not
1467 be reentered with a captured continuation. When you are prepared to
1468 handle reentries, include @code{SCM_F_DYNWIND_REWINDABLE} in
1469 @var{flags}.
1470
1471 Being prepared for reentry means that the effects of unwind handlers
1472 can be undone on reentry. In the example above, we want to prevent a
1473 memory leak on non-local exit and thus register an unwind handler that
1474 frees the memory. But once the memory is freed, we can not get it
1475 back on reentry. Thus reentry can not be allowed.
1476
1477 The consequence is that continuations become less useful when
1478 non-reentrant contexts are captured, but you don't need to worry
1479 about that too much.
1480
1481 The context is ended either implicitly when a non-local exit happens,
1482 or explicitly with @code{scm_dynwind_end}. You must make sure that a
1483 dynwind context is indeed ended properly. If you fail to call
1484 @code{scm_dynwind_end} for each @code{scm_dynwind_begin}, the behavior
1485 is undefined.
1486 @end deftypefn
1487
1488 @deftypefn {C Function} void scm_dynwind_end ()
1489 End the current dynamic context explicitly and make the previous one
1490 current.
1491 @end deftypefn
1492
1493 @deftp {C Type} scm_t_wind_flags
1494 This 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
1497 following table.
1498
1499 @table @code
1500 @item SCM_F_WIND_EXPLICITLY
1501 @vindex SCM_F_WIND_EXPLICITLY
1502 The registered action is also carried out when the dynwind context is
1503 entered 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)
1509 Arranges for @var{func} to be called with @var{data} as its arguments
1510 when the current context ends implicitly. If @var{flags} contains
1511 @code{SCM_F_WIND_EXPLICITLY}, @var{func} is also called when the
1512 context ends explicitly with @code{scm_dynwind_end}.
1513
1514 The function @code{scm_dynwind_unwind_handler_with_scm} takes care that
1515 @var{data} is protected from garbage collection.
1516 @end deftypefn
1517
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)
1520 Arrange for @var{func} to be called with @var{data} as its argument when
1521 the current context is restarted by rewinding the stack. When @var{flags}
1522 contains @code{SCM_F_WIND_EXPLICITLY}, @var{func} is called immediately
1523 as well.
1524
1525 The function @code{scm_dynwind_rewind_handler_with_scm} takes care that
1526 @var{data} is protected from garbage collection.
1527 @end deftypefn
1528
1529 @deftypefn {C Function} void scm_dynwind_free (void *mem)
1530 Arrange for @var{mem} to be freed automatically whenever the current
1531 context 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
1536
1537 @node Handling Errors
1538 @subsection How to Handle Errors
1539
1540 Error handling is based on @code{catch} and @code{throw}. Errors are
1541 always 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
1546 by 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)
1554 describing the error. The tokens @code{~A} and @code{~S} can be
1555 embedded within the message: they will be replaced with members of the
1556 @var{args} list when the message is printed. @code{~A} indicates an
1557 argument printed using @code{display}, while @code{~S} indicates an
1558 argument 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
1560 handler (may be useful if the @var{key} is to be thrown from both C and
1561 Scheme).
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
1566 arguments are required.
1567
1568 @item
1569 @var{rest}: a list of any additional objects required. e.g., when the
1570 key is @code{'system-error}, this contains the C errno value. Can also
1571 be @code{#f} if no additional objects are required.
1572 @end itemize
1573
1574 In addition to @code{catch} and @code{throw}, the following Scheme
1575 facilities are available:
1576
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)
1579 Display an error message to the output port @var{port}.
1580 @var{frame} is the frame in which the error occurred, @var{subr} is
1581 the name of the procedure in which the error occurred and
1582 @var{message} is the actual error message, which may contain
1583 formatting instructions. These will format the arguments in
1584 the list @var{args} accordingly. @var{rest} is currently
1585 ignored.
1586 @end deffn
1587
1588 The following are the error keys defined by libguile and the situations
1589 in 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
1595 such as SIGSEGV, SIGBUS, SIGFPE etc. The @var{rest} argument in the throw
1596 contains the coded signal number (at present this is not the same as the
1597 usual Unix signal number).
1598
1599 @item
1600 @cindex @code{system-error}
1601 @code{system-error}: thrown after the operating system indicates an
1602 error condition. The @var{rest} argument in the throw contains the
1603 errno 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
1612 accepted 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
1621 of 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
1634 expression 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
1644 In the following C functions, @var{SUBR} and @var{MESSAGE} parameters
1645 can 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})
1648 Throw an error, as per @code{scm-error} (@pxref{Error Reporting}).
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})
1653 Throw an error with key @code{system-error} and supply @code{errno} in
1654 the @var{rest} argument. For @code{scm_syserror} the message is
1655 generated using @code{strerror}.
1656
1657 Care should be taken that any code in between the failing operation
1658 and 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})
1665 @deftypefnx {C Function} void scm_wrong_type_arg_msg (char *@var{subr}, int @var{argnum}, SCM @var{bad_value}, const char *@var{expected})
1666 @deftypefnx {C Function} void scm_memory_error (char *@var{subr})
1667 Throw an error with the various keys described above.
1668 @deftypefnx {C Function} void scm_misc_error (const char *@var{subr}, const char *@var{message}, SCM @var{args})
1669
1670 In @code{scm_wrong_num_args}, @var{proc} should be a Scheme symbol
1671 which is the name of the procedure incorrectly invoked. The other
1672 routines take the name of the invoked procedure as a C string.
1673
1674 In @code{scm_wrong_type_arg_msg}, @var{expected} is a C string
1675 describing the type of argument that was expected.
1676
1677 In @code{scm_misc_error}, @var{message} is the error message string,
1678 possibly containing @code{simple-format} escapes (@pxref{Writing}), and
1679 the corresponding arguments in the @var{args} list.
1680 @end deftypefn
1681
1682
1683 @subsubsection Signalling Type Errors
1684
1685 Every function visible at the Scheme level should aggressively check the
1686 types of its arguments, to avoid misinterpreting a value, and perhaps
1687 causing a segmentation fault. Guile provides some macros to make this
1688 easier.
1689
1690 @deftypefn Macro void SCM_ASSERT (int @var{test}, SCM @var{obj}, unsigned int @var{position}, const char *@var{subr})
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})
1692 If @var{test} is zero, signal a ``wrong type argument'' error,
1693 attributed to the subroutine named @var{subr}, operating on the value
1694 @var{obj}, which is the @var{position}'th argument of @var{subr}.
1695
1696 In @code{SCM_ASSERT_TYPE}, @var{expected} is a C string describing the
1697 type of argument that was expected.
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
1707 One of the above values can be used for @var{position} to indicate the
1708 number of the argument of @var{subr} which is being checked.
1709 Alternatively, a positive integer number can be used, which allows to
1710 check arguments after the seventh. However, for parameter numbers up to
1711 seven it is preferable to use @code{SCM_ARGN} instead of the
1712 corresponding raw number, since it will make the code easier to
1713 understand.
1714 @end deftypefn
1715
1716 @deftypefn Macro int SCM_ARGn
1717 Passing a value of zero or @code{SCM_ARGn} for @var{position} allows to
1718 leave 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
1722 @node Continuation Barriers
1723 @subsection Continuation Barriers
1724
1725 The non-local flow of control caused by continuations might sometimes
1726 not be wanted. You can use @code{with-continuation-barrier} to erect
1727 fences that continuations can not pass.
1728
1729 @deffn {Scheme Procedure} with-continuation-barrier proc
1730 @deffnx {C Function} scm_with_continuation_barrier (proc)
1731 Call @var{proc} and return its result. Do not allow the invocation of
1732 continuations that would leave or enter the dynamic extent of the call
1733 to @code{with-continuation-barrier}. Such an attempt causes an error
1734 to be signaled.
1735
1736 Throws (such as errors) that are not caught from within @var{proc} are
1737 caught by @code{with-continuation-barrier}. In that case, a short
1738 message is printed to the current error port and @code{#f} is returned.
1739
1740 Thus, @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)
1744 Like @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
1749 @c Local Variables:
1750 @c TeX-master: "guile.texi"
1751 @c End: