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