api-control.texi 55 KB

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