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