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