api-control.texi 63 KB

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