typo fix
[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.
56664c08 3@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2009
07d83abe
MV
4@c Free Software Foundation, Inc.
5@c See the file guile.texi for copying conditions.
6
7@page
8@node Control Mechanisms
9@section Controlling the Flow of Program Execution
10
11See @ref{Control Flow} for a discussion of how the more general control
12flow of Scheme affects C code.
13
14@menu
15* begin:: Evaluating a sequence of expressions.
16* if cond case:: Simple conditional evaluation.
17* and or:: Conditional evaluation of a sequence.
18* while do:: Iteration mechanisms.
19* Continuations:: Continuations.
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
151the result of this evaluation is compared against all @var{datum}s using
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
269@code{#f} the first time then @var{body} is not executed at all. The
270return value is unspecified.
271
272Within @code{while}, two extra bindings are provided, they can be used
273from both @var{cond} and @var{body}.
274
275@deffn {Scheme Procedure} break
276Break out of the @code{while} form.
277@end deffn
278
279@deffn {Scheme Procedure} continue
280Abandon the current iteration, go back to the start and test
281@var{cond} again, etc.
282@end deffn
283
284Each @code{while} form gets its own @code{break} and @code{continue}
285procedures, operating on that @code{while}. This means when loops are
286nested the outer @code{break} can be used to escape all the way out.
287For example,
288
289@example
290(while (test1)
291 (let ((outer-break break))
292 (while (test2)
293 (if (something)
294 (outer-break #f))
295 ...)))
296@end example
297
298Note that each @code{break} and @code{continue} procedure can only be
299used within the dynamic extent of its @code{while}. Outside the
300@code{while} their behaviour is unspecified.
301@end deffn
302
303@cindex named let
304Another very common way of expressing iteration in Scheme programs is
305the use of the so-called @dfn{named let}.
306
307Named let is a variant of @code{let} which creates a procedure and calls
308it in one step. Because of the newly created procedure, named let is
309more powerful than @code{do}--it can be used for iteration, but also
310for arbitrary recursion.
311
312@deffn syntax let variable bindings body
313For the definition of @var{bindings} see the documentation about
314@code{let} (@pxref{Local Bindings}).
315
316Named @code{let} works as follows:
317
318@itemize @bullet
319@item
320A new procedure which accepts as many arguments as are in @var{bindings}
321is created and bound locally (using @code{let}) to @var{variable}. The
322new procedure's formal argument names are the name of the
323@var{variables}.
324
325@item
326The @var{body} expressions are inserted into the newly created procedure.
327
328@item
329The procedure is called with the @var{init} expressions as the formal
330arguments.
331@end itemize
332
333The next example implements a loop which iterates (by recursion) 1000
334times.
335
336@lisp
337(let lp ((x 1000))
338 (if (positive? x)
339 (lp (- x 1))
340 x))
341@result{}
3420
343@end lisp
344@end deffn
345
346
347@node Continuations
348@subsection Continuations
349@cindex continuations
350
351A ``continuation'' is the code that will execute when a given function
352or expression returns. For example, consider
353
354@example
355(define (foo)
356 (display "hello\n")
357 (display (bar)) (newline)
358 (exit))
359@end example
360
361The continuation from the call to @code{bar} comprises a
362@code{display} of the value returned, a @code{newline} and an
363@code{exit}. This can be expressed as a function of one argument.
364
365@example
366(lambda (r)
367 (display r) (newline)
368 (exit))
369@end example
370
371In Scheme, continuations are represented as special procedures just
372like this. The special property is that when a continuation is called
373it abandons the current program location and jumps directly to that
374represented by the continuation.
375
376A continuation is like a dynamic label, capturing at run-time a point
377in program execution, including all the nested calls that have lead to
378it (or rather the code that will execute when those calls return).
379
380Continuations are created with the following functions.
381
382@deffn {Scheme Procedure} call-with-current-continuation proc
383@deffnx {Scheme Procedure} call/cc proc
384@rnindex call-with-current-continuation
385Capture the current continuation and call @code{(@var{proc}
386@var{cont})} with it. The return value is the value returned by
387@var{proc}, or when @code{(@var{cont} @var{value})} is later invoked,
388the return is the @var{value} passed.
389
390Normally @var{cont} should be called with one argument, but when the
391location resumed is expecting multiple values (@pxref{Multiple
392Values}) then they should be passed as multiple arguments, for
393instance @code{(@var{cont} @var{x} @var{y} @var{z})}.
394
b4fddbbe
MV
395@var{cont} may only be used from the same side of a continuation
396barrier as it was created (@pxref{Continuation Barriers}), and in a
397multi-threaded program only from the thread in which it was created.
07d83abe
MV
398
399The call to @var{proc} is not part of the continuation captured, it runs
400only when the continuation is created. Often a program will want to
401store @var{cont} somewhere for later use; this can be done in
402@var{proc}.
403
404The @code{call} in the name @code{call-with-current-continuation}
405refers to the way a call to @var{proc} gives the newly created
406continuation. It's not related to the way a call is used later to
407invoke that continuation.
408
409@code{call/cc} is an alias for @code{call-with-current-continuation}.
410This is in common use since the latter is rather long.
411@end deffn
412
413@deftypefn {C Function} SCM scm_make_continuation (int *first)
414Capture the current continuation as described above. The return value
415is the new continuation, and @var{*first} is set to 1.
416
417When the continuation is invoked, @code{scm_make_continuation} will
418return again, this time returning the value (or set of multiple
419values) passed in that invocation, and with @var{*first} set to 0.
420@end deftypefn
421
422@sp 1
423@noindent
424Here is a simple example,
425
426@example
427(define kont #f)
428(format #t "the return is ~a\n"
429 (call/cc (lambda (k)
430 (set! kont k)
431 1)))
432@result{} the return is 1
433
434(kont 2)
435@result{} the return is 2
436@end example
437
438@code{call/cc} captures a continuation in which the value returned is
439going to be displayed by @code{format}. The @code{lambda} stores this
440in @code{kont} and gives an initial return @code{1} which is
441displayed. The later invocation of @code{kont} resumes the captured
442point, but this time returning @code{2}, which is displayed.
443
444When Guile is run interactively, a call to @code{format} like this has
445an implicit return back to the read-eval-print loop. @code{call/cc}
446captures that like any other return, which is why interactively
447@code{kont} will come back to read more input.
448
449@sp 1
450C programmers may note that @code{call/cc} is like @code{setjmp} in
451the way it records at runtime a point in program execution. A call to
452a continuation is like a @code{longjmp} in that it abandons the
453present location and goes to the recorded one. Like @code{longjmp},
454the value passed to the continuation is the value returned by
455@code{call/cc} on resuming there. However @code{longjmp} can only go
456up the program stack, but the continuation mechanism can go anywhere.
457
458When a continuation is invoked, @code{call/cc} and subsequent code
459effectively ``returns'' a second time. It can be confusing to imagine
460a function returning more times than it was called. It may help
461instead to think of it being stealthily re-entered and then program
462flow going on as normal.
463
464@code{dynamic-wind} (@pxref{Dynamic Wind}) can be used to ensure setup
465and cleanup code is run when a program locus is resumed or abandoned
661ae7ab 466through the continuation mechanism.
07d83abe
MV
467
468@sp 1
469Continuations are a powerful mechanism, and can be used to implement
470almost any sort of control structure, such as loops, coroutines, or
471exception handlers.
472
473However the implementation of continuations in Guile is not as
474efficient as one might hope, because Guile is designed to cooperate
475with programs written in other languages, such as C, which do not know
476about continuations. Basically continuations are captured by a block
477copy of the stack, and resumed by copying back.
478
479For this reason, generally continuations should be used only when
480there is no other simple way to achieve the desired result, or when
481the elegance of the continuation mechanism outweighs the need for
482performance.
483
484Escapes upwards from loops or nested functions are generally best
485handled with exceptions (@pxref{Exceptions}). Coroutines can be
486efficiently implemented with cooperating threads (a thread holds a
487full program stack but doesn't copy it around the way continuations
488do).
489
490
491@node Multiple Values
492@subsection Returning and Accepting Multiple Values
493
494@cindex multiple values
495@cindex receive
496
497Scheme allows a procedure to return more than one value to its caller.
498This is quite different to other languages which only allow
499single-value returns. Returning multiple values is different from
500returning a list (or pair or vector) of values to the caller, because
501conceptually not @emph{one} compound object is returned, but several
502distinct values.
503
504The primitive procedures for handling multiple values are @code{values}
505and @code{call-with-values}. @code{values} is used for returning
506multiple values from a procedure. This is done by placing a call to
507@code{values} with zero or more arguments in tail position in a
508procedure body. @code{call-with-values} combines a procedure returning
509multiple values with a procedure which accepts these values as
510parameters.
511
512@rnindex values
513@deffn {Scheme Procedure} values arg1 @dots{} argN
514@deffnx {C Function} scm_values (args)
515Delivers all of its arguments to its continuation. Except for
516continuations created by the @code{call-with-values} procedure,
517all continuations take exactly one value. The effect of
518passing no value or more than one value to continuations that
519were not created by @code{call-with-values} is unspecified.
520
521For @code{scm_values}, @var{args} is a list of arguments and the
522return is a multiple-values object which the caller can return. In
523the current implementation that object shares structure with
524@var{args}, so @var{args} should not be modified subsequently.
525@end deffn
526
527@rnindex call-with-values
528@deffn {Scheme Procedure} call-with-values producer consumer
529Calls its @var{producer} argument with no values and a
530continuation that, when passed some values, calls the
531@var{consumer} procedure with those values as arguments. The
532continuation for the call to @var{consumer} is the continuation
533of the call to @code{call-with-values}.
534
535@example
536(call-with-values (lambda () (values 4 5))
537 (lambda (a b) b))
538@result{} 5
539
540@end example
541@example
542(call-with-values * -)
543@result{} -1
544@end example
545@end deffn
546
547In addition to the fundamental procedures described above, Guile has a
23f2b9a3
KR
548module which exports a syntax called @code{receive}, which is much
549more convenient. This is in the @code{(ice-9 receive)} and is the
550same as specified by SRFI-8 (@pxref{SRFI-8}).
07d83abe
MV
551
552@lisp
553(use-modules (ice-9 receive))
554@end lisp
555
556@deffn {library syntax} receive formals expr body @dots{}
23f2b9a3
KR
557Evaluate the expression @var{expr}, and bind the result values (zero
558or more) to the formal arguments in @var{formals}. @var{formals} is a
559list of symbols, like the argument list in a @code{lambda}
560(@pxref{Lambda}). After binding the variables, the expressions in
561@var{body} @dots{} are evaluated in order, the return value is the
562result from the last expression.
563
564For example getting results from @code{partition} in SRFI-1
565(@pxref{SRFI-1}),
566
567@example
568(receive (odds evens)
569 (partition odd? '(7 4 2 8 3))
570 (display odds)
571 (display " and ")
572 (display evens))
573@print{} (7 3) and (4 2 8)
574@end example
575
07d83abe
MV
576@end deffn
577
578
579@node Exceptions
580@subsection Exceptions
581@cindex error handling
582@cindex exception handling
583
584A common requirement in applications is to want to jump
585@dfn{non-locally} from the depths of a computation back to, say, the
586application's main processing loop. Usually, the place that is the
587target of the jump is somewhere in the calling stack of procedures that
588called the procedure that wants to jump back. For example, typical
589logic for a key press driven application might look something like this:
590
591@example
592main-loop:
593 read the next key press and call dispatch-key
594
595dispatch-key:
596 lookup the key in a keymap and call an appropriate procedure,
597 say find-file
598
599find-file:
600 interactively read the required file name, then call
601 find-specified-file
602
603find-specified-file:
604 check whether file exists; if not, jump back to main-loop
605 @dots{}
606@end example
607
608The jump back to @code{main-loop} could be achieved by returning through
609the stack one procedure at a time, using the return value of each
610procedure to indicate the error condition, but Guile (like most modern
611programming languages) provides an additional mechanism called
612@dfn{exception handling} that can be used to implement such jumps much
613more conveniently.
614
615@menu
616* Exception Terminology:: Different ways to say the same thing.
617* Catch:: Setting up to catch exceptions.
7b4c914e 618* Throw Handlers:: Adding extra handling to a throw.
07d83abe 619* Lazy Catch:: Catch without unwinding the stack.
7b4c914e 620* Throw:: Throwing an exception.
07d83abe
MV
621* Exception Implementation:: How Guile implements exceptions.
622@end menu
623
624
625@node Exception Terminology
626@subsubsection Exception Terminology
627
628There are several variations on the terminology for dealing with
629non-local jumps. It is useful to be aware of them, and to realize
630that they all refer to the same basic mechanism.
631
632@itemize @bullet
633@item
634Actually making a non-local jump may be called @dfn{raising an
635exception}, @dfn{raising a signal}, @dfn{throwing an exception} or
636@dfn{doing a long jump}. When the jump indicates an error condition,
637people may talk about @dfn{signalling}, @dfn{raising} or @dfn{throwing}
638@dfn{an error}.
639
640@item
641Handling the jump at its target may be referred to as @dfn{catching} or
642@dfn{handling} the @dfn{exception}, @dfn{signal} or, where an error
643condition is involved, @dfn{error}.
644@end itemize
645
646Where @dfn{signal} and @dfn{signalling} are used, special care is needed
647to avoid the risk of confusion with POSIX signals.
648
649This manual prefers to speak of throwing and catching exceptions, since
650this terminology matches the corresponding Guile primitives.
651
652
653@node Catch
654@subsubsection Catching Exceptions
655
656@code{catch} is used to set up a target for a possible non-local jump.
657The arguments of a @code{catch} expression are a @dfn{key}, which
658restricts the set of exceptions to which this @code{catch} applies, a
7b4c914e
NJ
659thunk that specifies the code to execute and one or two @dfn{handler}
660procedures that say what to do if an exception is thrown while executing
661the code. If the execution thunk executes @dfn{normally}, which means
662without throwing any exceptions, the handler procedures are not called
663at all.
07d83abe
MV
664
665When an exception is thrown using the @code{throw} function, the first
666argument of the @code{throw} is a symbol that indicates the type of the
667exception. For example, Guile throws an exception using the symbol
668@code{numerical-overflow} to indicate numerical overflow errors such as
669division by zero:
670
671@lisp
672(/ 1 0)
673@result{}
674ABORT: (numerical-overflow)
675@end lisp
676
677The @var{key} argument in a @code{catch} expression corresponds to this
678symbol. @var{key} may be a specific symbol, such as
679@code{numerical-overflow}, in which case the @code{catch} applies
680specifically to exceptions of that type; or it may be @code{#t}, which
681means that the @code{catch} applies to all exceptions, irrespective of
682their type.
683
684The second argument of a @code{catch} expression should be a thunk
685(i.e. a procedure that accepts no arguments) that specifies the normal
686case code. The @code{catch} is active for the execution of this thunk,
687including any code called directly or indirectly by the thunk's body.
688Evaluation of the @code{catch} expression activates the catch and then
689calls this thunk.
690
691The third argument of a @code{catch} expression is a handler procedure.
692If an exception is thrown, this procedure is called with exactly the
693arguments specified by the @code{throw}. Therefore, the handler
694procedure must be designed to accept a number of arguments that
695corresponds to the number of arguments in all @code{throw} expressions
696that can be caught by this @code{catch}.
697
7b4c914e
NJ
698The fourth, optional argument of a @code{catch} expression is another
699handler procedure, called the @dfn{pre-unwind} handler. It differs from
700the third argument in that if an exception is thrown, it is called,
701@emph{before} the third argument handler, in exactly the dynamic context
702of the @code{throw} expression that threw the exception. This means
703that it is useful for capturing or displaying the stack at the point of
704the @code{throw}, or for examining other aspects of the dynamic context,
705such as fluid values, before the context is unwound back to that of the
706prevailing @code{catch}.
707
708@deffn {Scheme Procedure} catch key thunk handler [pre-unwind-handler]
709@deffnx {C Function} scm_catch_with_pre_unwind_handler (key, thunk, handler, pre_unwind_handler)
07d83abe
MV
710@deffnx {C Function} scm_catch (key, thunk, handler)
711Invoke @var{thunk} in the dynamic context of @var{handler} for
712exceptions matching @var{key}. If thunk throws to the symbol
713@var{key}, then @var{handler} is invoked this way:
714@lisp
715(handler key args ...)
716@end lisp
717
718@var{key} is a symbol or @code{#t}.
719
720@var{thunk} takes no arguments. If @var{thunk} returns
721normally, that is the return value of @code{catch}.
722
723Handler is invoked outside the scope of its own @code{catch}.
724If @var{handler} again throws to the same key, a new handler
725from further up the call chain is invoked.
726
727If the key is @code{#t}, then a throw to @emph{any} symbol will
728match this call to @code{catch}.
7b4c914e
NJ
729
730If a @var{pre-unwind-handler} is given and @var{thunk} throws
731an exception that matches @var{key}, Guile calls the
732@var{pre-unwind-handler} before unwinding the dynamic state and
733invoking the main @var{handler}. @var{pre-unwind-handler} should
734be a procedure with the same signature as @var{handler}, that
735is @code{(lambda (key . args))}. It is typically used to save
736the stack at the point where the exception occurred, but can also
737query other parts of the dynamic state at that point, such as
738fluid values.
739
740A @var{pre-unwind-handler} can exit either normally or non-locally.
741If it exits normally, Guile unwinds the stack and dynamic context
742and then calls the normal (third argument) handler. If it exits
743non-locally, that exit determines the continuation.
07d83abe
MV
744@end deffn
745
7b4c914e 746If a handler procedure needs to match a variety of @code{throw}
07d83abe
MV
747expressions with varying numbers of arguments, you should write it like
748this:
749
750@lisp
751(lambda (key . args)
752 @dots{})
753@end lisp
754
755@noindent
756The @var{key} argument is guaranteed always to be present, because a
757@code{throw} without a @var{key} is not valid. The number and
758interpretation of the @var{args} varies from one type of exception to
759another, but should be specified by the documentation for each exception
760type.
761
7b4c914e
NJ
762Note that, once the normal (post-unwind) handler procedure is invoked,
763the catch that led to the handler procedure being called is no longer
764active. Therefore, if the handler procedure itself throws an exception,
765that exception can only be caught by another active catch higher up the
766call stack, if there is one.
07d83abe
MV
767
768@sp 1
7b4c914e
NJ
769@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)
770@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)
771The above @code{scm_catch_with_pre_unwind_handler} and @code{scm_catch}
772take Scheme procedures as body and handler arguments.
773@code{scm_c_catch} and @code{scm_internal_catch} are equivalents taking
774C functions.
775
776@var{body} is called as @code{@var{body} (@var{body_data})} with a catch
777on exceptions of the given @var{tag} type. If an exception is caught,
778@var{pre_unwind_handler} and @var{handler} are called as
779@code{@var{handler} (@var{handler_data}, @var{key}, @var{args})}.
780@var{key} and @var{args} are the @code{SCM} key and argument list from
781the @code{throw}.
07d83abe
MV
782
783@tpindex scm_t_catch_body
784@tpindex scm_t_catch_handler
785@var{body} and @var{handler} should have the following prototypes.
786@code{scm_t_catch_body} and @code{scm_t_catch_handler} are pointer
787typedefs for these.
788
789@example
790SCM body (void *data);
791SCM handler (void *data, SCM key, SCM args);
792@end example
793
794The @var{body_data} and @var{handler_data} parameters are passed to
795the respective calls so an application can communicate extra
796information to those functions.
797
798If the data consists of an @code{SCM} object, care should be taken
799that it isn't garbage collected while still required. If the
800@code{SCM} is a local C variable, one way to protect it is to pass a
801pointer to that variable as the data parameter, since the C compiler
802will then know the value must be held on the stack. Another way is to
803use @code{scm_remember_upto_here_1} (@pxref{Remembering During
804Operations}).
805@end deftypefn
806
807
7b4c914e
NJ
808@node Throw Handlers
809@subsubsection Throw Handlers
07d83abe 810
7b4c914e
NJ
811It's sometimes useful to be able to intercept an exception that is being
812thrown, but without changing where in the dynamic context that exception
813will eventually be caught. This could be to clean up some related state
814or to pass information about the exception to a debugger, for example.
815The @code{with-throw-handler} procedure provides a way to do this.
07d83abe 816
7b4c914e
NJ
817@deffn {Scheme Procedure} with-throw-handler key thunk handler
818@deffnx {C Function} scm_with_throw_handler (key, thunk, handler)
819Add @var{handler} to the dynamic context as a throw handler
820for key @var{key}, then invoke @var{thunk}.
07d83abe
MV
821@end deffn
822
7b4c914e
NJ
823@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)
824The above @code{scm_with_throw_handler} takes Scheme procedures as body
825(thunk) and handler arguments. @code{scm_c_with_throw_handler} is an
826equivalent taking C functions. See @code{scm_c_catch} (@pxref{Catch})
827for a description of the parameters, the behaviour however of course
828follows @code{with-throw-handler}.
829@end deftypefn
07d83abe 830
7b4c914e
NJ
831If @var{thunk} throws an exception, Guile handles that exception by
832invoking the innermost @code{catch} or throw handler whose key matches
833that of the exception. When the innermost thing is a throw handler,
834Guile calls the specified handler procedure using @code{(apply
835@var{handler} key args)}. The handler procedure may either return
836normally or exit non-locally. If it returns normally, Guile passes the
837exception on to the next innermost @code{catch} or throw handler. If it
838exits non-locally, that exit determines the continuation.
839
840The behaviour of a throw handler is very similar to that of a
841@code{catch} expression's optional pre-unwind handler. In particular, a
842throw handler's handler procedure is invoked in the exact dynamic
843context of the @code{throw} expression, just as a pre-unwind handler is.
844@code{with-throw-handler} may be seen as a half-@code{catch}: it does
845everything that a @code{catch} would do until the point where
846@code{catch} would start unwinding the stack and dynamic context, but
847then it rethrows to the next innermost @code{catch} or throw handler
848instead.
07d83abe
MV
849
850
851@node Lazy Catch
852@subsubsection Catch Without Unwinding
853
7b4c914e
NJ
854Before version 1.8, Guile's closest equivalent to
855@code{with-throw-handler} was @code{lazy-catch}. From version 1.8
856onwards we recommend using @code{with-throw-handler} because its
857behaviour is more useful than that of @code{lazy-catch}, but
858@code{lazy-catch} is still supported as well.
859
07d83abe
MV
860A @dfn{lazy catch} is used in the same way as a normal @code{catch},
861with @var{key}, @var{thunk} and @var{handler} arguments specifying the
862exception type, normal case code and handler procedure, but differs in
863one important respect: the handler procedure is executed without
864unwinding the call stack from the context of the @code{throw} expression
865that caused the handler to be invoked.
866
867@deffn {Scheme Procedure} lazy-catch key thunk handler
868@deffnx {C Function} scm_lazy_catch (key, thunk, handler)
869This behaves exactly like @code{catch}, except that it does
870not unwind the stack before invoking @var{handler}.
7b4c914e
NJ
871If the @var{handler} procedure returns normally, Guile
872rethrows the same exception again to the next innermost catch,
873lazy-catch or throw handler. If the @var{handler} exits
874non-locally, that exit determines the continuation.
07d83abe
MV
875@end deffn
876
877@deftypefn {C Function} SCM scm_internal_lazy_catch (SCM tag, scm_t_catch_body body, void *body_data, scm_t_catch_handler handler, void *handler_data)
878The above @code{scm_lazy_catch} takes Scheme procedures as body and
879handler arguments. @code{scm_internal_lazy_catch} is an equivalent
880taking C functions. See @code{scm_internal_catch} (@pxref{Catch}) for
881a description of the parameters, the behaviour however of course
882follows @code{lazy-catch}.
883@end deftypefn
884
7b4c914e
NJ
885Typically @var{handler} is used to display a backtrace of the stack at
886the point where the corresponding @code{throw} occurred, or to save off
887this information for possible display later.
07d83abe
MV
888
889Not unwinding the stack means that throwing an exception that is caught
890by a @code{lazy-catch} is @emph{almost} equivalent to calling the
891@code{lazy-catch}'s handler inline instead of each @code{throw}, and
892then omitting the surrounding @code{lazy-catch}. In other words,
893
894@lisp
895(lazy-catch 'key
896 (lambda () @dots{} (throw 'key args @dots{}) @dots{})
897 handler)
898@end lisp
899
900@noindent
901is @emph{almost} equivalent to
902
903@lisp
904((lambda () @dots{} (handler 'key args @dots{}) @dots{}))
905@end lisp
906
907@noindent
908But why only @emph{almost}? The difference is that with
909@code{lazy-catch} (as with normal @code{catch}), the dynamic context is
910unwound back to just outside the @code{lazy-catch} expression before
911invoking the handler. (For an introduction to what is meant by dynamic
912context, @xref{Dynamic Wind}.)
913
914Then, when the handler @emph{itself} throws an exception, that exception
915must be caught by some kind of @code{catch} (including perhaps another
916@code{lazy-catch}) higher up the call stack.
917
9ef07f6f
KR
918The dynamic context also includes @code{with-fluids} blocks
919(@pxref{Fluids and Dynamic States}),
07d83abe
MV
920so the effect of unwinding the dynamic context can also be seen in fluid
921variable values. This is illustrated by the following code, in which
922the normal case thunk uses @code{with-fluids} to temporarily change the
923value of a fluid:
924
925@lisp
926(define f (make-fluid))
927(fluid-set! f "top level value")
928
929(define (handler . args)
930 (cons (fluid-ref f) args))
931
932(lazy-catch 'foo
933 (lambda ()
934 (with-fluids ((f "local value"))
935 (throw 'foo)))
936 handler)
937@result{}
938("top level value" foo)
939
940((lambda ()
941 (with-fluids ((f "local value"))
942 (handler 'foo))))
943@result{}
944("local value" foo)
945@end lisp
946
947@noindent
948In the @code{lazy-catch} version, the unwinding of dynamic context
949restores @code{f} to its value outside the @code{with-fluids} block
950before the handler is invoked, so the handler's @code{(fluid-ref f)}
951returns the external value.
952
953@code{lazy-catch} is useful because it permits the implementation of
954debuggers and other reflective programming tools that need to access the
955state of the call stack at the exact point where an exception or an
956error is thrown. For an example of this, see REFFIXME:stack-catch.
957
7b4c914e
NJ
958It should be obvious from the above that @code{lazy-catch} is very
959similar to @code{with-throw-handler}. In fact Guile implements
960@code{lazy-catch} in exactly the same way as @code{with-throw-handler},
961except with a flag set to say ``where there are slight differences
962between what @code{with-throw-handler} and @code{lazy-catch} would do,
963do what @code{lazy-catch} has always done''. There are two such
964differences:
965
966@enumerate
967@item
968@code{with-throw-handler} handlers execute in the full dynamic context
969of the originating @code{throw} call. @code{lazy-catch} handlers
970execute in the dynamic context of the @code{lazy-catch} expression,
971excepting only that the stack has not yet been unwound from the point of
972the @code{throw} call.
973
974@item
975If a @code{with-throw-handler} handler throws to a key that does not
976match the @code{with-throw-handler} expression's @var{key}, the new
977throw may be handled by a @code{catch} or throw handler that is _closer_
978to the throw than the first @code{with-throw-handler}. If a
979@code{lazy-catch} handler throws, it will always be handled by a
980@code{catch} or throw handler that is higher up the dynamic context than
981the first @code{lazy-catch}.
982@end enumerate
983
984Here is an example to illustrate the second difference:
985
986@lisp
987(catch 'a
988 (lambda ()
989 (with-throw-handler 'b
990 (lambda ()
991 (catch 'a
992 (lambda ()
993 (throw 'b))
994 inner-handler))
995 (lambda (key . args)
996 (throw 'a))))
997 outer-handler)
998@end lisp
999
1000@noindent
1001This code will call @code{inner-handler} and then continue with the
1002continuation of the inner @code{catch}. If the
1003@code{with-throw-handler} was changed to @code{lazy-catch}, however, the
1004code would call @code{outer-handler} and then continue with the
1005continuation of the outer @code{catch}.
1006
1007Modulo these two differences, any statements in the previous and
1008following subsections about throw handlers apply to lazy catches as
1009well.
1010
1011
1012@node Throw
1013@subsubsection Throwing Exceptions
1014
1015The @code{throw} primitive is used to throw an exception. One argument,
1016the @var{key}, is mandatory, and must be a symbol; it indicates the type
1017of exception that is being thrown. Following the @var{key},
1018@code{throw} accepts any number of additional arguments, whose meaning
1019depends on the exception type. The documentation for each possible type
1020of exception should specify the additional arguments that are expected
1021for that kind of exception.
1022
1023@deffn {Scheme Procedure} throw key . args
1024@deffnx {C Function} scm_throw (key, args)
1025Invoke the catch form matching @var{key}, passing @var{args} to the
1026@var{handler}.
1027
1028@var{key} is a symbol. It will match catches of the same symbol or of
1029@code{#t}.
1030
1031If there is no handler at all, Guile prints an error and then exits.
1032@end deffn
1033
1034When an exception is thrown, it will be caught by the innermost
1035@code{catch} or throw handler that applies to the type of the thrown
1036exception; in other words, whose @var{key} is either @code{#t} or the
1037same symbol as that used in the @code{throw} expression. Once Guile has
1038identified the appropriate @code{catch} or throw handler, it handles the
1039exception by applying the relevant handler procedure(s) to the arguments
1040of the @code{throw}.
1041
1042If there is no appropriate @code{catch} or throw handler for a thrown
1043exception, Guile prints an error to the current error port indicating an
1044uncaught exception, and then exits. In practice, it is quite difficult
1045to observe this behaviour, because Guile when used interactively
1046installs a top level @code{catch} handler that will catch all exceptions
1047and print an appropriate error message @emph{without} exiting. For
1048example, this is what happens if you try to throw an unhandled exception
1049in the standard Guile REPL; note that Guile's command loop continues
1050after the error message:
1051
1052@lisp
1053guile> (throw 'badex)
1054<unnamed port>:3:1: In procedure gsubr-apply @dots{}
1055<unnamed port>:3:1: unhandled-exception: badex
1056ABORT: (misc-error)
1057guile>
1058@end lisp
1059
1060The default uncaught exception behaviour can be observed by evaluating a
1061@code{throw} expression from the shell command line:
1062
1063@example
1064$ guile -c "(begin (throw 'badex) (display \"here\\n\"))"
1065guile: uncaught throw to badex: ()
1066$
1067@end example
1068
1069@noindent
1070That Guile exits immediately following the uncaught exception
1071is shown by the absence of any output from the @code{display}
1072expression, because Guile never gets to the point of evaluating that
1073expression.
1074
07d83abe
MV
1075
1076@node Exception Implementation
1077@subsubsection How Guile Implements Exceptions
1078
1079It is traditional in Scheme to implement exception systems using
1080@code{call-with-current-continuation}. Continuations
1081(@pxref{Continuations}) are such a powerful concept that any other
1082control mechanism --- including @code{catch} and @code{throw} --- can be
1083implemented in terms of them.
1084
1085Guile does not implement @code{catch} and @code{throw} like this,
1086though. Why not? Because Guile is specifically designed to be easy to
1087integrate with applications written in C. In a mixed Scheme/C
1088environment, the concept of @dfn{continuation} must logically include
1089``what happens next'' in the C parts of the application as well as the
1090Scheme parts, and it turns out that the only reasonable way of
1091implementing continuations like this is to save and restore the complete
1092C stack.
1093
1094So Guile's implementation of @code{call-with-current-continuation} is a
1095stack copying one. This allows it to interact well with ordinary C
1096code, but means that creating and calling a continuation is slowed down
1097by the time that it takes to copy the C stack.
1098
1099The more targeted mechanism provided by @code{catch} and @code{throw}
1100does not need to save and restore the C stack because the @code{throw}
1101always jumps to a location higher up the stack of the code that executes
1102the @code{throw}. Therefore Guile implements the @code{catch} and
1103@code{throw} primitives independently of
1104@code{call-with-current-continuation}, in a way that takes advantage of
1105this @emph{upwards only} nature of exceptions.
1106
1107
1108@node Error Reporting
1109@subsection Procedures for Signaling Errors
1110
1111Guile provides a set of convenience procedures for signaling error
1112conditions that are implemented on top of the exception primitives just
1113described.
1114
1115@deffn {Scheme Procedure} error msg args @dots{}
1116Raise an error with key @code{misc-error} and a message constructed by
1117displaying @var{msg} and writing @var{args}.
1118@end deffn
1119
1120@deffn {Scheme Procedure} scm-error key subr message args data
1121@deffnx {C Function} scm_error_scm (key, subr, message, args, data)
1122Raise an error with key @var{key}. @var{subr} can be a string
1123naming the procedure associated with the error, or @code{#f}.
1124@var{message} is the error message string, possibly containing
1125@code{~S} and @code{~A} escapes. When an error is reported,
1126these are replaced by formatting the corresponding members of
1127@var{args}: @code{~A} (was @code{%s} in older versions of
1128Guile) formats using @code{display} and @code{~S} (was
1129@code{%S}) formats using @code{write}. @var{data} is a list or
1130@code{#f} depending on @var{key}: if @var{key} is
1131@code{system-error} then it should be a list containing the
1132Unix @code{errno} value; If @var{key} is @code{signal} then it
7cd44c6d
MV
1133should be a list containing the Unix signal number; If
1134@var{key} is @code{out-of-range} or @code{wrong-type-arg},
1135it is a list containing the bad value; otherwise
07d83abe
MV
1136it will usually be @code{#f}.
1137@end deffn
1138
1139@deffn {Scheme Procedure} strerror err
1140@deffnx {C Function} scm_strerror (err)
44ba562e
KR
1141Return the Unix error message corresponding to @var{err}, an integer
1142@code{errno} value.
1143
1144When @code{setlocale} has been called (@pxref{Locales}), the message
1145is in the language and charset of @code{LC_MESSAGES}. (This is done
1146by the C library.)
07d83abe
MV
1147@end deffn
1148
1149@c begin (scm-doc-string "boot-9.scm" "false-if-exception")
1150@deffn syntax false-if-exception expr
1151Returns the result of evaluating its argument; however
1152if an exception occurs then @code{#f} is returned instead.
1153@end deffn
1154@c end
1155
1156
1157@node Dynamic Wind
1158@subsection Dynamic Wind
1159
661ae7ab
MV
1160For Scheme code, the fundamental procedure to react to non-local entry
1161and exits of dynamic contexts is @code{dynamic-wind}. C code could
1162use @code{scm_internal_dynamic_wind}, but since C does not allow the
1163convenient construction of anonymous procedures that close over
1164lexical variables, this will be, well, inconvenient.
1165
1166Therefore, Guile offers the functions @code{scm_dynwind_begin} and
1167@code{scm_dynwind_end} to delimit a dynamic extent. Within this
a1ef7406 1168dynamic extent, which is called a @dfn{dynwind context}, you can
661ae7ab
MV
1169perform various @dfn{dynwind actions} that control what happens when
1170the dynwind context is entered or left. For example, you can register
1171a cleanup routine with @code{scm_dynwind_unwind_handler} that is
1172executed when the context is left. There are several other more
1173specialized dynwind actions as well, for example to temporarily block
1174the execution of asyncs or to temporarily change the current output
1175port. They are described elsewhere in this manual.
1176
1177Here is an example that shows how to prevent memory leaks.
1178
1179@example
1180
1181/* Suppose there is a function called FOO in some library that you
1182 would like to make available to Scheme code (or to C code that
1183 follows the Scheme conventions).
1184
1185 FOO takes two C strings and returns a new string. When an error has
1186 occurred in FOO, it returns NULL.
1187*/
1188
1189char *foo (char *s1, char *s2);
1190
1191/* SCM_FOO interfaces the C function FOO to the Scheme way of life.
1192 It takes care to free up all temporary strings in the case of
1193 non-local exits.
1194 */
1195
1196SCM
1197scm_foo (SCM s1, SCM s2)
1198@{
1199 char *c_s1, *c_s2, *c_res;
1200
1201 scm_dynwind_begin (0);
1202
1203 c_s1 = scm_to_locale_string (s1);
1204
1205 /* Call 'free (c_s1)' when the dynwind context is left.
1206 */
1207 scm_dynwind_unwind_handler (free, c_s1, SCM_F_WIND_EXPLICITLY);
1208
1209 c_s2 = scm_to_locale_string (s2);
1210
1211 /* Same as above, but more concisely.
1212 */
1213 scm_dynwind_free (c_s2);
1214
1215 c_res = foo (c_s1, c_s2);
1216 if (c_res == NULL)
1217 scm_memory_error ("foo");
1218
1219 scm_dynwind_end ();
1220
1221 return scm_take_locale_string (res);
1222@}
1223@end example
1224
07d83abe
MV
1225@rnindex dynamic-wind
1226@deffn {Scheme Procedure} dynamic-wind in_guard thunk out_guard
1227@deffnx {C Function} scm_dynamic_wind (in_guard, thunk, out_guard)
1228All three arguments must be 0-argument procedures.
1229@var{in_guard} is called, then @var{thunk}, then
1230@var{out_guard}.
1231
1232If, any time during the execution of @var{thunk}, the
1233dynamic extent of the @code{dynamic-wind} expression is escaped
1234non-locally, @var{out_guard} is called. If the dynamic extent of
1235the dynamic-wind is re-entered, @var{in_guard} is called. Thus
1236@var{in_guard} and @var{out_guard} may be called any number of
1237times.
40296bab 1238
07d83abe
MV
1239@lisp
1240(define x 'normal-binding)
1241@result{} x
40296bab
KR
1242(define a-cont
1243 (call-with-current-continuation
1244 (lambda (escape)
1245 (let ((old-x x))
1246 (dynamic-wind
1247 ;; in-guard:
1248 ;;
1249 (lambda () (set! x 'special-binding))
1250
1251 ;; thunk
1252 ;;
1253 (lambda () (display x) (newline)
1254 (call-with-current-continuation escape)
1255 (display x) (newline)
1256 x)
1257
1258 ;; out-guard:
1259 ;;
1260 (lambda () (set! x old-x)))))))
07d83abe
MV
1261;; Prints:
1262special-binding
1263;; Evaluates to:
1264@result{} a-cont
1265x
1266@result{} normal-binding
1267(a-cont #f)
1268;; Prints:
1269special-binding
1270;; Evaluates to:
1271@result{} a-cont ;; the value of the (define a-cont...)
1272x
1273@result{} normal-binding
1274a-cont
1275@result{} special-binding
1276@end lisp
1277@end deffn
1278
98241dc5
NJ
1279@deftp {C Type} scm_t_dynwind_flags
1280This is an enumeration of several flags that modify the behavior of
1281@code{scm_dynwind_begin}. The flags are listed in the following
1282table.
1283
1284@table @code
1285@item SCM_F_DYNWIND_REWINDABLE
1286The dynamic context is @dfn{rewindable}. This means that it can be
1287reentered non-locally (via the invokation of a continuation). The
1288default is that a dynwind context can not be reentered non-locally.
1289@end table
1290
1291@end deftp
1292
1293@deftypefn {C Function} void scm_dynwind_begin (scm_t_dynwind_flags flags)
661ae7ab
MV
1294The function @code{scm_dynwind_begin} starts a new dynamic context and
1295makes it the `current' one.
07d83abe 1296
661ae7ab
MV
1297The @var{flags} argument determines the default behavior of the
1298context. Normally, use 0. This will result in a context that can not
1299be reentered with a captured continuation. When you are prepared to
1300handle reentries, include @code{SCM_F_DYNWIND_REWINDABLE} in
1301@var{flags}.
07d83abe
MV
1302
1303Being prepared for reentry means that the effects of unwind handlers
1304can be undone on reentry. In the example above, we want to prevent a
1305memory leak on non-local exit and thus register an unwind handler that
1306frees the memory. But once the memory is freed, we can not get it
1307back on reentry. Thus reentry can not be allowed.
1308
1309The consequence is that continuations become less useful when
661ae7ab
MV
1310non-reenterable contexts are captured, but you don't need to worry
1311about that too much.
1312
1313The context is ended either implicitly when a non-local exit happens,
1314or explicitly with @code{scm_dynwind_end}. You must make sure that a
1315dynwind context is indeed ended properly. If you fail to call
1316@code{scm_dynwind_end} for each @code{scm_dynwind_begin}, the behavior
1317is undefined.
07d83abe
MV
1318@end deftypefn
1319
661ae7ab
MV
1320@deftypefn {C Function} void scm_dynwind_end ()
1321End the current dynamic context explicitly and make the previous one
1322current.
07d83abe
MV
1323@end deftypefn
1324
98241dc5
NJ
1325@deftp {C Type} scm_t_wind_flags
1326This is an enumeration of several flags that modify the behavior of
1327@code{scm_dynwind_unwind_handler} and
1328@code{scm_dynwind_rewind_handler}. The flags are listed in the
1329following table.
1330
1331@table @code
1332@item SCM_F_WIND_EXPLICITLY
1333@vindex SCM_F_WIND_EXPLICITLY
1334The registered action is also carried out when the dynwind context is
1335entered or left locally.
1336@end table
1337@end deftp
1338
1339@deftypefn {C Function} void scm_dynwind_unwind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
1340@deftypefnx {C Function} void scm_dynwind_unwind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
07d83abe 1341Arranges for @var{func} to be called with @var{data} as its arguments
661ae7ab
MV
1342when the current context ends implicitly. If @var{flags} contains
1343@code{SCM_F_WIND_EXPLICITLY}, @var{func} is also called when the
1344context ends explicitly with @code{scm_dynwind_end}.
07d83abe 1345
661ae7ab 1346The function @code{scm_dynwind_unwind_handler_with_scm} takes care that
07d83abe
MV
1347@var{data} is protected from garbage collection.
1348@end deftypefn
1349
98241dc5
NJ
1350@deftypefn {C Function} void scm_dynwind_rewind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
1351@deftypefnx {C Function} void scm_dynwind_rewind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
07d83abe 1352Arrange for @var{func} to be called with @var{data} as its argument when
661ae7ab 1353the current context is restarted by rewinding the stack. When @var{flags}
07d83abe
MV
1354contains @code{SCM_F_WIND_EXPLICITLY}, @var{func} is called immediately
1355as well.
1356
661ae7ab 1357The function @code{scm_dynwind_rewind_handler_with_scm} takes care that
07d83abe
MV
1358@var{data} is protected from garbage collection.
1359@end deftypefn
1360
9f1ba6a9
NJ
1361@deftypefn {C Function} void scm_dynwind_free (void *mem)
1362Arrange for @var{mem} to be freed automatically whenever the current
1363context is exited, whether normally or non-locally.
1364@code{scm_dynwind_free (mem)} is an equivalent shorthand for
1365@code{scm_dynwind_unwind_handler (free, mem, SCM_F_WIND_EXPLICITLY)}.
1366@end deftypefn
1367
07d83abe
MV
1368
1369@node Handling Errors
1370@subsection How to Handle Errors
1371
1372Error handling is based on @code{catch} and @code{throw}. Errors are
1373always thrown with a @var{key} and four arguments:
1374
1375@itemize @bullet
1376@item
1377@var{key}: a symbol which indicates the type of error. The symbols used
1378by libguile are listed below.
1379
1380@item
1381@var{subr}: the name of the procedure from which the error is thrown, or
1382@code{#f}.
1383
1384@item
1385@var{message}: a string (possibly language and system dependent)
1386describing the error. The tokens @code{~A} and @code{~S} can be
1387embedded within the message: they will be replaced with members of the
1388@var{args} list when the message is printed. @code{~A} indicates an
1389argument printed using @code{display}, while @code{~S} indicates an
1390argument printed using @code{write}. @var{message} can also be
1391@code{#f}, to allow it to be derived from the @var{key} by the error
1392handler (may be useful if the @var{key} is to be thrown from both C and
1393Scheme).
1394
1395@item
1396@var{args}: a list of arguments to be used to expand @code{~A} and
1397@code{~S} tokens in @var{message}. Can also be @code{#f} if no
1398arguments are required.
1399
1400@item
1401@var{rest}: a list of any additional objects required. e.g., when the
1402key is @code{'system-error}, this contains the C errno value. Can also
1403be @code{#f} if no additional objects are required.
1404@end itemize
1405
1406In addition to @code{catch} and @code{throw}, the following Scheme
1407facilities are available:
1408
1409@deffn {Scheme Procedure} display-error stack port subr message args rest
1410@deffnx {C Function} scm_display_error (stack, port, subr, message, args, rest)
1411Display an error message to the output port @var{port}.
1412@var{stack} is the saved stack for the error, @var{subr} is
1413the name of the procedure in which the error occurred and
1414@var{message} is the actual error message, which may contain
1415formatting instructions. These will format the arguments in
1416the list @var{args} accordingly. @var{rest} is currently
1417ignored.
1418@end deffn
1419
1420The following are the error keys defined by libguile and the situations
1421in which they are used:
1422
1423@itemize @bullet
1424@item
1425@cindex @code{error-signal}
1426@code{error-signal}: thrown after receiving an unhandled fatal signal
1427such as SIGSEGV, SIGBUS, SIGFPE etc. The @var{rest} argument in the throw
1428contains the coded signal number (at present this is not the same as the
1429usual Unix signal number).
1430
1431@item
1432@cindex @code{system-error}
1433@code{system-error}: thrown after the operating system indicates an
1434error condition. The @var{rest} argument in the throw contains the
1435errno value.
1436
1437@item
1438@cindex @code{numerical-overflow}
1439@code{numerical-overflow}: numerical overflow.
1440
1441@item
1442@cindex @code{out-of-range}
1443@code{out-of-range}: the arguments to a procedure do not fall within the
1444accepted domain.
1445
1446@item
1447@cindex @code{wrong-type-arg}
1448@code{wrong-type-arg}: an argument to a procedure has the wrong type.
1449
1450@item
1451@cindex @code{wrong-number-of-args}
1452@code{wrong-number-of-args}: a procedure was called with the wrong number
1453of arguments.
1454
1455@item
1456@cindex @code{memory-allocation-error}
1457@code{memory-allocation-error}: memory allocation error.
1458
1459@item
1460@cindex @code{stack-overflow}
1461@code{stack-overflow}: stack overflow error.
1462
1463@item
1464@cindex @code{regular-expression-syntax}
1465@code{regular-expression-syntax}: errors generated by the regular
1466expression library.
1467
1468@item
1469@cindex @code{misc-error}
1470@code{misc-error}: other errors.
1471@end itemize
1472
1473
1474@subsubsection C Support
1475
1476In the following C functions, @var{SUBR} and @var{MESSAGE} parameters
1477can be @code{NULL} to give the effect of @code{#f} described above.
1478
1479@deftypefn {C Function} SCM scm_error (SCM @var{key}, char *@var{subr}, char *@var{message}, SCM @var{args}, SCM @var{rest})
9a18d8d4 1480Throw an error, as per @code{scm-error} (@pxref{Error Reporting}).
07d83abe
MV
1481@end deftypefn
1482
1483@deftypefn {C Function} void scm_syserror (char *@var{subr})
1484@deftypefnx {C Function} void scm_syserror_msg (char *@var{subr}, char *@var{message}, SCM @var{args})
1485Throw an error with key @code{system-error} and supply @code{errno} in
1486the @var{rest} argument. For @code{scm_syserror} the message is
1487generated using @code{strerror}.
1488
1489Care should be taken that any code in between the failing operation
1490and the call to these routines doesn't change @code{errno}.
1491@end deftypefn
1492
1493@deftypefn {C Function} void scm_num_overflow (char *@var{subr})
1494@deftypefnx {C Function} void scm_out_of_range (char *@var{subr}, SCM @var{bad_value})
1495@deftypefnx {C Function} void scm_wrong_num_args (SCM @var{proc})
1496@deftypefnx {C Function} void scm_wrong_type_arg (char *@var{subr}, int @var{argnum}, SCM @var{bad_value})
1497@deftypefnx {C Function} void scm_memory_error (char *@var{subr})
1498Throw an error with the various keys described above.
1499
1500For @code{scm_wrong_num_args}, @var{proc} should be a Scheme symbol
1501which is the name of the procedure incorrectly invoked.
1502@end deftypefn
1503
1504
ce2612cd
NJ
1505@node Continuation Barriers
1506@subsection Continuation Barriers
1507
1508The non-local flow of control caused by continuations might sometimes
56664c08
AW
1509not be wanted. You can use @code{with-continuation-barrier} to erect
1510fences that continuations can not pass.
ce2612cd
NJ
1511
1512@deffn {Scheme Procedure} with-continuation-barrier proc
1513@deffnx {C Function} scm_with_continuation_barrier (proc)
1514Call @var{proc} and return its result. Do not allow the invocation of
1515continuations that would leave or enter the dynamic extent of the call
1516to @code{with-continuation-barrier}. Such an attempt causes an error
1517to be signaled.
1518
1519Throws (such as errors) that are not caught from within @var{proc} are
1520caught by @code{with-continuation-barrier}. In that case, a short
1521message is printed to the current error port and @code{#f} is returned.
1522
1523Thus, @code{with-continuation-barrier} returns exactly once.
1524@end deffn
1525
1526@deftypefn {C Function} {void *} scm_c_with_continuation_barrier (void *(*func) (void *), void *data)
1527Like @code{scm_with_continuation_barrier} but call @var{func} on
1528@var{data}. When an error is caught, @code{NULL} is returned.
1529@end deftypefn
1530
1531
07d83abe
MV
1532@c Local Variables:
1533@c TeX-master: "guile.texi"
1534@c End: