api-control.texi 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878
  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,
  4. @c 2011, 2012, 2013 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}. If 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. @cindex continuation, escape
  471. One example where this optimization matters is @dfn{escape
  472. continuations}. Escape continuations are delimited continuations whose
  473. only use is to make a non-local exit---i.e., to escape from the current
  474. continuation. Such continuations are invoked only once, and for this
  475. reason they are sometimes called @dfn{one-shot continuations}. A common
  476. use of escape continuations is when throwing an exception
  477. (@pxref{Exceptions}).
  478. The constructs below are syntactic sugar atop prompts to simplify the
  479. use of escape continuations.
  480. @deffn {Scheme Procedure} call-with-escape-continuation proc
  481. @deffnx {Scheme Procedure} call/ec proc
  482. Call @var{proc} with an escape continuation.
  483. In the example below, the @var{return} continuation is used to escape
  484. the continuation of the call to @code{fold}.
  485. @lisp
  486. (use-modules (ice-9 control)
  487. (srfi srfi-1))
  488. (define (prefix x lst)
  489. ;; Return all the elements before the first occurrence
  490. ;; of X in LST.
  491. (call/ec
  492. (lambda (return)
  493. (fold (lambda (element prefix)
  494. (if (equal? element x)
  495. (return (reverse prefix)) ; escape `fold'
  496. (cons element prefix)))
  497. '()
  498. lst))))
  499. (prefix 'a '(0 1 2 a 3 4 5))
  500. @result{} (0 1 2)
  501. @end lisp
  502. @end deffn
  503. @deffn {Scheme Syntax} let-escape-continuation k body @dots{}
  504. @deffnx {Scheme Syntax} let/ec k body @dots{}
  505. Bind @var{k} within @var{body} to an escape continuation.
  506. This is equivalent to
  507. @code{(call/ec (lambda (@var{k}) @var{body} @dots{}))}.
  508. @end deffn
  509. @node Shift and Reset
  510. @subsubsection Shift, Reset, and All That
  511. There is a whole zoo of delimited control operators, and as it does not
  512. seem to be a bounded set, Guile implements support for them in a
  513. separate module:
  514. @example
  515. (use-modules (ice-9 control))
  516. @end example
  517. Firstly, we have a helpful abbreviation for the @code{call-with-prompt}
  518. operator.
  519. @deffn {Scheme Syntax} % expr
  520. @deffnx {Scheme Syntax} % expr handler
  521. @deffnx {Scheme Syntax} % tag expr handler
  522. Evaluate @var{expr} in a prompt, optionally specifying a tag and a
  523. handler. If no tag is given, the default prompt tag is used.
  524. If no handler is given, a default handler is installed. The default
  525. handler accepts a procedure of one argument, which will called on the
  526. captured continuation, within a prompt.
  527. Sometimes it's easier just to show code, as in this case:
  528. @example
  529. (define (default-prompt-handler k proc)
  530. (% (default-prompt-tag)
  531. (proc k)
  532. default-prompt-handler))
  533. @end example
  534. The @code{%} symbol is chosen because it looks like a prompt.
  535. @end deffn
  536. Likewise there is an abbreviation for @code{abort-to-prompt}, which
  537. assumes the default prompt tag:
  538. @deffn {Scheme Procedure} abort val1 val2 @dots{}
  539. Abort to the default prompt tag, passing @var{val1} @var{val2} @dots{}
  540. to the handler.
  541. @end deffn
  542. As mentioned before, @code{(ice-9 control)} also provides other
  543. delimited control operators. This section is a bit technical, and
  544. first-time users of delimited continuations should probably come back to
  545. it after some practice with @code{%}.
  546. Still here? So, when one implements a delimited control operator like
  547. @code{call-with-prompt}, one needs to make two decisions. Firstly, does
  548. the handler run within or outside the prompt? Having the handler run
  549. within the prompt allows an abort inside the handler to return to the
  550. same prompt handler, which is often useful. However it prevents tail
  551. calls from the handler, so it is less general.
  552. Similarly, does invoking a captured continuation reinstate a prompt?
  553. Again we have the tradeoff of convenience versus proper tail calls.
  554. These decisions are captured in the Felleisen @dfn{F} operator. If
  555. neither the continuations nor the handlers implicitly add a prompt, the
  556. operator is known as @dfn{--F--}. This is the case for Guile's
  557. @code{call-with-prompt} and @code{abort-to-prompt}.
  558. If both continuation and handler implicitly add prompts, then the
  559. operator is @dfn{+F+}. @code{shift} and @code{reset} are such
  560. operators.
  561. @deffn {Scheme Syntax} reset body1 body2 @dots{}
  562. Establish a prompt, and evaluate @var{body1} @var{body2} @dots{} within
  563. that prompt.
  564. The prompt handler is designed to work with @code{shift}, described
  565. below.
  566. @end deffn
  567. @deffn {Scheme Syntax} shift cont body1 body2 @dots{}
  568. Abort to the nearest @code{reset}, and evaluate @var{body1} @var{body2}
  569. @dots{} in a context in which the captured continuation is bound to
  570. @var{cont}.
  571. As mentioned above, taken together, the @var{body1} @var{body2} @dots{}
  572. expressions and the invocations of @var{cont} implicitly establish a
  573. prompt.
  574. @end deffn
  575. Interested readers are invited to explore Oleg Kiselyov's wonderful web
  576. site at @uref{http://okmij.org/ftp/}, for more information on these
  577. operators.
  578. @node Continuations
  579. @subsection Continuations
  580. @cindex continuations
  581. A ``continuation'' is the code that will execute when a given function
  582. or expression returns. For example, consider
  583. @example
  584. (define (foo)
  585. (display "hello\n")
  586. (display (bar)) (newline)
  587. (exit))
  588. @end example
  589. The continuation from the call to @code{bar} comprises a
  590. @code{display} of the value returned, a @code{newline} and an
  591. @code{exit}. This can be expressed as a function of one argument.
  592. @example
  593. (lambda (r)
  594. (display r) (newline)
  595. (exit))
  596. @end example
  597. In Scheme, continuations are represented as special procedures just
  598. like this. The special property is that when a continuation is called
  599. it abandons the current program location and jumps directly to that
  600. represented by the continuation.
  601. A continuation is like a dynamic label, capturing at run-time a point
  602. in program execution, including all the nested calls that have lead to
  603. it (or rather the code that will execute when those calls return).
  604. Continuations are created with the following functions.
  605. @deffn {Scheme Procedure} call-with-current-continuation proc
  606. @deffnx {Scheme Procedure} call/cc proc
  607. @rnindex call-with-current-continuation
  608. Capture the current continuation and call @code{(@var{proc}
  609. @var{cont})} with it. The return value is the value returned by
  610. @var{proc}, or when @code{(@var{cont} @var{value})} is later invoked,
  611. the return is the @var{value} passed.
  612. Normally @var{cont} should be called with one argument, but when the
  613. location resumed is expecting multiple values (@pxref{Multiple
  614. Values}) then they should be passed as multiple arguments, for
  615. instance @code{(@var{cont} @var{x} @var{y} @var{z})}.
  616. @var{cont} may only be used from the same side of a continuation
  617. barrier as it was created (@pxref{Continuation Barriers}), and in a
  618. multi-threaded program only from the thread in which it was created.
  619. The call to @var{proc} is not part of the continuation captured, it runs
  620. only when the continuation is created. Often a program will want to
  621. store @var{cont} somewhere for later use; this can be done in
  622. @var{proc}.
  623. The @code{call} in the name @code{call-with-current-continuation}
  624. refers to the way a call to @var{proc} gives the newly created
  625. continuation. It's not related to the way a call is used later to
  626. invoke that continuation.
  627. @code{call/cc} is an alias for @code{call-with-current-continuation}.
  628. This is in common use since the latter is rather long.
  629. @end deffn
  630. @sp 1
  631. @noindent
  632. Here is a simple example,
  633. @example
  634. (define kont #f)
  635. (format #t "the return is ~a\n"
  636. (call/cc (lambda (k)
  637. (set! kont k)
  638. 1)))
  639. @result{} the return is 1
  640. (kont 2)
  641. @result{} the return is 2
  642. @end example
  643. @code{call/cc} captures a continuation in which the value returned is
  644. going to be displayed by @code{format}. The @code{lambda} stores this
  645. in @code{kont} and gives an initial return @code{1} which is
  646. displayed. The later invocation of @code{kont} resumes the captured
  647. point, but this time returning @code{2}, which is displayed.
  648. When Guile is run interactively, a call to @code{format} like this has
  649. an implicit return back to the read-eval-print loop. @code{call/cc}
  650. captures that like any other return, which is why interactively
  651. @code{kont} will come back to read more input.
  652. @sp 1
  653. C programmers may note that @code{call/cc} is like @code{setjmp} in
  654. the way it records at runtime a point in program execution. A call to
  655. a continuation is like a @code{longjmp} in that it abandons the
  656. present location and goes to the recorded one. Like @code{longjmp},
  657. the value passed to the continuation is the value returned by
  658. @code{call/cc} on resuming there. However @code{longjmp} can only go
  659. up the program stack, but the continuation mechanism can go anywhere.
  660. When a continuation is invoked, @code{call/cc} and subsequent code
  661. effectively ``returns'' a second time. It can be confusing to imagine
  662. a function returning more times than it was called. It may help
  663. instead to think of it being stealthily re-entered and then program
  664. flow going on as normal.
  665. @code{dynamic-wind} (@pxref{Dynamic Wind}) can be used to ensure setup
  666. and cleanup code is run when a program locus is resumed or abandoned
  667. through the continuation mechanism.
  668. @sp 1
  669. Continuations are a powerful mechanism, and can be used to implement
  670. almost any sort of control structure, such as loops, coroutines, or
  671. exception handlers.
  672. However the implementation of continuations in Guile is not as
  673. efficient as one might hope, because Guile is designed to cooperate
  674. with programs written in other languages, such as C, which do not know
  675. about continuations. Basically continuations are captured by a block
  676. copy of the stack, and resumed by copying back.
  677. For this reason, continuations captured by @code{call/cc} should be used only
  678. when there is no other simple way to achieve the desired result, or when the
  679. elegance of the continuation mechanism outweighs the need for performance.
  680. Escapes upwards from loops or nested functions are generally best
  681. handled with prompts (@pxref{Prompts}). Coroutines can be
  682. efficiently implemented with cooperating threads (a thread holds a
  683. full program stack but doesn't copy it around the way continuations
  684. do).
  685. @node Multiple Values
  686. @subsection Returning and Accepting Multiple Values
  687. @cindex multiple values
  688. @cindex receive
  689. Scheme allows a procedure to return more than one value to its caller.
  690. This is quite different to other languages which only allow
  691. single-value returns. Returning multiple values is different from
  692. returning a list (or pair or vector) of values to the caller, because
  693. conceptually not @emph{one} compound object is returned, but several
  694. distinct values.
  695. The primitive procedures for handling multiple values are @code{values}
  696. and @code{call-with-values}. @code{values} is used for returning
  697. multiple values from a procedure. This is done by placing a call to
  698. @code{values} with zero or more arguments in tail position in a
  699. procedure body. @code{call-with-values} combines a procedure returning
  700. multiple values with a procedure which accepts these values as
  701. parameters.
  702. @rnindex values
  703. @deffn {Scheme Procedure} values arg @dots{}
  704. @deffnx {C Function} scm_values (args)
  705. Delivers all of its arguments to its continuation. Except for
  706. continuations created by the @code{call-with-values} procedure,
  707. all continuations take exactly one value. The effect of
  708. passing no value or more than one value to continuations that
  709. were not created by @code{call-with-values} is unspecified.
  710. For @code{scm_values}, @var{args} is a list of arguments and the
  711. return is a multiple-values object which the caller can return. In
  712. the current implementation that object shares structure with
  713. @var{args}, so @var{args} should not be modified subsequently.
  714. @end deffn
  715. @deftypefn {C Function} SCM scm_c_values (SCM *base, size_t n)
  716. @code{scm_c_values} is an alternative to @code{scm_values}. It creates
  717. a new values object, and copies into it the @var{n} values starting from
  718. @var{base}.
  719. Currently this creates a list and passes it to @code{scm_values}, but we
  720. expect that in the future we will be able to use more a efficient
  721. representation.
  722. @end deftypefn
  723. @deftypefn {C Function} size_t scm_c_nvalues (SCM obj)
  724. If @var{obj} is a multiple-values object, returns the number of values
  725. it contains. Otherwise returns 1.
  726. @end deftypefn
  727. @deftypefn {C Function} SCM scm_c_value_ref (SCM obj, size_t idx)
  728. Returns the value at the position specified by @var{idx} in
  729. @var{obj}. Note that @var{obj} will ordinarily be a
  730. multiple-values object, but it need not be. Any other object
  731. represents a single value (itself), and is handled appropriately.
  732. @end deftypefn
  733. @rnindex call-with-values
  734. @deffn {Scheme Procedure} call-with-values producer consumer
  735. Calls its @var{producer} argument with no values and a
  736. continuation that, when passed some values, calls the
  737. @var{consumer} procedure with those values as arguments. The
  738. continuation for the call to @var{consumer} is the continuation
  739. of the call to @code{call-with-values}.
  740. @example
  741. (call-with-values (lambda () (values 4 5))
  742. (lambda (a b) b))
  743. @result{} 5
  744. @end example
  745. @example
  746. (call-with-values * -)
  747. @result{} -1
  748. @end example
  749. @end deffn
  750. In addition to the fundamental procedures described above, Guile has a
  751. module which exports a syntax called @code{receive}, which is much
  752. more convenient. This is in the @code{(ice-9 receive)} and is the
  753. same as specified by SRFI-8 (@pxref{SRFI-8}).
  754. @lisp
  755. (use-modules (ice-9 receive))
  756. @end lisp
  757. @deffn {library syntax} receive formals expr body @dots{}
  758. Evaluate the expression @var{expr}, and bind the result values (zero
  759. or more) to the formal arguments in @var{formals}. @var{formals} is a
  760. list of symbols, like the argument list in a @code{lambda}
  761. (@pxref{Lambda}). After binding the variables, the expressions in
  762. @var{body} @dots{} are evaluated in order, the return value is the
  763. result from the last expression.
  764. For example getting results from @code{partition} in SRFI-1
  765. (@pxref{SRFI-1}),
  766. @example
  767. (receive (odds evens)
  768. (partition odd? '(7 4 2 8 3))
  769. (display odds)
  770. (display " and ")
  771. (display evens))
  772. @print{} (7 3) and (4 2 8)
  773. @end example
  774. @end deffn
  775. @node Exceptions
  776. @subsection Exceptions
  777. @cindex error handling
  778. @cindex exception handling
  779. A common requirement in applications is to want to jump
  780. @dfn{non-locally} from the depths of a computation back to, say, the
  781. application's main processing loop. Usually, the place that is the
  782. target of the jump is somewhere in the calling stack of procedures that
  783. called the procedure that wants to jump back. For example, typical
  784. logic for a key press driven application might look something like this:
  785. @example
  786. main-loop:
  787. read the next key press and call dispatch-key
  788. dispatch-key:
  789. lookup the key in a keymap and call an appropriate procedure,
  790. say find-file
  791. find-file:
  792. interactively read the required file name, then call
  793. find-specified-file
  794. find-specified-file:
  795. check whether file exists; if not, jump back to main-loop
  796. @dots{}
  797. @end example
  798. The jump back to @code{main-loop} could be achieved by returning through
  799. the stack one procedure at a time, using the return value of each
  800. procedure to indicate the error condition, but Guile (like most modern
  801. programming languages) provides an additional mechanism called
  802. @dfn{exception handling} that can be used to implement such jumps much
  803. more conveniently.
  804. @menu
  805. * Exception Terminology:: Different ways to say the same thing.
  806. * Catch:: Setting up to catch exceptions.
  807. * Throw Handlers:: Handling exceptions before unwinding the stack.
  808. * Throw:: Throwing an exception.
  809. * Exception Implementation:: How Guile implements exceptions.
  810. @end menu
  811. @node Exception Terminology
  812. @subsubsection Exception Terminology
  813. There are several variations on the terminology for dealing with
  814. non-local jumps. It is useful to be aware of them, and to realize
  815. that they all refer to the same basic mechanism.
  816. @itemize @bullet
  817. @item
  818. Actually making a non-local jump may be called @dfn{raising an
  819. exception}, @dfn{raising a signal}, @dfn{throwing an exception} or
  820. @dfn{doing a long jump}. When the jump indicates an error condition,
  821. people may talk about @dfn{signalling}, @dfn{raising} or @dfn{throwing}
  822. @dfn{an error}.
  823. @item
  824. Handling the jump at its target may be referred to as @dfn{catching} or
  825. @dfn{handling} the @dfn{exception}, @dfn{signal} or, where an error
  826. condition is involved, @dfn{error}.
  827. @end itemize
  828. Where @dfn{signal} and @dfn{signalling} are used, special care is needed
  829. to avoid the risk of confusion with POSIX signals.
  830. This manual prefers to speak of throwing and catching exceptions, since
  831. this terminology matches the corresponding Guile primitives.
  832. The exception mechanism described in this section has connections with
  833. @dfn{delimited continuations} (@pxref{Prompts}). In particular,
  834. throwing an exception is akin to invoking an @dfn{escape continuation}
  835. (@pxref{Prompt Primitives, @code{call/ec}}).
  836. @node Catch
  837. @subsubsection Catching Exceptions
  838. @code{catch} is used to set up a target for a possible non-local jump.
  839. The arguments of a @code{catch} expression are a @dfn{key}, which
  840. restricts the set of exceptions to which this @code{catch} applies, a
  841. thunk that specifies the code to execute and one or two @dfn{handler}
  842. procedures that say what to do if an exception is thrown while executing
  843. the code. If the execution thunk executes @dfn{normally}, which means
  844. without throwing any exceptions, the handler procedures are not called
  845. at all.
  846. When an exception is thrown using the @code{throw} function, the first
  847. argument of the @code{throw} is a symbol that indicates the type of the
  848. exception. For example, Guile throws an exception using the symbol
  849. @code{numerical-overflow} to indicate numerical overflow errors such as
  850. division by zero:
  851. @lisp
  852. (/ 1 0)
  853. @result{}
  854. ABORT: (numerical-overflow)
  855. @end lisp
  856. The @var{key} argument in a @code{catch} expression corresponds to this
  857. symbol. @var{key} may be a specific symbol, such as
  858. @code{numerical-overflow}, in which case the @code{catch} applies
  859. specifically to exceptions of that type; or it may be @code{#t}, which
  860. means that the @code{catch} applies to all exceptions, irrespective of
  861. their type.
  862. The second argument of a @code{catch} expression should be a thunk
  863. (i.e.@: a procedure that accepts no arguments) that specifies the normal
  864. case code. The @code{catch} is active for the execution of this thunk,
  865. including any code called directly or indirectly by the thunk's body.
  866. Evaluation of the @code{catch} expression activates the catch and then
  867. calls this thunk.
  868. The third argument of a @code{catch} expression is a handler procedure.
  869. If an exception is thrown, this procedure is called with exactly the
  870. arguments specified by the @code{throw}. Therefore, the handler
  871. procedure must be designed to accept a number of arguments that
  872. corresponds to the number of arguments in all @code{throw} expressions
  873. that can be caught by this @code{catch}.
  874. The fourth, optional argument of a @code{catch} expression is another
  875. handler procedure, called the @dfn{pre-unwind} handler. It differs from
  876. the third argument in that if an exception is thrown, it is called,
  877. @emph{before} the third argument handler, in exactly the dynamic context
  878. of the @code{throw} expression that threw the exception. This means
  879. that it is useful for capturing or displaying the stack at the point of
  880. the @code{throw}, or for examining other aspects of the dynamic context,
  881. such as fluid values, before the context is unwound back to that of the
  882. prevailing @code{catch}.
  883. @deffn {Scheme Procedure} catch key thunk handler [pre-unwind-handler]
  884. @deffnx {C Function} scm_catch_with_pre_unwind_handler (key, thunk, handler, pre_unwind_handler)
  885. @deffnx {C Function} scm_catch (key, thunk, handler)
  886. Invoke @var{thunk} in the dynamic context of @var{handler} for
  887. exceptions matching @var{key}. If thunk throws to the symbol
  888. @var{key}, then @var{handler} is invoked this way:
  889. @lisp
  890. (handler key args ...)
  891. @end lisp
  892. @var{key} is a symbol or @code{#t}.
  893. @var{thunk} takes no arguments. If @var{thunk} returns
  894. normally, that is the return value of @code{catch}.
  895. Handler is invoked outside the scope of its own @code{catch}.
  896. If @var{handler} again throws to the same key, a new handler
  897. from further up the call chain is invoked.
  898. If the key is @code{#t}, then a throw to @emph{any} symbol will
  899. match this call to @code{catch}.
  900. If a @var{pre-unwind-handler} is given and @var{thunk} throws
  901. an exception that matches @var{key}, Guile calls the
  902. @var{pre-unwind-handler} before unwinding the dynamic state and
  903. invoking the main @var{handler}. @var{pre-unwind-handler} should
  904. be a procedure with the same signature as @var{handler}, that
  905. is @code{(lambda (key . args))}. It is typically used to save
  906. the stack at the point where the exception occurred, but can also
  907. query other parts of the dynamic state at that point, such as
  908. fluid values.
  909. A @var{pre-unwind-handler} can exit either normally or non-locally.
  910. If it exits normally, Guile unwinds the stack and dynamic context
  911. and then calls the normal (third argument) handler. If it exits
  912. non-locally, that exit determines the continuation.
  913. @end deffn
  914. If a handler procedure needs to match a variety of @code{throw}
  915. expressions with varying numbers of arguments, you should write it like
  916. this:
  917. @lisp
  918. (lambda (key . args)
  919. @dots{})
  920. @end lisp
  921. @noindent
  922. The @var{key} argument is guaranteed always to be present, because a
  923. @code{throw} without a @var{key} is not valid. The number and
  924. interpretation of the @var{args} varies from one type of exception to
  925. another, but should be specified by the documentation for each exception
  926. type.
  927. Note that, once the normal (post-unwind) handler procedure is invoked,
  928. the catch that led to the handler procedure being called is no longer
  929. active. Therefore, if the handler procedure itself throws an exception,
  930. that exception can only be caught by another active catch higher up the
  931. call stack, if there is one.
  932. @sp 1
  933. @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)
  934. @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)
  935. The above @code{scm_catch_with_pre_unwind_handler} and @code{scm_catch}
  936. take Scheme procedures as body and handler arguments.
  937. @code{scm_c_catch} and @code{scm_internal_catch} are equivalents taking
  938. C functions.
  939. @var{body} is called as @code{@var{body} (@var{body_data})} with a catch
  940. on exceptions of the given @var{tag} type. If an exception is caught,
  941. @var{pre_unwind_handler} and @var{handler} are called as
  942. @code{@var{handler} (@var{handler_data}, @var{key}, @var{args})}.
  943. @var{key} and @var{args} are the @code{SCM} key and argument list from
  944. the @code{throw}.
  945. @tpindex scm_t_catch_body
  946. @tpindex scm_t_catch_handler
  947. @var{body} and @var{handler} should have the following prototypes.
  948. @code{scm_t_catch_body} and @code{scm_t_catch_handler} are pointer
  949. typedefs for these.
  950. @example
  951. SCM body (void *data);
  952. SCM handler (void *data, SCM key, SCM args);
  953. @end example
  954. The @var{body_data} and @var{handler_data} parameters are passed to
  955. the respective calls so an application can communicate extra
  956. information to those functions.
  957. If the data consists of an @code{SCM} object, care should be taken
  958. that it isn't garbage collected while still required. If the
  959. @code{SCM} is a local C variable, one way to protect it is to pass a
  960. pointer to that variable as the data parameter, since the C compiler
  961. will then know the value must be held on the stack. Another way is to
  962. use @code{scm_remember_upto_here_1} (@pxref{Remembering During
  963. Operations}).
  964. @end deftypefn
  965. @node Throw Handlers
  966. @subsubsection Throw Handlers
  967. It's sometimes useful to be able to intercept an exception that is being
  968. thrown before the stack is unwound. This could be to clean up some
  969. related state, to print a backtrace, or to pass information about the
  970. exception to a debugger, for example. The @code{with-throw-handler}
  971. procedure provides a way to do this.
  972. @deffn {Scheme Procedure} with-throw-handler key thunk handler
  973. @deffnx {C Function} scm_with_throw_handler (key, thunk, handler)
  974. Add @var{handler} to the dynamic context as a throw handler
  975. for key @var{key}, then invoke @var{thunk}.
  976. This behaves exactly like @code{catch}, except that it does not unwind
  977. the stack before invoking @var{handler}. If the @var{handler} procedure
  978. returns normally, Guile rethrows the same exception again to the next
  979. innermost catch or throw handler. @var{handler} may exit nonlocally, of
  980. course, via an explicit throw or via invoking a continuation.
  981. @end deffn
  982. Typically @var{handler} is used to display a backtrace of the stack at
  983. the point where the corresponding @code{throw} occurred, or to save off
  984. this information for possible display later.
  985. Not unwinding the stack means that throwing an exception that is handled
  986. via a throw handler is equivalent to calling the throw handler handler
  987. inline instead of each @code{throw}, and then omitting the surrounding
  988. @code{with-throw-handler}. In other words,
  989. @lisp
  990. (with-throw-handler 'key
  991. (lambda () @dots{} (throw 'key args @dots{}) @dots{})
  992. handler)
  993. @end lisp
  994. @noindent
  995. is mostly equivalent to
  996. @lisp
  997. ((lambda () @dots{} (handler 'key args @dots{}) @dots{}))
  998. @end lisp
  999. In particular, the dynamic context when @var{handler} is invoked is that
  1000. of the site where @code{throw} is called. The examples are not quite
  1001. equivalent, because the body of a @code{with-throw-handler} is not in
  1002. tail position with respect to the @code{with-throw-handler}, and if
  1003. @var{handler} exits normally, Guile arranges to rethrow the error, but
  1004. hopefully the intention is clear. (For an introduction to what is meant
  1005. by dynamic context, @xref{Dynamic Wind}.)
  1006. @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)
  1007. The above @code{scm_with_throw_handler} takes Scheme procedures as body
  1008. (thunk) and handler arguments. @code{scm_c_with_throw_handler} is an
  1009. equivalent taking C functions. See @code{scm_c_catch} (@pxref{Catch})
  1010. for a description of the parameters, the behaviour however of course
  1011. follows @code{with-throw-handler}.
  1012. @end deftypefn
  1013. If @var{thunk} throws an exception, Guile handles that exception by
  1014. invoking the innermost @code{catch} or throw handler whose key matches
  1015. that of the exception. When the innermost thing is a throw handler,
  1016. Guile calls the specified handler procedure using @code{(apply
  1017. @var{handler} key args)}. The handler procedure may either return
  1018. normally or exit non-locally. If it returns normally, Guile passes the
  1019. exception on to the next innermost @code{catch} or throw handler. If it
  1020. exits non-locally, that exit determines the continuation.
  1021. The behaviour of a throw handler is very similar to that of a
  1022. @code{catch} expression's optional pre-unwind handler. In particular, a
  1023. throw handler's handler procedure is invoked in the exact dynamic
  1024. context of the @code{throw} expression, just as a pre-unwind handler is.
  1025. @code{with-throw-handler} may be seen as a half-@code{catch}: it does
  1026. everything that a @code{catch} would do until the point where
  1027. @code{catch} would start unwinding the stack and dynamic context, but
  1028. then it rethrows to the next innermost @code{catch} or throw handler
  1029. instead.
  1030. Note also that since the dynamic context is not unwound, if a
  1031. @code{with-throw-handler} handler throws to a key that does not match
  1032. the @code{with-throw-handler} expression's @var{key}, the new throw may
  1033. be handled by a @code{catch} or throw handler that is @emph{closer} to
  1034. the throw than the first @code{with-throw-handler}.
  1035. Here is an example to illustrate this behavior:
  1036. @lisp
  1037. (catch 'a
  1038. (lambda ()
  1039. (with-throw-handler 'b
  1040. (lambda ()
  1041. (catch 'a
  1042. (lambda ()
  1043. (throw 'b))
  1044. inner-handler))
  1045. (lambda (key . args)
  1046. (throw 'a))))
  1047. outer-handler)
  1048. @end lisp
  1049. @noindent
  1050. This code will call @code{inner-handler} and then continue with the
  1051. continuation of the inner @code{catch}.
  1052. @node Throw
  1053. @subsubsection Throwing Exceptions
  1054. The @code{throw} primitive is used to throw an exception. One argument,
  1055. the @var{key}, is mandatory, and must be a symbol; it indicates the type
  1056. of exception that is being thrown. Following the @var{key},
  1057. @code{throw} accepts any number of additional arguments, whose meaning
  1058. depends on the exception type. The documentation for each possible type
  1059. of exception should specify the additional arguments that are expected
  1060. for that kind of exception.
  1061. @deffn {Scheme Procedure} throw key arg @dots{}
  1062. @deffnx {C Function} scm_throw (key, args)
  1063. Invoke the catch form matching @var{key}, passing @var{arg} @dots{} to
  1064. the @var{handler}.
  1065. @var{key} is a symbol. It will match catches of the same symbol or of
  1066. @code{#t}.
  1067. If there is no handler at all, Guile prints an error and then exits.
  1068. @end deffn
  1069. When an exception is thrown, it will be caught by the innermost
  1070. @code{catch} or throw handler that applies to the type of the thrown
  1071. exception; in other words, whose @var{key} is either @code{#t} or the
  1072. same symbol as that used in the @code{throw} expression. Once Guile has
  1073. identified the appropriate @code{catch} or throw handler, it handles the
  1074. exception by applying the relevant handler procedure(s) to the arguments
  1075. of the @code{throw}.
  1076. If there is no appropriate @code{catch} or throw handler for a thrown
  1077. exception, Guile prints an error to the current error port indicating an
  1078. uncaught exception, and then exits. In practice, it is quite difficult
  1079. to observe this behaviour, because Guile when used interactively
  1080. installs a top level @code{catch} handler that will catch all exceptions
  1081. and print an appropriate error message @emph{without} exiting. For
  1082. example, this is what happens if you try to throw an unhandled exception
  1083. in the standard Guile REPL; note that Guile's command loop continues
  1084. after the error message:
  1085. @lisp
  1086. guile> (throw 'badex)
  1087. <unnamed port>:3:1: In procedure gsubr-apply @dots{}
  1088. <unnamed port>:3:1: unhandled-exception: badex
  1089. ABORT: (misc-error)
  1090. guile>
  1091. @end lisp
  1092. The default uncaught exception behaviour can be observed by evaluating a
  1093. @code{throw} expression from the shell command line:
  1094. @example
  1095. $ guile -c "(begin (throw 'badex) (display \"here\\n\"))"
  1096. guile: uncaught throw to badex: ()
  1097. $
  1098. @end example
  1099. @noindent
  1100. That Guile exits immediately following the uncaught exception
  1101. is shown by the absence of any output from the @code{display}
  1102. expression, because Guile never gets to the point of evaluating that
  1103. expression.
  1104. @node Exception Implementation
  1105. @subsubsection How Guile Implements Exceptions
  1106. It is traditional in Scheme to implement exception systems using
  1107. @code{call-with-current-continuation}. Continuations
  1108. (@pxref{Continuations}) are such a powerful concept that any other
  1109. control mechanism --- including @code{catch} and @code{throw} --- can be
  1110. implemented in terms of them.
  1111. Guile does not implement @code{catch} and @code{throw} like this,
  1112. though. Why not? Because Guile is specifically designed to be easy to
  1113. integrate with applications written in C. In a mixed Scheme/C
  1114. environment, the concept of @dfn{continuation} must logically include
  1115. ``what happens next'' in the C parts of the application as well as the
  1116. Scheme parts, and it turns out that the only reasonable way of
  1117. implementing continuations like this is to save and restore the complete
  1118. C stack.
  1119. So Guile's implementation of @code{call-with-current-continuation} is a
  1120. stack copying one. This allows it to interact well with ordinary C
  1121. code, but means that creating and calling a continuation is slowed down
  1122. by the time that it takes to copy the C stack.
  1123. The more targeted mechanism provided by @code{catch} and @code{throw}
  1124. does not need to save and restore the C stack because the @code{throw}
  1125. always jumps to a location higher up the stack of the code that executes
  1126. the @code{throw}. Therefore Guile implements the @code{catch} and
  1127. @code{throw} primitives independently of
  1128. @code{call-with-current-continuation}, in a way that takes advantage of
  1129. this @emph{upwards only} nature of exceptions.
  1130. @node Error Reporting
  1131. @subsection Procedures for Signaling Errors
  1132. Guile provides a set of convenience procedures for signaling error
  1133. conditions that are implemented on top of the exception primitives just
  1134. described.
  1135. @deffn {Scheme Procedure} error msg arg @dots{}
  1136. Raise an error with key @code{misc-error} and a message constructed by
  1137. displaying @var{msg} and writing @var{arg} @enddots{}.
  1138. @end deffn
  1139. @deffn {Scheme Procedure} scm-error key subr message args data
  1140. @deffnx {C Function} scm_error_scm (key, subr, message, args, data)
  1141. Raise an error with key @var{key}. @var{subr} can be a string
  1142. naming the procedure associated with the error, or @code{#f}.
  1143. @var{message} is the error message string, possibly containing
  1144. @code{~S} and @code{~A} escapes. When an error is reported,
  1145. these are replaced by formatting the corresponding members of
  1146. @var{args}: @code{~A} (was @code{%s} in older versions of
  1147. Guile) formats using @code{display} and @code{~S} (was
  1148. @code{%S}) formats using @code{write}. @var{data} is a list or
  1149. @code{#f} depending on @var{key}: if @var{key} is
  1150. @code{system-error} then it should be a list containing the
  1151. Unix @code{errno} value; If @var{key} is @code{signal} then it
  1152. should be a list containing the Unix signal number; If
  1153. @var{key} is @code{out-of-range}, @code{wrong-type-arg},
  1154. or @code{keyword-argument-error},
  1155. it is a list containing the bad value; otherwise
  1156. it will usually be @code{#f}.
  1157. @end deffn
  1158. @deffn {Scheme Procedure} strerror err
  1159. @deffnx {C Function} scm_strerror (err)
  1160. Return the Unix error message corresponding to @var{err}, an integer
  1161. @code{errno} value.
  1162. When @code{setlocale} has been called (@pxref{Locales}), the message
  1163. is in the language and charset of @code{LC_MESSAGES}. (This is done
  1164. by the C library.)
  1165. @end deffn
  1166. @c begin (scm-doc-string "boot-9.scm" "false-if-exception")
  1167. @deffn syntax false-if-exception expr
  1168. Returns the result of evaluating its argument; however
  1169. if an exception occurs then @code{#f} is returned instead.
  1170. @end deffn
  1171. @c end
  1172. @node Dynamic Wind
  1173. @subsection Dynamic Wind
  1174. For Scheme code, the fundamental procedure to react to non-local entry
  1175. and exits of dynamic contexts is @code{dynamic-wind}. C code could
  1176. use @code{scm_internal_dynamic_wind}, but since C does not allow the
  1177. convenient construction of anonymous procedures that close over
  1178. lexical variables, this will be, well, inconvenient.
  1179. Therefore, Guile offers the functions @code{scm_dynwind_begin} and
  1180. @code{scm_dynwind_end} to delimit a dynamic extent. Within this
  1181. dynamic extent, which is called a @dfn{dynwind context}, you can
  1182. perform various @dfn{dynwind actions} that control what happens when
  1183. the dynwind context is entered or left. For example, you can register
  1184. a cleanup routine with @code{scm_dynwind_unwind_handler} that is
  1185. executed when the context is left. There are several other more
  1186. specialized dynwind actions as well, for example to temporarily block
  1187. the execution of asyncs or to temporarily change the current output
  1188. port. They are described elsewhere in this manual.
  1189. Here is an example that shows how to prevent memory leaks.
  1190. @example
  1191. /* Suppose there is a function called FOO in some library that you
  1192. would like to make available to Scheme code (or to C code that
  1193. follows the Scheme conventions).
  1194. FOO takes two C strings and returns a new string. When an error has
  1195. occurred in FOO, it returns NULL.
  1196. */
  1197. char *foo (char *s1, char *s2);
  1198. /* SCM_FOO interfaces the C function FOO to the Scheme way of life.
  1199. It takes care to free up all temporary strings in the case of
  1200. non-local exits.
  1201. */
  1202. SCM
  1203. scm_foo (SCM s1, SCM s2)
  1204. @{
  1205. char *c_s1, *c_s2, *c_res;
  1206. scm_dynwind_begin (0);
  1207. c_s1 = scm_to_locale_string (s1);
  1208. /* Call 'free (c_s1)' when the dynwind context is left.
  1209. */
  1210. scm_dynwind_unwind_handler (free, c_s1, SCM_F_WIND_EXPLICITLY);
  1211. c_s2 = scm_to_locale_string (s2);
  1212. /* Same as above, but more concisely.
  1213. */
  1214. scm_dynwind_free (c_s2);
  1215. c_res = foo (c_s1, c_s2);
  1216. if (c_res == NULL)
  1217. scm_memory_error ("foo");
  1218. scm_dynwind_end ();
  1219. return scm_take_locale_string (res);
  1220. @}
  1221. @end example
  1222. @rnindex dynamic-wind
  1223. @deffn {Scheme Procedure} dynamic-wind in_guard thunk out_guard
  1224. @deffnx {C Function} scm_dynamic_wind (in_guard, thunk, out_guard)
  1225. All three arguments must be 0-argument procedures.
  1226. @var{in_guard} is called, then @var{thunk}, then
  1227. @var{out_guard}.
  1228. If, any time during the execution of @var{thunk}, the
  1229. dynamic extent of the @code{dynamic-wind} expression is escaped
  1230. non-locally, @var{out_guard} is called. If the dynamic extent of
  1231. the dynamic-wind is re-entered, @var{in_guard} is called. Thus
  1232. @var{in_guard} and @var{out_guard} may be called any number of
  1233. times.
  1234. @lisp
  1235. (define x 'normal-binding)
  1236. @result{} x
  1237. (define a-cont
  1238. (call-with-current-continuation
  1239. (lambda (escape)
  1240. (let ((old-x x))
  1241. (dynamic-wind
  1242. ;; in-guard:
  1243. ;;
  1244. (lambda () (set! x 'special-binding))
  1245. ;; thunk
  1246. ;;
  1247. (lambda () (display x) (newline)
  1248. (call-with-current-continuation escape)
  1249. (display x) (newline)
  1250. x)
  1251. ;; out-guard:
  1252. ;;
  1253. (lambda () (set! x old-x)))))))
  1254. ;; Prints:
  1255. special-binding
  1256. ;; Evaluates to:
  1257. @result{} a-cont
  1258. x
  1259. @result{} normal-binding
  1260. (a-cont #f)
  1261. ;; Prints:
  1262. special-binding
  1263. ;; Evaluates to:
  1264. @result{} a-cont ;; the value of the (define a-cont...)
  1265. x
  1266. @result{} normal-binding
  1267. a-cont
  1268. @result{} special-binding
  1269. @end lisp
  1270. @end deffn
  1271. @deftp {C Type} scm_t_dynwind_flags
  1272. This is an enumeration of several flags that modify the behavior of
  1273. @code{scm_dynwind_begin}. The flags are listed in the following
  1274. table.
  1275. @table @code
  1276. @item SCM_F_DYNWIND_REWINDABLE
  1277. The dynamic context is @dfn{rewindable}. This means that it can be
  1278. reentered non-locally (via the invocation of a continuation). The
  1279. default is that a dynwind context can not be reentered non-locally.
  1280. @end table
  1281. @end deftp
  1282. @deftypefn {C Function} void scm_dynwind_begin (scm_t_dynwind_flags flags)
  1283. The function @code{scm_dynwind_begin} starts a new dynamic context and
  1284. makes it the `current' one.
  1285. The @var{flags} argument determines the default behavior of the
  1286. context. Normally, use 0. This will result in a context that can not
  1287. be reentered with a captured continuation. When you are prepared to
  1288. handle reentries, include @code{SCM_F_DYNWIND_REWINDABLE} in
  1289. @var{flags}.
  1290. Being prepared for reentry means that the effects of unwind handlers
  1291. can be undone on reentry. In the example above, we want to prevent a
  1292. memory leak on non-local exit and thus register an unwind handler that
  1293. frees the memory. But once the memory is freed, we can not get it
  1294. back on reentry. Thus reentry can not be allowed.
  1295. The consequence is that continuations become less useful when
  1296. non-reentrant contexts are captured, but you don't need to worry
  1297. about that too much.
  1298. The context is ended either implicitly when a non-local exit happens,
  1299. or explicitly with @code{scm_dynwind_end}. You must make sure that a
  1300. dynwind context is indeed ended properly. If you fail to call
  1301. @code{scm_dynwind_end} for each @code{scm_dynwind_begin}, the behavior
  1302. is undefined.
  1303. @end deftypefn
  1304. @deftypefn {C Function} void scm_dynwind_end ()
  1305. End the current dynamic context explicitly and make the previous one
  1306. current.
  1307. @end deftypefn
  1308. @deftp {C Type} scm_t_wind_flags
  1309. This is an enumeration of several flags that modify the behavior of
  1310. @code{scm_dynwind_unwind_handler} and
  1311. @code{scm_dynwind_rewind_handler}. The flags are listed in the
  1312. following table.
  1313. @table @code
  1314. @item SCM_F_WIND_EXPLICITLY
  1315. @vindex SCM_F_WIND_EXPLICITLY
  1316. The registered action is also carried out when the dynwind context is
  1317. entered or left locally.
  1318. @end table
  1319. @end deftp
  1320. @deftypefn {C Function} void scm_dynwind_unwind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
  1321. @deftypefnx {C Function} void scm_dynwind_unwind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
  1322. Arranges for @var{func} to be called with @var{data} as its arguments
  1323. when the current context ends implicitly. If @var{flags} contains
  1324. @code{SCM_F_WIND_EXPLICITLY}, @var{func} is also called when the
  1325. context ends explicitly with @code{scm_dynwind_end}.
  1326. The function @code{scm_dynwind_unwind_handler_with_scm} takes care that
  1327. @var{data} is protected from garbage collection.
  1328. @end deftypefn
  1329. @deftypefn {C Function} void scm_dynwind_rewind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
  1330. @deftypefnx {C Function} void scm_dynwind_rewind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
  1331. Arrange for @var{func} to be called with @var{data} as its argument when
  1332. the current context is restarted by rewinding the stack. When @var{flags}
  1333. contains @code{SCM_F_WIND_EXPLICITLY}, @var{func} is called immediately
  1334. as well.
  1335. The function @code{scm_dynwind_rewind_handler_with_scm} takes care that
  1336. @var{data} is protected from garbage collection.
  1337. @end deftypefn
  1338. @deftypefn {C Function} void scm_dynwind_free (void *mem)
  1339. Arrange for @var{mem} to be freed automatically whenever the current
  1340. context is exited, whether normally or non-locally.
  1341. @code{scm_dynwind_free (mem)} is an equivalent shorthand for
  1342. @code{scm_dynwind_unwind_handler (free, mem, SCM_F_WIND_EXPLICITLY)}.
  1343. @end deftypefn
  1344. @node Handling Errors
  1345. @subsection How to Handle Errors
  1346. Error handling is based on @code{catch} and @code{throw}. Errors are
  1347. always thrown with a @var{key} and four arguments:
  1348. @itemize @bullet
  1349. @item
  1350. @var{key}: a symbol which indicates the type of error. The symbols used
  1351. by libguile are listed below.
  1352. @item
  1353. @var{subr}: the name of the procedure from which the error is thrown, or
  1354. @code{#f}.
  1355. @item
  1356. @var{message}: a string (possibly language and system dependent)
  1357. describing the error. The tokens @code{~A} and @code{~S} can be
  1358. embedded within the message: they will be replaced with members of the
  1359. @var{args} list when the message is printed. @code{~A} indicates an
  1360. argument printed using @code{display}, while @code{~S} indicates an
  1361. argument printed using @code{write}. @var{message} can also be
  1362. @code{#f}, to allow it to be derived from the @var{key} by the error
  1363. handler (may be useful if the @var{key} is to be thrown from both C and
  1364. Scheme).
  1365. @item
  1366. @var{args}: a list of arguments to be used to expand @code{~A} and
  1367. @code{~S} tokens in @var{message}. Can also be @code{#f} if no
  1368. arguments are required.
  1369. @item
  1370. @var{rest}: a list of any additional objects required. e.g., when the
  1371. key is @code{'system-error}, this contains the C errno value. Can also
  1372. be @code{#f} if no additional objects are required.
  1373. @end itemize
  1374. In addition to @code{catch} and @code{throw}, the following Scheme
  1375. facilities are available:
  1376. @deffn {Scheme Procedure} display-error frame port subr message args rest
  1377. @deffnx {C Function} scm_display_error (frame, port, subr, message, args, rest)
  1378. Display an error message to the output port @var{port}.
  1379. @var{frame} is the frame in which the error occurred, @var{subr} is
  1380. the name of the procedure in which the error occurred and
  1381. @var{message} is the actual error message, which may contain
  1382. formatting instructions. These will format the arguments in
  1383. the list @var{args} accordingly. @var{rest} is currently
  1384. ignored.
  1385. @end deffn
  1386. The following are the error keys defined by libguile and the situations
  1387. in which they are used:
  1388. @itemize @bullet
  1389. @item
  1390. @cindex @code{error-signal}
  1391. @code{error-signal}: thrown after receiving an unhandled fatal signal
  1392. such as SIGSEGV, SIGBUS, SIGFPE etc. The @var{rest} argument in the throw
  1393. contains the coded signal number (at present this is not the same as the
  1394. usual Unix signal number).
  1395. @item
  1396. @cindex @code{system-error}
  1397. @code{system-error}: thrown after the operating system indicates an
  1398. error condition. The @var{rest} argument in the throw contains the
  1399. errno value.
  1400. @item
  1401. @cindex @code{numerical-overflow}
  1402. @code{numerical-overflow}: numerical overflow.
  1403. @item
  1404. @cindex @code{out-of-range}
  1405. @code{out-of-range}: the arguments to a procedure do not fall within the
  1406. accepted domain.
  1407. @item
  1408. @cindex @code{wrong-type-arg}
  1409. @code{wrong-type-arg}: an argument to a procedure has the wrong type.
  1410. @item
  1411. @cindex @code{wrong-number-of-args}
  1412. @code{wrong-number-of-args}: a procedure was called with the wrong number
  1413. of arguments.
  1414. @item
  1415. @cindex @code{memory-allocation-error}
  1416. @code{memory-allocation-error}: memory allocation error.
  1417. @item
  1418. @cindex @code{stack-overflow}
  1419. @code{stack-overflow}: stack overflow error.
  1420. @item
  1421. @cindex @code{regular-expression-syntax}
  1422. @code{regular-expression-syntax}: errors generated by the regular
  1423. expression library.
  1424. @item
  1425. @cindex @code{misc-error}
  1426. @code{misc-error}: other errors.
  1427. @end itemize
  1428. @subsubsection C Support
  1429. In the following C functions, @var{SUBR} and @var{MESSAGE} parameters
  1430. can be @code{NULL} to give the effect of @code{#f} described above.
  1431. @deftypefn {C Function} SCM scm_error (SCM @var{key}, char *@var{subr}, char *@var{message}, SCM @var{args}, SCM @var{rest})
  1432. Throw an error, as per @code{scm-error} (@pxref{Error Reporting}).
  1433. @end deftypefn
  1434. @deftypefn {C Function} void scm_syserror (char *@var{subr})
  1435. @deftypefnx {C Function} void scm_syserror_msg (char *@var{subr}, char *@var{message}, SCM @var{args})
  1436. Throw an error with key @code{system-error} and supply @code{errno} in
  1437. the @var{rest} argument. For @code{scm_syserror} the message is
  1438. generated using @code{strerror}.
  1439. Care should be taken that any code in between the failing operation
  1440. and the call to these routines doesn't change @code{errno}.
  1441. @end deftypefn
  1442. @deftypefn {C Function} void scm_num_overflow (char *@var{subr})
  1443. @deftypefnx {C Function} void scm_out_of_range (char *@var{subr}, SCM @var{bad_value})
  1444. @deftypefnx {C Function} void scm_wrong_num_args (SCM @var{proc})
  1445. @deftypefnx {C Function} void scm_wrong_type_arg (char *@var{subr}, int @var{argnum}, SCM @var{bad_value})
  1446. @deftypefnx {C Function} void scm_wrong_type_arg_msg (char *@var{subr}, int @var{argnum}, SCM @var{bad_value}, const char *@var{expected})
  1447. @deftypefnx {C Function} void scm_memory_error (char *@var{subr})
  1448. @deftypefnx {C Function} void scm_misc_error (const char *@var{subr}, const char *@var{message}, SCM @var{args})
  1449. Throw an error with the various keys described above.
  1450. In @code{scm_wrong_num_args}, @var{proc} should be a Scheme symbol
  1451. which is the name of the procedure incorrectly invoked. The other
  1452. routines take the name of the invoked procedure as a C string.
  1453. In @code{scm_wrong_type_arg_msg}, @var{expected} is a C string
  1454. describing the type of argument that was expected.
  1455. In @code{scm_misc_error}, @var{message} is the error message string,
  1456. possibly containing @code{simple-format} escapes (@pxref{Writing}), and
  1457. the corresponding arguments in the @var{args} list.
  1458. @end deftypefn
  1459. @subsubsection Signalling Type Errors
  1460. Every function visible at the Scheme level should aggressively check the
  1461. types of its arguments, to avoid misinterpreting a value, and perhaps
  1462. causing a segmentation fault. Guile provides some macros to make this
  1463. easier.
  1464. @deftypefn Macro void SCM_ASSERT (int @var{test}, SCM @var{obj}, unsigned int @var{position}, const char *@var{subr})
  1465. @deftypefnx Macro void SCM_ASSERT_TYPE (int @var{test}, SCM @var{obj}, unsigned int @var{position}, const char *@var{subr}, const char *@var{expected})
  1466. If @var{test} is zero, signal a ``wrong type argument'' error,
  1467. attributed to the subroutine named @var{subr}, operating on the value
  1468. @var{obj}, which is the @var{position}'th argument of @var{subr}.
  1469. In @code{SCM_ASSERT_TYPE}, @var{expected} is a C string describing the
  1470. type of argument that was expected.
  1471. @end deftypefn
  1472. @deftypefn Macro int SCM_ARG1
  1473. @deftypefnx Macro int SCM_ARG2
  1474. @deftypefnx Macro int SCM_ARG3
  1475. @deftypefnx Macro int SCM_ARG4
  1476. @deftypefnx Macro int SCM_ARG5
  1477. @deftypefnx Macro int SCM_ARG6
  1478. @deftypefnx Macro int SCM_ARG7
  1479. One of the above values can be used for @var{position} to indicate the
  1480. number of the argument of @var{subr} which is being checked.
  1481. Alternatively, a positive integer number can be used, which allows to
  1482. check arguments after the seventh. However, for parameter numbers up to
  1483. seven it is preferable to use @code{SCM_ARGN} instead of the
  1484. corresponding raw number, since it will make the code easier to
  1485. understand.
  1486. @end deftypefn
  1487. @deftypefn Macro int SCM_ARGn
  1488. Passing a value of zero or @code{SCM_ARGn} for @var{position} allows to
  1489. leave it unspecified which argument's type is incorrect. Again,
  1490. @code{SCM_ARGn} should be preferred over a raw zero constant.
  1491. @end deftypefn
  1492. @node Continuation Barriers
  1493. @subsection Continuation Barriers
  1494. The non-local flow of control caused by continuations might sometimes
  1495. not be wanted. You can use @code{with-continuation-barrier} to erect
  1496. fences that continuations can not pass.
  1497. @deffn {Scheme Procedure} with-continuation-barrier proc
  1498. @deffnx {C Function} scm_with_continuation_barrier (proc)
  1499. Call @var{proc} and return its result. Do not allow the invocation of
  1500. continuations that would leave or enter the dynamic extent of the call
  1501. to @code{with-continuation-barrier}. Such an attempt causes an error
  1502. to be signaled.
  1503. Throws (such as errors) that are not caught from within @var{proc} are
  1504. caught by @code{with-continuation-barrier}. In that case, a short
  1505. message is printed to the current error port and @code{#f} is returned.
  1506. Thus, @code{with-continuation-barrier} returns exactly once.
  1507. @end deffn
  1508. @deftypefn {C Function} {void *} scm_c_with_continuation_barrier (void *(*func) (void *), void *data)
  1509. Like @code{scm_with_continuation_barrier} but call @var{func} on
  1510. @var{data}. When an error is caught, @code{NULL} is returned.
  1511. @end deftypefn
  1512. @c Local Variables:
  1513. @c TeX-master: "guile.texi"
  1514. @c End: