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