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