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