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