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