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