api-control.texi 83 KB

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