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