api-control.texi 66 KB

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