* api-i18n.texi: New file.
[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
375@var{cont} may only be used from the dynamic root in which it was
376created (@pxref{Dynamic Roots}), and in a multi-threaded program only
377from the thread in which it was created, since each thread is a
378separate dynamic root.
379
380The call to @var{proc} is not part of the continuation captured, it runs
381only when the continuation is created. Often a program will want to
382store @var{cont} somewhere for later use; this can be done in
383@var{proc}.
384
385The @code{call} in the name @code{call-with-current-continuation}
386refers to the way a call to @var{proc} gives the newly created
387continuation. It's not related to the way a call is used later to
388invoke that continuation.
389
390@code{call/cc} is an alias for @code{call-with-current-continuation}.
391This is in common use since the latter is rather long.
392@end deffn
393
394@deftypefn {C Function} SCM scm_make_continuation (int *first)
395Capture the current continuation as described above. The return value
396is the new continuation, and @var{*first} is set to 1.
397
398When the continuation is invoked, @code{scm_make_continuation} will
399return again, this time returning the value (or set of multiple
400values) passed in that invocation, and with @var{*first} set to 0.
401@end deftypefn
402
403@sp 1
404@noindent
405Here is a simple example,
406
407@example
408(define kont #f)
409(format #t "the return is ~a\n"
410 (call/cc (lambda (k)
411 (set! kont k)
412 1)))
413@result{} the return is 1
414
415(kont 2)
416@result{} the return is 2
417@end example
418
419@code{call/cc} captures a continuation in which the value returned is
420going to be displayed by @code{format}. The @code{lambda} stores this
421in @code{kont} and gives an initial return @code{1} which is
422displayed. The later invocation of @code{kont} resumes the captured
423point, but this time returning @code{2}, which is displayed.
424
425When Guile is run interactively, a call to @code{format} like this has
426an implicit return back to the read-eval-print loop. @code{call/cc}
427captures that like any other return, which is why interactively
428@code{kont} will come back to read more input.
429
430@sp 1
431C programmers may note that @code{call/cc} is like @code{setjmp} in
432the way it records at runtime a point in program execution. A call to
433a continuation is like a @code{longjmp} in that it abandons the
434present location and goes to the recorded one. Like @code{longjmp},
435the value passed to the continuation is the value returned by
436@code{call/cc} on resuming there. However @code{longjmp} can only go
437up the program stack, but the continuation mechanism can go anywhere.
438
439When a continuation is invoked, @code{call/cc} and subsequent code
440effectively ``returns'' a second time. It can be confusing to imagine
441a function returning more times than it was called. It may help
442instead to think of it being stealthily re-entered and then program
443flow going on as normal.
444
445@code{dynamic-wind} (@pxref{Dynamic Wind}) can be used to ensure setup
446and cleanup code is run when a program locus is resumed or abandoned
447through the continuation mechanism. C code can use @dfn{frames}
448(@pxref{Frames}).
449
450@sp 1
451Continuations are a powerful mechanism, and can be used to implement
452almost any sort of control structure, such as loops, coroutines, or
453exception handlers.
454
455However the implementation of continuations in Guile is not as
456efficient as one might hope, because Guile is designed to cooperate
457with programs written in other languages, such as C, which do not know
458about continuations. Basically continuations are captured by a block
459copy of the stack, and resumed by copying back.
460
461For this reason, generally continuations should be used only when
462there is no other simple way to achieve the desired result, or when
463the elegance of the continuation mechanism outweighs the need for
464performance.
465
466Escapes upwards from loops or nested functions are generally best
467handled with exceptions (@pxref{Exceptions}). Coroutines can be
468efficiently implemented with cooperating threads (a thread holds a
469full program stack but doesn't copy it around the way continuations
470do).
471
472
473@node Multiple Values
474@subsection Returning and Accepting Multiple Values
475
476@cindex multiple values
477@cindex receive
478
479Scheme allows a procedure to return more than one value to its caller.
480This is quite different to other languages which only allow
481single-value returns. Returning multiple values is different from
482returning a list (or pair or vector) of values to the caller, because
483conceptually not @emph{one} compound object is returned, but several
484distinct values.
485
486The primitive procedures for handling multiple values are @code{values}
487and @code{call-with-values}. @code{values} is used for returning
488multiple values from a procedure. This is done by placing a call to
489@code{values} with zero or more arguments in tail position in a
490procedure body. @code{call-with-values} combines a procedure returning
491multiple values with a procedure which accepts these values as
492parameters.
493
494@rnindex values
495@deffn {Scheme Procedure} values arg1 @dots{} argN
496@deffnx {C Function} scm_values (args)
497Delivers all of its arguments to its continuation. Except for
498continuations created by the @code{call-with-values} procedure,
499all continuations take exactly one value. The effect of
500passing no value or more than one value to continuations that
501were not created by @code{call-with-values} is unspecified.
502
503For @code{scm_values}, @var{args} is a list of arguments and the
504return is a multiple-values object which the caller can return. In
505the current implementation that object shares structure with
506@var{args}, so @var{args} should not be modified subsequently.
507@end deffn
508
509@rnindex call-with-values
510@deffn {Scheme Procedure} call-with-values producer consumer
511Calls its @var{producer} argument with no values and a
512continuation that, when passed some values, calls the
513@var{consumer} procedure with those values as arguments. The
514continuation for the call to @var{consumer} is the continuation
515of the call to @code{call-with-values}.
516
517@example
518(call-with-values (lambda () (values 4 5))
519 (lambda (a b) b))
520@result{} 5
521
522@end example
523@example
524(call-with-values * -)
525@result{} -1
526@end example
527@end deffn
528
529In addition to the fundamental procedures described above, Guile has a
530module which exports a syntax called @code{receive}, which is much more
531convenient. If you want to use it in your programs, you have to load
532the module @code{(ice-9 receive)} with the statement
533
534@lisp
535(use-modules (ice-9 receive))
536@end lisp
537
538@deffn {library syntax} receive formals expr body @dots{}
539Evaluate the expression @var{expr}, and bind the result values (zero or
540more) to the formal arguments in the formal argument list @var{formals}.
541@var{formals} must have the same syntax like the formal argument list
542used in @code{lambda} (@pxref{Lambda}). After binding the variables,
543the expressions in @var{body} @dots{} are evaluated in order.
544@end deffn
545
546
547@node Exceptions
548@subsection Exceptions
549@cindex error handling
550@cindex exception handling
551
552A common requirement in applications is to want to jump
553@dfn{non-locally} from the depths of a computation back to, say, the
554application's main processing loop. Usually, the place that is the
555target of the jump is somewhere in the calling stack of procedures that
556called the procedure that wants to jump back. For example, typical
557logic for a key press driven application might look something like this:
558
559@example
560main-loop:
561 read the next key press and call dispatch-key
562
563dispatch-key:
564 lookup the key in a keymap and call an appropriate procedure,
565 say find-file
566
567find-file:
568 interactively read the required file name, then call
569 find-specified-file
570
571find-specified-file:
572 check whether file exists; if not, jump back to main-loop
573 @dots{}
574@end example
575
576The jump back to @code{main-loop} could be achieved by returning through
577the stack one procedure at a time, using the return value of each
578procedure to indicate the error condition, but Guile (like most modern
579programming languages) provides an additional mechanism called
580@dfn{exception handling} that can be used to implement such jumps much
581more conveniently.
582
583@menu
584* Exception Terminology:: Different ways to say the same thing.
585* Catch:: Setting up to catch exceptions.
586* Throw:: Throwing an exception.
587* Lazy Catch:: Catch without unwinding the stack.
588* Exception Implementation:: How Guile implements exceptions.
589@end menu
590
591
592@node Exception Terminology
593@subsubsection Exception Terminology
594
595There are several variations on the terminology for dealing with
596non-local jumps. It is useful to be aware of them, and to realize
597that they all refer to the same basic mechanism.
598
599@itemize @bullet
600@item
601Actually making a non-local jump may be called @dfn{raising an
602exception}, @dfn{raising a signal}, @dfn{throwing an exception} or
603@dfn{doing a long jump}. When the jump indicates an error condition,
604people may talk about @dfn{signalling}, @dfn{raising} or @dfn{throwing}
605@dfn{an error}.
606
607@item
608Handling the jump at its target may be referred to as @dfn{catching} or
609@dfn{handling} the @dfn{exception}, @dfn{signal} or, where an error
610condition is involved, @dfn{error}.
611@end itemize
612
613Where @dfn{signal} and @dfn{signalling} are used, special care is needed
614to avoid the risk of confusion with POSIX signals.
615
616This manual prefers to speak of throwing and catching exceptions, since
617this terminology matches the corresponding Guile primitives.
618
619
620@node Catch
621@subsubsection Catching Exceptions
622
623@code{catch} is used to set up a target for a possible non-local jump.
624The arguments of a @code{catch} expression are a @dfn{key}, which
625restricts the set of exceptions to which this @code{catch} applies, a
626thunk that specifies the code to execute and a @dfn{handler} procedure
627that says what to do if an exception is thrown while executing the code.
628Note that if the execution thunk executes @dfn{normally}, which means
629without throwing any exceptions, the handler procedure is not called at
630all.
631
632When an exception is thrown using the @code{throw} function, the first
633argument of the @code{throw} is a symbol that indicates the type of the
634exception. For example, Guile throws an exception using the symbol
635@code{numerical-overflow} to indicate numerical overflow errors such as
636division by zero:
637
638@lisp
639(/ 1 0)
640@result{}
641ABORT: (numerical-overflow)
642@end lisp
643
644The @var{key} argument in a @code{catch} expression corresponds to this
645symbol. @var{key} may be a specific symbol, such as
646@code{numerical-overflow}, in which case the @code{catch} applies
647specifically to exceptions of that type; or it may be @code{#t}, which
648means that the @code{catch} applies to all exceptions, irrespective of
649their type.
650
651The second argument of a @code{catch} expression should be a thunk
652(i.e. a procedure that accepts no arguments) that specifies the normal
653case code. The @code{catch} is active for the execution of this thunk,
654including any code called directly or indirectly by the thunk's body.
655Evaluation of the @code{catch} expression activates the catch and then
656calls this thunk.
657
658The third argument of a @code{catch} expression is a handler procedure.
659If an exception is thrown, this procedure is called with exactly the
660arguments specified by the @code{throw}. Therefore, the handler
661procedure must be designed to accept a number of arguments that
662corresponds to the number of arguments in all @code{throw} expressions
663that can be caught by this @code{catch}.
664
665@deffn {Scheme Procedure} catch key thunk handler
666@deffnx {C Function} scm_catch (key, thunk, handler)
667Invoke @var{thunk} in the dynamic context of @var{handler} for
668exceptions matching @var{key}. If thunk throws to the symbol
669@var{key}, then @var{handler} is invoked this way:
670@lisp
671(handler key args ...)
672@end lisp
673
674@var{key} is a symbol or @code{#t}.
675
676@var{thunk} takes no arguments. If @var{thunk} returns
677normally, that is the return value of @code{catch}.
678
679Handler is invoked outside the scope of its own @code{catch}.
680If @var{handler} again throws to the same key, a new handler
681from further up the call chain is invoked.
682
683If the key is @code{#t}, then a throw to @emph{any} symbol will
684match this call to @code{catch}.
685@end deffn
686
687If the handler procedure needs to match a variety of @code{throw}
688expressions with varying numbers of arguments, you should write it like
689this:
690
691@lisp
692(lambda (key . args)
693 @dots{})
694@end lisp
695
696@noindent
697The @var{key} argument is guaranteed always to be present, because a
698@code{throw} without a @var{key} is not valid. The number and
699interpretation of the @var{args} varies from one type of exception to
700another, but should be specified by the documentation for each exception
701type.
702
703Note that, once the handler procedure is invoked, the catch that led to
704the handler procedure being called is no longer active. Therefore, if
705the handler procedure itself throws an exception, that exception can
706only be caught by another active catch higher up the call stack, if
707there is one.
708
709@sp 1
710@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)
711The above @code{scm_catch} takes Scheme procedures as body and handler
712arguments. @code{scm_internal_catch} is an equivalent taking C
713functions.
714
715@var{body} is called as @code{@var{body} (@var{body_data})} with a
716catch on exceptions of the given @var{tag} type. If an exception is
717caught, @var{handler} is called @code{@var{handler}
718(@var{handler_data}, @var{key}, @var{args})}. @var{key} and
719@var{args} are the @code{SCM} key and argument list from the
720@code{throw}.
721
722@tpindex scm_t_catch_body
723@tpindex scm_t_catch_handler
724@var{body} and @var{handler} should have the following prototypes.
725@code{scm_t_catch_body} and @code{scm_t_catch_handler} are pointer
726typedefs for these.
727
728@example
729SCM body (void *data);
730SCM handler (void *data, SCM key, SCM args);
731@end example
732
733The @var{body_data} and @var{handler_data} parameters are passed to
734the respective calls so an application can communicate extra
735information to those functions.
736
737If the data consists of an @code{SCM} object, care should be taken
738that it isn't garbage collected while still required. If the
739@code{SCM} is a local C variable, one way to protect it is to pass a
740pointer to that variable as the data parameter, since the C compiler
741will then know the value must be held on the stack. Another way is to
742use @code{scm_remember_upto_here_1} (@pxref{Remembering During
743Operations}).
744@end deftypefn
745
746
747@node Throw
748@subsubsection Throwing Exceptions
749
750The @code{throw} primitive is used to throw an exception. One argument,
751the @var{key}, is mandatory, and must be a symbol; it indicates the type
752of exception that is being thrown. Following the @var{key},
753@code{throw} accepts any number of additional arguments, whose meaning
754depends on the exception type. The documentation for each possible type
755of exception should specify the additional arguments that are expected
756for that kind of exception.
757
758@deffn {Scheme Procedure} throw key . args
759@deffnx {C Function} scm_throw (key, args)
760Invoke the catch form matching @var{key}, passing @var{args} to the
761@var{handler}.
762
763@var{key} is a symbol. It will match catches of the same symbol or of
764@code{#t}.
765
766If there is no handler at all, Guile prints an error and then exits.
767@end deffn
768
769When an exception is thrown, it will be caught by the innermost
770@code{catch} expression that applies to the type of the thrown
771exception; in other words, the innermost @code{catch} whose @var{key} is
772@code{#t} or is the same symbol as that used in the @code{throw}
773expression. Once Guile has identified the appropriate @code{catch}, it
774handles the exception by applying that @code{catch} expression's handler
775procedure to the arguments of the @code{throw}.
776
777If there is no appropriate @code{catch} for a thrown exception, Guile
778prints an error to the current error port indicating an uncaught
779exception, and then exits. In practice, it is quite difficult to
780observe this behaviour, because Guile when used interactively installs a
781top level @code{catch} handler that will catch all exceptions and print
782an appropriate error message @emph{without} exiting. For example, this
783is what happens if you try to throw an unhandled exception in the
784standard Guile REPL; note that Guile's command loop continues after the
785error message:
786
787@lisp
788guile> (throw 'badex)
789<unnamed port>:3:1: In procedure gsubr-apply @dots{}
790<unnamed port>:3:1: unhandled-exception: badex
791ABORT: (misc-error)
792guile>
793@end lisp
794
795The default uncaught exception behaviour can be observed by evaluating a
796@code{throw} expression from the shell command line:
797
798@example
799$ guile -c "(begin (throw 'badex) (display \"here\\n\"))"
800guile: uncaught throw to badex: ()
801$
802@end example
803
804@noindent
805That Guile exits immediately following the uncaught exception
806is shown by the absence of any output from the @code{display}
807expression, because Guile never gets to the point of evaluating that
808expression.
809
810
811@node Lazy Catch
812@subsubsection Catch Without Unwinding
813
814A @dfn{lazy catch} is used in the same way as a normal @code{catch},
815with @var{key}, @var{thunk} and @var{handler} arguments specifying the
816exception type, normal case code and handler procedure, but differs in
817one important respect: the handler procedure is executed without
818unwinding the call stack from the context of the @code{throw} expression
819that caused the handler to be invoked.
820
821@deffn {Scheme Procedure} lazy-catch key thunk handler
822@deffnx {C Function} scm_lazy_catch (key, thunk, handler)
823This behaves exactly like @code{catch}, except that it does
824not unwind the stack before invoking @var{handler}.
825The @var{handler} procedure is not allowed to return:
826it must throw to another catch, or otherwise exit non-locally.
827@end deffn
828
829@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)
830The above @code{scm_lazy_catch} takes Scheme procedures as body and
831handler arguments. @code{scm_internal_lazy_catch} is an equivalent
832taking C functions. See @code{scm_internal_catch} (@pxref{Catch}) for
833a description of the parameters, the behaviour however of course
834follows @code{lazy-catch}.
835@end deftypefn
836
837Typically, @var{handler} should save any desired state associated with
838the stack at the point where the corresponding @code{throw} occurred,
839and then throw an exception itself --- usually the same exception as the
840one it caught. If @var{handler} is invoked and does @emph{not} throw an
841exception, Guile itself throws an exception with key @code{misc-error}.
842
843Not unwinding the stack means that throwing an exception that is caught
844by a @code{lazy-catch} is @emph{almost} equivalent to calling the
845@code{lazy-catch}'s handler inline instead of each @code{throw}, and
846then omitting the surrounding @code{lazy-catch}. In other words,
847
848@lisp
849(lazy-catch 'key
850 (lambda () @dots{} (throw 'key args @dots{}) @dots{})
851 handler)
852@end lisp
853
854@noindent
855is @emph{almost} equivalent to
856
857@lisp
858((lambda () @dots{} (handler 'key args @dots{}) @dots{}))
859@end lisp
860
861@noindent
862But why only @emph{almost}? The difference is that with
863@code{lazy-catch} (as with normal @code{catch}), the dynamic context is
864unwound back to just outside the @code{lazy-catch} expression before
865invoking the handler. (For an introduction to what is meant by dynamic
866context, @xref{Dynamic Wind}.)
867
868Then, when the handler @emph{itself} throws an exception, that exception
869must be caught by some kind of @code{catch} (including perhaps another
870@code{lazy-catch}) higher up the call stack.
871
872The dynamic context also includes @code{with-fluids} blocks (REFFIXME),
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
969should be a list containing the Unix signal number; otherwise
970it will usually be @code{#f}.
971@end deffn
972
973@deffn {Scheme Procedure} strerror err
974@deffnx {C Function} scm_strerror (err)
975Return the Unix error message corresponding to @var{err}, which
976must be an integer value.
977@end deffn
978
979@c begin (scm-doc-string "boot-9.scm" "false-if-exception")
980@deffn syntax false-if-exception expr
981Returns the result of evaluating its argument; however
982if an exception occurs then @code{#f} is returned instead.
983@end deffn
984@c end
985
986
987@node Dynamic Wind
988@subsection Dynamic Wind
989
990@rnindex dynamic-wind
991@deffn {Scheme Procedure} dynamic-wind in_guard thunk out_guard
992@deffnx {C Function} scm_dynamic_wind (in_guard, thunk, out_guard)
993All three arguments must be 0-argument procedures.
994@var{in_guard} is called, then @var{thunk}, then
995@var{out_guard}.
996
997If, any time during the execution of @var{thunk}, the
998dynamic extent of the @code{dynamic-wind} expression is escaped
999non-locally, @var{out_guard} is called. If the dynamic extent of
1000the dynamic-wind is re-entered, @var{in_guard} is called. Thus
1001@var{in_guard} and @var{out_guard} may be called any number of
1002times.
1003@lisp
1004(define x 'normal-binding)
1005@result{} x
1006(define a-cont (call-with-current-continuation
1007 (lambda (escape)
1008 (let ((old-x x))
1009 (dynamic-wind
1010 ;; in-guard:
1011 ;;
1012 (lambda () (set! x 'special-binding))
1013
1014 ;; thunk
1015 ;;
1016 (lambda () (display x) (newline)
1017 (call-with-current-continuation escape)
1018 (display x) (newline)
1019 x)
1020
1021 ;; out-guard:
1022 ;;
1023 (lambda () (set! x old-x)))))))
1024
1025;; Prints:
1026special-binding
1027;; Evaluates to:
1028@result{} a-cont
1029x
1030@result{} normal-binding
1031(a-cont #f)
1032;; Prints:
1033special-binding
1034;; Evaluates to:
1035@result{} a-cont ;; the value of the (define a-cont...)
1036x
1037@result{} normal-binding
1038a-cont
1039@result{} special-binding
1040@end lisp
1041@end deffn
1042
1043@node Frames
1044@subsection Frames
1045
1046For Scheme code, the fundamental procedure to react to non-local entry
1047and exits of dynamic contexts is @code{dynamic-wind}. C code could use
1048@code{scm_internal_dynamic_wind}, but since C does not allow the
1049convenient construction of anonymous procedures that close over lexical
1050variables, this will be, well, inconvenient. Instead, C code can use
1051@dfn{frames}.
1052
1053Guile offers the functions @code{scm_frame_begin} and
1054@code{scm_frame_end} to delimit a dynamic extent. Within this dynamic
1055extent, which is called a @dfn{frame}, you can perform various
1056@dfn{frame actions} that control what happens when the frame is entered
1057or left. For example, you can register a cleanup routine with
1058@code{scm_frame_unwind} that is executed when the frame is left. There are
1059several other more specialized frame actions as well, for example to
1060temporarily block the execution of asyncs or to temporarily change the
1061current output port. They are described elsewhere in this manual.
1062
1063Here is an example that shows how to prevent memory leaks.
1064
1065@example
1066
1067/* Suppose there is a function called FOO in some library that you
1068 would like to make available to Scheme code (or to C code that
1069 follows the Scheme conventions).
1070
1071 FOO takes two C strings and returns a new string. When an error has
1072 occurred in FOO, it returns NULL.
1073*/
1074
1075char *foo (char *s1, char *s2);
1076
1077/* SCM_FOO interfaces the C function FOO to the Scheme way of life.
1078 It takes care to free up all temporary strings in the case of
1079 non-local exits.
07d83abe
MV
1080 */
1081
07d83abe
MV
1082SCM
1083scm_foo (SCM s1, SCM s2)
1084@{
1085 char *c_s1, *c_s2, *c_res;
1086
1087 scm_frame_begin (0);
1088
27316760
MV
1089 c_s1 = scm_to_locale_string (s1);
1090
1091 /* Call 'free (c_s1)' when the frame is left.
1092 */
07d83abe
MV
1093 scm_frame_unwind_handler (free, c_s1, SCM_F_WIND_EXPLICITLY);
1094
27316760
MV
1095 c_s2 = scm_to_locale_string (s2);
1096
1097 /* Same as above, but more concisely.
1098 */
1099 scm_frame_free (c_s2);
07d83abe
MV
1100
1101 c_res = foo (c_s1, c_s2);
1102 if (c_res == NULL)
1103 scm_memory_error ("foo");
1104
1105 scm_frame_end ();
1106
27316760 1107 return scm_take_locale_string (res);
07d83abe
MV
1108@}
1109@end example
1110
1111@deftp {C Type} scm_t_frame_flags
1112This is an enumeration of several flags that modify the behavior of
1113@code{scm_begin_frame}. The flags are listed in the following table.
1114
1115@table @code
1116@item SCM_F_FRAME_REWINDABLE
1117The frame is @dfn{rewindable}. This means that it can be reentered
1118non-locally (via the invokation of a continuation). The default is that
1119a frame can not be reentered non-locally.
1120@end table
1121
1122@end deftp
1123
1124@deftypefn {C Function} void scm_frame_begin (scm_t_frame_flags flags)
1125The function @code{scm_begin_frame} starts a new frame and makes it the
1126`current' one.
1127
1128The @var{flags} argument determines the default behavior of the frame.
1129For normal frames, use 0. This will result in a frame that can not be
1130reentered with a captured continuation. When you are prepared to handle
1131reentries, include @code{SCM_F_FRAME_REWINDABLE} in @var{flags}.
1132
1133Being prepared for reentry means that the effects of unwind handlers
1134can be undone on reentry. In the example above, we want to prevent a
1135memory leak on non-local exit and thus register an unwind handler that
1136frees the memory. But once the memory is freed, we can not get it
1137back on reentry. Thus reentry can not be allowed.
1138
1139The consequence is that continuations become less useful when
1140non-reenterable frames are captured, but you don't need to worry about
1141that too much.
1142
1143The frame is ended either implicitly when a non-local exit happens, or
1144explicitly with @code{scm_end_frame}. You must make sure that a frame
1145is indeed ended properly. If you fail to call @code{scm_end_frame}
1146for each @code{scm_begin_frame}, the behavior is undefined.
1147@end deftypefn
1148
1149@deftypefn {C Function} void scm_frame_end ()
1150End the current frame explicitly and make the previous frame current.
1151@end deftypefn
1152
1153@deftp {C Type} scm_t_wind_flags
1154This is an enumeration of several flags that modify the behavior of
1155@code{scm_on_unwind_handler} and @code{scm_on_rewind_handler}. The
1156flags are listed in the following table.
1157
1158@table @code
1159@item SCM_F_WIND_EXPLICITLY
1160@vindex SCM_F_WIND_EXPLICITLY
1161The registered action is also carried out when the frame is entered or
1162left locally.
1163@end table
1164@end deftp
1165
1166@deftypefn {C Function} void scm_frame_unwind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
1167@deftypefnx {C Function} void scm_frame_unwind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
1168Arranges for @var{func} to be called with @var{data} as its arguments
1169when the current frame ends implicitly. If @var{flags} contains
1170@code{SCM_F_WIND_EXPLICITLY}, @var{func} is also called when the frame
1171ends explicitly with @code{scm_frame_end}.
1172
1173The function @code{scm_frame_unwind_handler_with_scm} takes care that
1174@var{data} is protected from garbage collection.
1175@end deftypefn
1176
1177@deftypefn {C Function} void scm_frame_rewind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
1178@deftypefnx {C Function} void scm_frame_rewind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
1179Arrange for @var{func} to be called with @var{data} as its argument when
1180the current frame is restarted by rewinding the stack. When @var{flags}
1181contains @code{SCM_F_WIND_EXPLICITLY}, @var{func} is called immediately
1182as well.
1183
1184The function @code{scm_frame_rewind_handler_with_scm} takes care that
1185@var{data} is protected from garbage collection.
1186@end deftypefn
1187
1188
1189@node Handling Errors
1190@subsection How to Handle Errors
1191
1192Error handling is based on @code{catch} and @code{throw}. Errors are
1193always thrown with a @var{key} and four arguments:
1194
1195@itemize @bullet
1196@item
1197@var{key}: a symbol which indicates the type of error. The symbols used
1198by libguile are listed below.
1199
1200@item
1201@var{subr}: the name of the procedure from which the error is thrown, or
1202@code{#f}.
1203
1204@item
1205@var{message}: a string (possibly language and system dependent)
1206describing the error. The tokens @code{~A} and @code{~S} can be
1207embedded within the message: they will be replaced with members of the
1208@var{args} list when the message is printed. @code{~A} indicates an
1209argument printed using @code{display}, while @code{~S} indicates an
1210argument printed using @code{write}. @var{message} can also be
1211@code{#f}, to allow it to be derived from the @var{key} by the error
1212handler (may be useful if the @var{key} is to be thrown from both C and
1213Scheme).
1214
1215@item
1216@var{args}: a list of arguments to be used to expand @code{~A} and
1217@code{~S} tokens in @var{message}. Can also be @code{#f} if no
1218arguments are required.
1219
1220@item
1221@var{rest}: a list of any additional objects required. e.g., when the
1222key is @code{'system-error}, this contains the C errno value. Can also
1223be @code{#f} if no additional objects are required.
1224@end itemize
1225
1226In addition to @code{catch} and @code{throw}, the following Scheme
1227facilities are available:
1228
1229@deffn {Scheme Procedure} display-error stack port subr message args rest
1230@deffnx {C Function} scm_display_error (stack, port, subr, message, args, rest)
1231Display an error message to the output port @var{port}.
1232@var{stack} is the saved stack for the error, @var{subr} is
1233the name of the procedure in which the error occurred and
1234@var{message} is the actual error message, which may contain
1235formatting instructions. These will format the arguments in
1236the list @var{args} accordingly. @var{rest} is currently
1237ignored.
1238@end deffn
1239
1240The following are the error keys defined by libguile and the situations
1241in which they are used:
1242
1243@itemize @bullet
1244@item
1245@cindex @code{error-signal}
1246@code{error-signal}: thrown after receiving an unhandled fatal signal
1247such as SIGSEGV, SIGBUS, SIGFPE etc. The @var{rest} argument in the throw
1248contains the coded signal number (at present this is not the same as the
1249usual Unix signal number).
1250
1251@item
1252@cindex @code{system-error}
1253@code{system-error}: thrown after the operating system indicates an
1254error condition. The @var{rest} argument in the throw contains the
1255errno value.
1256
1257@item
1258@cindex @code{numerical-overflow}
1259@code{numerical-overflow}: numerical overflow.
1260
1261@item
1262@cindex @code{out-of-range}
1263@code{out-of-range}: the arguments to a procedure do not fall within the
1264accepted domain.
1265
1266@item
1267@cindex @code{wrong-type-arg}
1268@code{wrong-type-arg}: an argument to a procedure has the wrong type.
1269
1270@item
1271@cindex @code{wrong-number-of-args}
1272@code{wrong-number-of-args}: a procedure was called with the wrong number
1273of arguments.
1274
1275@item
1276@cindex @code{memory-allocation-error}
1277@code{memory-allocation-error}: memory allocation error.
1278
1279@item
1280@cindex @code{stack-overflow}
1281@code{stack-overflow}: stack overflow error.
1282
1283@item
1284@cindex @code{regular-expression-syntax}
1285@code{regular-expression-syntax}: errors generated by the regular
1286expression library.
1287
1288@item
1289@cindex @code{misc-error}
1290@code{misc-error}: other errors.
1291@end itemize
1292
1293
1294@subsubsection C Support
1295
1296In the following C functions, @var{SUBR} and @var{MESSAGE} parameters
1297can be @code{NULL} to give the effect of @code{#f} described above.
1298
1299@deftypefn {C Function} SCM scm_error (SCM @var{key}, char *@var{subr}, char *@var{message}, SCM @var{args}, SCM @var{rest})
1300Throw an error, as per @code{scm-error} above.
1301@end deftypefn
1302
1303@deftypefn {C Function} void scm_syserror (char *@var{subr})
1304@deftypefnx {C Function} void scm_syserror_msg (char *@var{subr}, char *@var{message}, SCM @var{args})
1305Throw an error with key @code{system-error} and supply @code{errno} in
1306the @var{rest} argument. For @code{scm_syserror} the message is
1307generated using @code{strerror}.
1308
1309Care should be taken that any code in between the failing operation
1310and the call to these routines doesn't change @code{errno}.
1311@end deftypefn
1312
1313@deftypefn {C Function} void scm_num_overflow (char *@var{subr})
1314@deftypefnx {C Function} void scm_out_of_range (char *@var{subr}, SCM @var{bad_value})
1315@deftypefnx {C Function} void scm_wrong_num_args (SCM @var{proc})
1316@deftypefnx {C Function} void scm_wrong_type_arg (char *@var{subr}, int @var{argnum}, SCM @var{bad_value})
1317@deftypefnx {C Function} void scm_memory_error (char *@var{subr})
1318Throw an error with the various keys described above.
1319
1320For @code{scm_wrong_num_args}, @var{proc} should be a Scheme symbol
1321which is the name of the procedure incorrectly invoked.
1322@end deftypefn
1323
1324
1325@c Local Variables:
1326@c TeX-master: "guile.texi"
1327@c End: