api-control.texi 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376
  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:: Raising and handling 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
  417. @code{abort-to-prompt} as a fancy kind of @code{setjmp} and
  418. @code{longjmp}, respectively. Prompts are indeed quite useful as
  419. non-local escape mechanisms. Guile's @code{with-exception-handler} and
  420. @code{raise-exception} are implemented in terms of prompts. Prompts are
  421. more convenient than @code{longjmp}, in that one has the opportunity to
  422. pass multiple values to the jump target.
  423. Also unlike @code{longjmp}, the prompt handler is given the full state of the
  424. process that was aborted, as the first argument to the prompt's handler. That
  425. state is the @dfn{continuation} of the computation wrapped by the prompt. It is
  426. a @dfn{delimited continuation}, because it is not the whole continuation of the
  427. program; rather, just the computation initiated by the call to
  428. @code{call-with-prompt}.
  429. The continuation is a procedure, and may be reinstated simply by invoking it,
  430. with any number of values. Here's where things get interesting, and complicated
  431. as well. Besides being described as delimited, continuations reified by prompts
  432. are also @dfn{composable}, because invoking a prompt-saved continuation composes
  433. that continuation with the current one.
  434. Imagine you have saved a continuation via call-with-prompt:
  435. @example
  436. (define cont
  437. (call-with-prompt
  438. ;; tag
  439. 'foo
  440. ;; thunk
  441. (lambda ()
  442. (+ 34 (abort-to-prompt 'foo)))
  443. ;; handler
  444. (lambda (k) k)))
  445. @end example
  446. The resulting continuation is the addition of 34. It's as if you had written:
  447. @example
  448. (define cont
  449. (lambda (x)
  450. (+ 34 x)))
  451. @end example
  452. So, if we call @code{cont} with one numeric value, we get that number,
  453. incremented by 34:
  454. @example
  455. (cont 8)
  456. @result{} 42
  457. (* 2 (cont 8))
  458. @result{} 84
  459. @end example
  460. The last example illustrates what we mean when we say, "composes with the
  461. current continuation". We mean that there is a current continuation -- some
  462. remaining things to compute, like @code{(lambda (x) (* x 2))} -- and that
  463. calling the saved continuation doesn't wipe out the current continuation, it
  464. composes the saved continuation with the current one.
  465. We're belaboring the point here because traditional Scheme continuations, as
  466. discussed in the next section, aren't composable, and are actually less
  467. expressive than continuations captured by prompts. But there's a place for them
  468. both.
  469. Before moving on, we should mention that if the handler of a prompt is a
  470. @code{lambda} expression, and the first argument isn't referenced, an abort to
  471. that prompt will not cause a continuation to be reified. This can be an
  472. important efficiency consideration to keep in mind.
  473. @cindex continuation, escape
  474. One example where this optimization matters is @dfn{escape
  475. continuations}. Escape continuations are delimited continuations whose
  476. only use is to make a non-local exit---i.e., to escape from the current
  477. continuation. A common use of escape continuations is when handling an
  478. exception (@pxref{Exceptions}).
  479. The constructs below are syntactic sugar atop prompts to simplify the
  480. use of escape continuations.
  481. @deffn {Scheme Procedure} call-with-escape-continuation proc
  482. @deffnx {Scheme Procedure} call/ec proc
  483. Call @var{proc} with an escape continuation.
  484. In the example below, the @var{return} continuation is used to escape
  485. the continuation of the call to @code{fold}.
  486. @lisp
  487. (use-modules (ice-9 control)
  488. (srfi srfi-1))
  489. (define (prefix x lst)
  490. ;; Return all the elements before the first occurrence
  491. ;; of X in LST.
  492. (call/ec
  493. (lambda (return)
  494. (fold (lambda (element prefix)
  495. (if (equal? element x)
  496. (return (reverse prefix)) ; escape `fold'
  497. (cons element prefix)))
  498. '()
  499. lst))))
  500. (prefix 'a '(0 1 2 a 3 4 5))
  501. @result{} (0 1 2)
  502. @end lisp
  503. @end deffn
  504. @deffn {Scheme Syntax} let-escape-continuation k body @dots{}
  505. @deffnx {Scheme Syntax} let/ec k body @dots{}
  506. Bind @var{k} within @var{body} to an escape continuation.
  507. This is equivalent to
  508. @code{(call/ec (lambda (@var{k}) @var{body} @dots{}))}.
  509. @end deffn
  510. Additionally there is another helper primitive exported by @code{(ice-9
  511. control)}, so load up that module for @code{suspendable-continuation?}:
  512. @example
  513. (use-modules (ice-9 control))
  514. @end example
  515. @deffn {Scheme Procedure} suspendable-continuation? tag
  516. Return @code{#t} if a call to @code{abort-to-prompt} with the prompt tag
  517. @var{tag} would produce a delimited continuation that could be resumed
  518. later.
  519. Almost all continuations have this property. The exception is where
  520. some code between the @code{call-with-prompt} and the
  521. @code{abort-to-prompt} recursed through C for some reason, the
  522. @code{abort-to-prompt} will succeed but any attempt to resume the
  523. continuation (by calling it) would fail. This is because composing a
  524. saved continuation with the current continuation involves relocating the
  525. stack frames that were saved from the old stack onto a (possibly) new
  526. position on the new stack, and Guile can only do this for stack frames
  527. that it created for Scheme code, not stack frames created by the C
  528. compiler. It's a bit gnarly but if you stick with Scheme, you won't
  529. have any problem.
  530. If no prompt is found with the given tag, this procedure just returns
  531. @code{#f}.
  532. @end deffn
  533. @node Shift and Reset
  534. @subsubsection Shift, Reset, and All That
  535. There is a whole zoo of delimited control operators, and as it does not
  536. seem to be a bounded set, Guile implements support for them in a
  537. separate module:
  538. @example
  539. (use-modules (ice-9 control))
  540. @end example
  541. Firstly, we have a helpful abbreviation for the @code{call-with-prompt}
  542. operator.
  543. @deffn {Scheme Syntax} % expr
  544. @deffnx {Scheme Syntax} % expr handler
  545. @deffnx {Scheme Syntax} % tag expr handler
  546. Evaluate @var{expr} in a prompt, optionally specifying a tag and a
  547. handler. If no tag is given, the default prompt tag is used.
  548. If no handler is given, a default handler is installed. The default
  549. handler accepts a procedure of one argument, which will be called on
  550. the captured continuation, within a prompt.
  551. Sometimes it's easier just to show code, as in this case:
  552. @example
  553. (define (default-prompt-handler k proc)
  554. (% (default-prompt-tag)
  555. (proc k)
  556. default-prompt-handler))
  557. @end example
  558. The @code{%} symbol is chosen because it looks like a prompt.
  559. @end deffn
  560. Likewise there is an abbreviation for @code{abort-to-prompt}, which
  561. assumes the default prompt tag:
  562. @deffn {Scheme Procedure} abort val1 val2 @dots{}
  563. Abort to the default prompt tag, passing @var{val1} @var{val2} @dots{}
  564. to the handler.
  565. @end deffn
  566. As mentioned before, @code{(ice-9 control)} also provides other
  567. delimited control operators. This section is a bit technical, and
  568. first-time users of delimited continuations should probably come back to
  569. it after some practice with @code{%}.
  570. Still here? So, when one implements a delimited control operator like
  571. @code{call-with-prompt}, one needs to make two decisions. Firstly, does
  572. the handler run within or outside the prompt? Having the handler run
  573. within the prompt allows an abort inside the handler to return to the
  574. same prompt handler, which is often useful. However it prevents tail
  575. calls from the handler, so it is less general.
  576. Similarly, does invoking a captured continuation reinstate a prompt?
  577. Again we have the tradeoff of convenience versus proper tail calls.
  578. These decisions are captured in the Felleisen @dfn{F} operator. If
  579. neither the continuations nor the handlers implicitly add a prompt, the
  580. operator is known as @dfn{--F--}. This is the case for Guile's
  581. @code{call-with-prompt} and @code{abort-to-prompt}.
  582. If both continuation and handler implicitly add prompts, then the
  583. operator is @dfn{+F+}. @code{shift} and @code{reset} are such
  584. operators.
  585. @deffn {Scheme Syntax} reset body1 body2 @dots{}
  586. Establish a prompt, and evaluate @var{body1} @var{body2} @dots{} within
  587. that prompt.
  588. The prompt handler is designed to work with @code{shift}, described
  589. below.
  590. @end deffn
  591. @deffn {Scheme Syntax} shift cont body1 body2 @dots{}
  592. Abort to the nearest @code{reset}, and evaluate @var{body1} @var{body2}
  593. @dots{} in a context in which the captured continuation is bound to
  594. @var{cont}.
  595. As mentioned above, taken together, the @var{body1} @var{body2} @dots{}
  596. expressions and the invocations of @var{cont} implicitly establish a
  597. prompt.
  598. @end deffn
  599. Interested readers are invited to explore Oleg Kiselyov's wonderful web
  600. site at @uref{http://okmij.org/ftp/}, for more information on these
  601. operators.
  602. @node Continuations
  603. @subsection Continuations
  604. @cindex continuations
  605. A ``continuation'' is the code that will execute when a given function
  606. or expression returns. For example, consider
  607. @example
  608. (define (foo)
  609. (display "hello\n")
  610. (display (bar)) (newline)
  611. (exit))
  612. @end example
  613. The continuation from the call to @code{bar} comprises a
  614. @code{display} of the value returned, a @code{newline} and an
  615. @code{exit}. This can be expressed as a function of one argument.
  616. @example
  617. (lambda (r)
  618. (display r) (newline)
  619. (exit))
  620. @end example
  621. In Scheme, continuations are represented as special procedures just
  622. like this. The special property is that when a continuation is called
  623. it abandons the current program location and jumps directly to that
  624. represented by the continuation.
  625. A continuation is like a dynamic label, capturing at run-time a point
  626. in program execution, including all the nested calls that have lead to
  627. it (or rather the code that will execute when those calls return).
  628. Continuations are created with the following functions.
  629. @deffn {Scheme Procedure} call-with-current-continuation proc
  630. @deffnx {Scheme Procedure} call/cc proc
  631. @rnindex call-with-current-continuation
  632. Capture the current continuation and call @code{(@var{proc}
  633. @var{cont})} with it. The return value is the value returned by
  634. @var{proc}, or when @code{(@var{cont} @var{value})} is later invoked,
  635. the return is the @var{value} passed.
  636. Normally @var{cont} should be called with one argument, but when the
  637. location resumed is expecting multiple values (@pxref{Multiple
  638. Values}) then they should be passed as multiple arguments, for
  639. instance @code{(@var{cont} @var{x} @var{y} @var{z})}.
  640. @var{cont} may only be used from the same side of a continuation
  641. barrier as it was created (@pxref{Continuation Barriers}), and in a
  642. multi-threaded program only from the thread in which it was created.
  643. The call to @var{proc} is not part of the continuation captured, it runs
  644. only when the continuation is created. Often a program will want to
  645. store @var{cont} somewhere for later use; this can be done in
  646. @var{proc}.
  647. The @code{call} in the name @code{call-with-current-continuation}
  648. refers to the way a call to @var{proc} gives the newly created
  649. continuation. It's not related to the way a call is used later to
  650. invoke that continuation.
  651. @code{call/cc} is an alias for @code{call-with-current-continuation}.
  652. This is in common use since the latter is rather long.
  653. @end deffn
  654. @sp 1
  655. @noindent
  656. Here is a simple example,
  657. @example
  658. (define kont #f)
  659. (format #t "the return is ~a\n"
  660. (call/cc (lambda (k)
  661. (set! kont k)
  662. 1)))
  663. @result{} the return is 1
  664. (kont 2)
  665. @result{} the return is 2
  666. @end example
  667. @code{call/cc} captures a continuation in which the value returned is
  668. going to be displayed by @code{format}. The @code{lambda} stores this
  669. in @code{kont} and gives an initial return @code{1} which is
  670. displayed. The later invocation of @code{kont} resumes the captured
  671. point, but this time returning @code{2}, which is displayed.
  672. When Guile is run interactively, a call to @code{format} like this has
  673. an implicit return back to the read-eval-print loop. @code{call/cc}
  674. captures that like any other return, which is why interactively
  675. @code{kont} will come back to read more input.
  676. @sp 1
  677. C programmers may note that @code{call/cc} is like @code{setjmp} in
  678. the way it records at runtime a point in program execution. A call to
  679. a continuation is like a @code{longjmp} in that it abandons the
  680. present location and goes to the recorded one. Like @code{longjmp},
  681. the value passed to the continuation is the value returned by
  682. @code{call/cc} on resuming there. However @code{longjmp} can only go
  683. up the program stack, but the continuation mechanism can go anywhere.
  684. When a continuation is invoked, @code{call/cc} and subsequent code
  685. effectively ``returns'' a second time. It can be confusing to imagine
  686. a function returning more times than it was called. It may help
  687. instead to think of it being stealthily re-entered and then program
  688. flow going on as normal.
  689. @code{dynamic-wind} (@pxref{Dynamic Wind}) can be used to ensure setup
  690. and cleanup code is run when a program locus is resumed or abandoned
  691. through the continuation mechanism.
  692. @sp 1
  693. Continuations are a powerful mechanism, and can be used to implement
  694. almost any sort of control structure, such as loops, coroutines, or
  695. exception handlers.
  696. However the implementation of continuations in Guile is not as
  697. efficient as one might hope, because Guile is designed to cooperate
  698. with programs written in other languages, such as C, which do not know
  699. about continuations. Basically continuations are captured by a block
  700. copy of the stack, and resumed by copying back.
  701. For this reason, continuations captured by @code{call/cc} should be used only
  702. when there is no other simple way to achieve the desired result, or when the
  703. elegance of the continuation mechanism outweighs the need for performance.
  704. Escapes upwards from loops or nested functions are generally best
  705. handled with prompts (@pxref{Prompts}). Coroutines can be
  706. efficiently implemented with cooperating threads (a thread holds a
  707. full program stack but doesn't copy it around the way continuations
  708. do).
  709. @node Multiple Values
  710. @subsection Returning and Accepting Multiple Values
  711. @cindex multiple values
  712. @cindex receive
  713. Scheme allows a procedure to return more than one value to its caller.
  714. This is quite different to other languages which only allow
  715. single-value returns. Returning multiple values is different from
  716. returning a list (or pair or vector) of values to the caller, because
  717. conceptually not @emph{one} compound object is returned, but several
  718. distinct values.
  719. The primitive procedures for handling multiple values are @code{values}
  720. and @code{call-with-values}. @code{values} is used for returning
  721. multiple values from a procedure. This is done by placing a call to
  722. @code{values} with zero or more arguments in tail position in a
  723. procedure body. @code{call-with-values} combines a procedure returning
  724. multiple values with a procedure which accepts these values as
  725. parameters.
  726. @rnindex values
  727. @deffn {Scheme Procedure} values arg @dots{}
  728. @deffnx {C Function} scm_values (args)
  729. Delivers all of its arguments to its continuation. Except for
  730. continuations created by the @code{call-with-values} procedure,
  731. all continuations take exactly one value. The effect of
  732. passing no value or more than one value to continuations that
  733. were not created by @code{call-with-values} is unspecified.
  734. For @code{scm_values}, @var{args} is a list of arguments and the
  735. return is a multiple-values object which the caller can return. In
  736. the current implementation that object shares structure with
  737. @var{args}, so @var{args} should not be modified subsequently.
  738. @end deffn
  739. @deftypefn {C Function} SCM scm_c_values (SCM *base, size_t n)
  740. @code{scm_c_values} is an alternative to @code{scm_values}. It creates
  741. a new values object, and copies into it the @var{n} values starting from
  742. @var{base}.
  743. Currently this creates a list and passes it to @code{scm_values}, but we
  744. expect that in the future we will be able to use a more efficient
  745. representation.
  746. @end deftypefn
  747. @deftypefn {C Function} size_t scm_c_nvalues (SCM obj)
  748. If @var{obj} is a multiple-values object, returns the number of values
  749. it contains. Otherwise returns 1.
  750. @end deftypefn
  751. @deftypefn {C Function} SCM scm_c_value_ref (SCM obj, size_t idx)
  752. Returns the value at the position specified by @var{idx} in
  753. @var{obj}. Note that @var{obj} will ordinarily be a
  754. multiple-values object, but it need not be. Any other object
  755. represents a single value (itself), and is handled appropriately.
  756. @end deftypefn
  757. @rnindex call-with-values
  758. @deffn {Scheme Procedure} call-with-values producer consumer
  759. Calls its @var{producer} argument with no values and a
  760. continuation that, when passed some values, calls the
  761. @var{consumer} procedure with those values as arguments. The
  762. continuation for the call to @var{consumer} is the continuation
  763. of the call to @code{call-with-values}.
  764. @example
  765. (call-with-values (lambda () (values 4 5))
  766. (lambda (a b) b))
  767. @result{} 5
  768. @end example
  769. @example
  770. (call-with-values * -)
  771. @result{} -1
  772. @end example
  773. @end deffn
  774. In addition to the fundamental procedures described above, Guile has a
  775. module which exports a syntax called @code{receive}, which is much
  776. more convenient. This is in the @code{(ice-9 receive)} and is the
  777. same as specified by SRFI-8 (@pxref{SRFI-8}).
  778. @lisp
  779. (use-modules (ice-9 receive))
  780. @end lisp
  781. @deffn {library syntax} receive formals expr body @dots{}
  782. Evaluate the expression @var{expr}, and bind the result values (zero
  783. or more) to the formal arguments in @var{formals}. @var{formals} is a
  784. list of symbols, like the argument list in a @code{lambda}
  785. (@pxref{Lambda}). After binding the variables, the expressions in
  786. @var{body} @dots{} are evaluated in order, the return value is the
  787. result from the last expression.
  788. For example getting results from @code{partition} in SRFI-1
  789. (@pxref{SRFI-1}),
  790. @example
  791. (receive (odds evens)
  792. (partition odd? '(7 4 2 8 3))
  793. (display odds)
  794. (display " and ")
  795. (display evens))
  796. @print{} (7 3) and (4 2 8)
  797. @end example
  798. @end deffn
  799. @node Exceptions
  800. @subsection Exceptions
  801. @cindex error handling
  802. @cindex exception handling
  803. What happens when things go wrong? Guile's exception facility exists to
  804. help answer this question, allowing programs to describe the problem and
  805. to handle the situation in a flexible way.
  806. When a program runs into a problem, such as division by zero, it will
  807. raise an exception. Sometimes exceptions get raised by Guile on a
  808. program's behalf. Sometimes a program will want to raise exceptions of
  809. its own. Raising an exception stops the current computation and instead
  810. invokes the current exception handler, passing it an exception object
  811. describing the unexpected situation.
  812. Usually an exception handler will unwind the computation back to some
  813. kind of safe point. For example, typical logic for a key press driven
  814. application might look something like this:
  815. @example
  816. main-loop:
  817. read the next key press and call dispatch-key
  818. dispatch-key:
  819. lookup the key in a keymap and call an appropriate procedure,
  820. say find-file
  821. find-file:
  822. interactively read the required file name, then call
  823. find-specified-file
  824. find-specified-file:
  825. check whether file exists; if not, raise an exception
  826. @dots{}
  827. @end example
  828. In this case, @code{main-loop} can install an exception handler that
  829. would cause any exception raised inside @code{dispatch-key} to print a
  830. warning and jump back to the main loop.
  831. The following subsections go into more detail about exception objects,
  832. raising exceptions, and handling exceptions. It also presents a
  833. historical interface that was used in Guile's first 25 years and which
  834. won't be going away any time soon.
  835. @menu
  836. * Exception Objects:: What went wrong?
  837. * Raising and Handling Exceptions:: What to do when something goes wrong.
  838. * Throw and Catch:: An older approach to exceptions.
  839. * Exceptions and C:: Specialized interfaces for C.
  840. @end menu
  841. @node Exception Objects
  842. @subsubsection Exception Objects
  843. When Guile encounters an exceptional situation, it raises an exception,
  844. where the exception is an object that describes the exceptional
  845. situation. Exception objects are structured data, built on the record
  846. facility (@pxref{Records}).
  847. @deftp {Exception Type} &exception
  848. The base exception type. All exception objects are composed of
  849. instances of subtypes of @code{&exception}.
  850. @end deftp
  851. @deffn {Scheme Procedure} exception-type? obj
  852. Return true if @var{obj} is an exception type.
  853. @end deffn
  854. Exception types exist in a hierarchy. New exception types can be
  855. defined using @code{make-exception-type}.
  856. @deffn {Scheme Procedure} make-exception-type id parent field-names
  857. Return a new exception type named @var{id}, inheriting from
  858. @var{parent}, and with the fields whose names are listed in
  859. @var{field-names}. @var{field-names} must be a list of symbols and must
  860. not contain names already used by @var{parent} or one of its supertypes.
  861. @end deffn
  862. Exception type objects are record type objects, and as such, one can use
  863. @code{record-constructor} on an exception type to get its constructor.
  864. The constructor will take as many arguments as the exception has fields
  865. (including supertypes). @xref{Records}.
  866. However, @code{record-predicate} and @code{record-accessor} aren't
  867. usually what you want to use as exception type predicates and field
  868. accessors. The reason is, instances of exception types can be composed
  869. into @dfn{compound exceptions}. Exception accessors should pick out the
  870. specific component of a compound exception, and then access the field on
  871. that specific component.
  872. @deffn {Scheme Procedure} make-exception exceptions @dots{}
  873. Return an exception object composed of @var{exceptions}.
  874. @end deffn
  875. @deffn {Scheme Procedure} exception? obj
  876. Return true if @var{obj} is an exception object.
  877. @end deffn
  878. @deffn {Scheme Procedure} exception-predicate type
  879. Return a procedure that will return true if its argument is a simple
  880. exception that is an instance of @var{type}, or a compound exception
  881. composed of such an instance.
  882. @end deffn
  883. @deffn {Scheme Procedure} exception-accessor rtd proc
  884. Return a procedure that will tail-call @var{proc} on an instance of the
  885. exception type @var{rtd}, or on the component of a compound exception
  886. that is an instance of @var{rtd}.
  887. @end deffn
  888. Compound exceptions are useful to separately express the different
  889. aspects of a situation. For example, compound exceptions allow a
  890. programmer to say that ``this situation is a programming error, and also
  891. here's a useful message to show to the user, and here are some relevant
  892. objects that can give more information about the error''. This error
  893. could be composed of instances of the @code{&programming-error},
  894. @code{&message}, and @code{&irritants} exception types.
  895. The subtyping relationship in exceptions is useful to let
  896. different-but-similar situations to be treated the same; for example
  897. there are many varieties of programming errors (for example,
  898. divide-by-zero or type mismatches), but perhaps there are common ways
  899. that the user would like to handle them all, and that common way might
  900. be different than how one might handle an error originating outside the
  901. program (for example, a file-not-found error).
  902. The standard exception hierarchy in Guile takes its cues from R6RS,
  903. though the names of some of the types are different. @xref{rnrs
  904. exceptions}, for more details.
  905. To have access to Guile's exception type hierarchy, import the
  906. @code{(ice-9 exceptions)} module:
  907. @example
  908. (use-modules (ice-9 exceptions))
  909. @end example
  910. The following diagram gives an overview of the standard exception type
  911. hierarchy.
  912. @example
  913. &exception
  914. |- &warning
  915. |- &message
  916. |- &irritants
  917. |- &origin
  918. \- &error
  919. |- &external-error
  920. \- &programming-error
  921. |- &assertion-failure
  922. |- &non-continuable
  923. |- &implementation-restriction
  924. |- &lexical
  925. |- &syntax
  926. \- &undefined-variable
  927. @end example
  928. @deftp {Exception Type} &warning
  929. An exception type denoting warnings. These are usually raised using
  930. @code{#:continuable? #t}; see the @code{raise-exception} documentation
  931. for more.
  932. @end deftp
  933. @deffn {Scheme Procedure} make-warning
  934. @deffnx {Scheme Procedure} warning? obj
  935. Constructor and predicate for @code{&warning} exception objects.
  936. @end deffn
  937. @deftp {Exception Type} &message message
  938. An exception type that provides a message to display to the user.
  939. Usually used as a component of a compound exception.
  940. @end deftp
  941. @deffn {Scheme Procedure} make-exception-with-message message
  942. @deffnx {Scheme Procedure} exception-with-message? obj
  943. @deffnx {Scheme Procedure} exception-message exn
  944. Constructor, predicate, and accessor for @code{&message} exception
  945. objects.
  946. @end deffn
  947. @deftp {Exception Type} &irritants irritants
  948. An exception type that provides a list of objects that were unexpected
  949. in some way. Usually used as a component of a compound exception.
  950. @end deftp
  951. @deffn {Scheme Procedure} make-exception-with-irritants irritants
  952. @deffnx {Scheme Procedure} exception-with-irritants? obj
  953. @deffnx {Scheme Procedure} exception-irritants exn
  954. Constructor, predicate, and accessor for @code{&irritants} exception
  955. objects.
  956. @end deffn
  957. @deftp {Exception Type} &origin origin
  958. An exception type that indicates the origin of an exception, typically
  959. expressed as a procedure name, as a symbol. Usually used as a component
  960. of a compound exception.
  961. @end deftp
  962. @deffn {Scheme Procedure} make-exception-with-origin origin
  963. @deffnx {Scheme Procedure} exception-with-origin? obj
  964. @deffnx {Scheme Procedure} exception-origin exn
  965. Constructor, predicate, and accessor for @code{&origin} exception
  966. objects.
  967. @end deffn
  968. @deftp {Exception Type} &error
  969. An exception type denoting errors: situations that are not just
  970. exceptional, but wrong.
  971. @end deftp
  972. @deffn {Scheme Procedure} make-error
  973. @deffnx {Scheme Procedure} error? obj
  974. Constructor and predicate for @code{&error} exception objects.
  975. @end deffn
  976. @deftp {Exception Type} &external-error
  977. An exception type denoting errors that proceed from the interaction of
  978. the program with the world, for example a ``file not found'' error.
  979. @end deftp
  980. @deffn {Scheme Procedure} make-external-error
  981. @deffnx {Scheme Procedure} external-error? obj
  982. Constructor and predicate for @code{&external-error} exception objects.
  983. @end deffn
  984. @deftp {Exception Type} &programming-error
  985. An exception type denoting errors that proceed from inside a program:
  986. type mismatches and so on.
  987. @end deftp
  988. @deffn {Scheme Procedure} make-programming-error
  989. @deffnx {Scheme Procedure} programming-error? obj
  990. Constructor and predicate for @code{&programming-error} exception
  991. objects.
  992. @end deffn
  993. @deftp {Exception Type} &non-continuable
  994. An exception type denoting errors that proceed from inside a program:
  995. type mismatches and so on.
  996. @end deftp
  997. @deffn {Scheme Procedure} make-non-continuable-error
  998. @deffnx {Scheme Procedure} non-continuable-error? obj
  999. Constructor and predicate for @code{&non-continuable} exception objects.
  1000. @end deffn
  1001. @deftp {Exception Type} &lexical
  1002. An exception type denoting lexical errors, for example unbalanced
  1003. parentheses.
  1004. @end deftp
  1005. @deffn {Scheme Procedure} make-lexical-error
  1006. @deffnx {Scheme Procedure} lexical-error? obj
  1007. Constructor and predicate for @code{&lexical} exception objects.
  1008. @end deffn
  1009. @deftp {Exception Type} &syntax form subform
  1010. An exception type denoting syntax errors, for example a @code{cond}
  1011. expression with invalid syntax. The @var{form} field indicates the form
  1012. containing the error, and @var{subform} indicates the unexpected
  1013. subcomponent, or @code{#f} if unavailable.
  1014. @end deftp
  1015. @deffn {Scheme Procedure} make-syntax-error form subform
  1016. @deffnx {Scheme Procedure} syntax-error? obj
  1017. @deffnx {Scheme Procedure} syntax-error-form exn
  1018. @deffnx {Scheme Procedure} syntax-error-subform exn
  1019. Constructor, predicate, and accessors for @code{&syntax} exception
  1020. objects.
  1021. @end deffn
  1022. @deftp {Exception Type} &undefined-variable
  1023. An exception type denoting undefined variables.
  1024. @end deftp
  1025. @deffn {Scheme Procedure} make-undefine-variable-error
  1026. @deffnx {Scheme Procedure} undefined-variable-error? obj
  1027. Constructor and predicate for @code{&undefined-variable} exception
  1028. objects.
  1029. @end deffn
  1030. Incidentally, the @code{(ice-9 exceptions)} module also includes a
  1031. @code{define-exception-type} macro that can be used to conveniently add
  1032. new exception types to the hierarchy.
  1033. @deffn {Syntax} define-exception-type name parent @
  1034. constructor predicate @
  1035. (field accessor) @dots{}
  1036. Define @var{name} to be a new exception type, inheriting from
  1037. @var{parent}. Define @var{constructor} and @var{predicate} to be the
  1038. exception constructor and predicate, respectively, and define an
  1039. @var{accessor} for each @var{field}.
  1040. @end deffn
  1041. @node Raising and Handling Exceptions
  1042. @subsubsection Raising and Handling Exceptions
  1043. An exception object describes an exceptional situation. To bring that
  1044. description to the attention of the user or to handle the situation
  1045. programmatically, the first step is to @dfn{raise} the exception.
  1046. @deffn {Scheme Procedure} raise-exception obj [#:continuable=#f]
  1047. Raise an exception by invoking the current exception handler on
  1048. @var{obj}. The handler is called with a continuation whose dynamic
  1049. environment is that of the call to @code{raise}, except that the current
  1050. exception handler is the one that was in place when the handler being
  1051. called was installed.
  1052. If @var{continuable?} is true, the handler is invoked in tail position
  1053. relative to the @code{raise-exception} call. Otherwise if the handler
  1054. returns, a non-continuable exception of type @code{&non-continuable} is
  1055. raised in the same dynamic environment as the handler.
  1056. @end deffn
  1057. As the above description notes, Guile has a notion of a @dfn{current
  1058. exception handler}. At the REPL, this exception handler may enter a
  1059. recursive debugger; in a standalone program, it may simply print a
  1060. representation of the error and exit.
  1061. To establish an exception handler within the dynamic extent of a call,
  1062. use @code{with-exception-handler}.
  1063. @deffn {Scheme Procedure} with-exception-handler handler thunk @
  1064. [#:unwind?=#f] [#:unwind-for-type=#t]
  1065. Establish @var{handler}, a procedure of one argument, as the current
  1066. exception handler during the dynamic extent of invoking @var{thunk}.
  1067. If @code{raise-exception} is called during the dynamic extent of
  1068. invoking @var{thunk}, @var{handler} will be invoked on the argument of
  1069. @code{raise-exception}.
  1070. @end deffn
  1071. There are two kinds of exception handlers: unwinding and non-unwinding.
  1072. By default, exception handlers are non-unwinding. Unless
  1073. @code{with-exception-handler} was invoked with @code{#:unwind? #t},
  1074. exception handlers are invoked within the continuation of the error,
  1075. without unwinding the stack. The dynamic environment of the handler
  1076. call will be that of the @code{raise-exception} call, with the
  1077. difference that the current exception handler will be ``unwound'' to the
  1078. \"outer\" handler (the one that was in place when the corresponding
  1079. @code{with-exception-handler} was called).
  1080. However, it's often the case that one would like to handle an exception
  1081. by unwinding the computation to an earlier state and running the error
  1082. handler there. After all, unless the @code{raise-exception} call is
  1083. continuable, the exception handler needs to abort the continuation. To
  1084. support this use case, if @code{with-exception-handler} was invoked with
  1085. @code{#:unwind? #t} is true, @code{raise-exception} will first unwind
  1086. the stack by invoking an @dfn{escape continuation} (@pxref{Prompt
  1087. Primitives, @code{call/ec}}), and then invoke the handler with the
  1088. continuation of the @code{with-exception-handler} call.
  1089. Finally, one more wrinkle: for unwinding exception handlers, it can be
  1090. useful to Guile if it can determine whether an exception handler would
  1091. indeed handle a particular exception or not. This is especially the
  1092. case for exceptions raised in resource-exhaustion scenarios like
  1093. @code{stack-overflow} or @code{out-of-memory}, where you want to
  1094. immediately shrink resource use before recovering. @xref{Stack
  1095. Overflow}. For this purpose, the @code{#:unwind-for-type} keyword
  1096. argument allows users to specify the kind of exception handled by an
  1097. exception handler; if @code{#t}, all exceptions will be handled; if an
  1098. exception type object, only exceptions of that type will be handled;
  1099. otherwise if a symbol, only that exceptions with the given
  1100. @code{exception-kind} will be handled.
  1101. @node Throw and Catch
  1102. @subsubsection Throw and Catch
  1103. Guile only adopted @code{with-exception-handler} and
  1104. @code{raise-exception} as its primary exception-handling facility in
  1105. 2019. Before then, exception handling was fundamentally based on three
  1106. other primitives with a somewhat more complex interface: @code{catch},
  1107. @code{with-throw-handler}, and @code{throw}.
  1108. @deffn {Scheme Procedure} catch key thunk handler [pre-unwind-handler]
  1109. @deffnx {C Function} scm_catch_with_pre_unwind_handler (key, thunk, handler, pre_unwind_handler)
  1110. @deffnx {C Function} scm_catch (key, thunk, handler)
  1111. Establish an exception handler during the dynamic extent of the call to
  1112. @var{thunk}. @var{key} is either @code{#t}, indicating that all
  1113. exceptions should be handled, or a symbol, restricting the exceptions
  1114. handled to those having the @var{key} as their @code{exception-kind}.
  1115. If @var{thunk} executes normally, meaning without throwing any
  1116. exceptions, the handler procedures are not called at all and the result
  1117. of the @code{thunk} call is the result of the @code{catch}. Otherwise
  1118. if an exception is thrown that matches @var{key}, @var{handler} is
  1119. called with the continuation of the @code{catch} call.
  1120. @end deffn
  1121. Given the discussion from the previous section, it is most precise and
  1122. concise to specify what @code{catch} does by expressing it in terms of
  1123. @code{with-exception-handler}. Calling @code{catch} with the three
  1124. arguments is the same as:
  1125. @example
  1126. (define (catch key thunk handler)
  1127. (with-exception-handler
  1128. (lambda (exn)
  1129. (apply handler (exception-kind exn) (exception-args exn)))
  1130. thunk
  1131. #:unwind? #t
  1132. #:unwind-for-type key))
  1133. @end example
  1134. By invoking @code{with-exception-handler} with @code{#:unwind? #t},
  1135. @code{catch} sets up an escape continuation that will be invoked in an
  1136. exceptional situation before the handler is called.
  1137. If @code{catch} is called with four arguments, then the use of
  1138. @var{thunk} should be replaced with:
  1139. @example
  1140. (lambda ()
  1141. (with-throw-handler key thunk pre-unwind-handler))
  1142. @end example
  1143. As can be seen above, if a pre-unwind-handler is passed to @code{catch},
  1144. it's like calling @code{with-throw-handler} inside the body thunk.
  1145. @code{with-throw-handler} is the second of the older primitives, and is
  1146. used to be able to intercept an exception that is being thrown before
  1147. the stack is unwound. This could be to clean up some related state, to
  1148. print a backtrace, or to pass information about the exception to a
  1149. debugger, for example.
  1150. @deffn {Scheme Procedure} with-throw-handler key thunk handler
  1151. @deffnx {C Function} scm_with_throw_handler (key, thunk, handler)
  1152. Add @var{handler} to the dynamic context as a throw handler
  1153. for key @var{key}, then invoke @var{thunk}.
  1154. @end deffn
  1155. It's not possible to exactly express @code{with-throw-handler} in terms
  1156. of @code{with-exception-handler}, but we can get close.
  1157. @example
  1158. (define (with-throw-handler key thunk handler)
  1159. (with-exception-handler
  1160. (lambda (exn)
  1161. (when (or (eq? key #t) (eq? key (exception-kind exn)))
  1162. (apply handler (exception-kind exn) (exception-args exn)))
  1163. (raise-exception exn))
  1164. thunk))
  1165. @end example
  1166. As you can see, unlike in the case of @code{catch}, the handler for
  1167. @code{with-throw-handler} is invoked within the continuation of
  1168. @code{raise-exception}, before unwinding the stack. If the throw
  1169. handler returns normally, the exception will be re-raised, to be handled
  1170. by the next exception handler.
  1171. The special wrinkle of @code{with-throw-handler} that can't be shown
  1172. above is that if invoking the handler causes a @code{raise-exception}
  1173. instead of completing normally, the exception is thrown in the
  1174. @emph{original} dynamic environment of the @code{raise-exception}. Any
  1175. inner exception handler will get another shot at handling the exception.
  1176. Here is an example to illustrate this behavior:
  1177. @lisp
  1178. (catch 'a
  1179. (lambda ()
  1180. (with-throw-handler 'b
  1181. (lambda ()
  1182. (catch 'a
  1183. (lambda ()
  1184. (throw 'b))
  1185. inner-handler))
  1186. (lambda (key . args)
  1187. (throw 'a))))
  1188. outer-handler)
  1189. @end lisp
  1190. @noindent
  1191. This code will call @code{inner-handler} and then continue with the
  1192. continuation of the inner @code{catch}.
  1193. Finally, we get to @code{throw}, which is the older equivalent to
  1194. @code{raise-exception}.
  1195. @deffn {Scheme Procedure} throw key arg @dots{}
  1196. @deffnx {C Function} scm_throw (key, args)
  1197. Raise an exception with kind @var{key} and arguments @var{args}.
  1198. @var{key} is a symbol, denoting the ``kind'' of the exception.
  1199. @end deffn
  1200. Again, we can specify what @code{throw} does by expressing it in terms
  1201. of @code{raise-exception}.
  1202. @example
  1203. (define (throw key . args)
  1204. (raise-exception (make-exception-from-throw key args)))
  1205. @end example
  1206. At this point, we should mention the primitive that manage the
  1207. relationship between structured exception objects @code{throw}.
  1208. @deffn {Scheme Procedure} make-exception-from-throw key args
  1209. Create an exception object for the given @var{key} and @var{args} passed
  1210. to @code{throw}. This may be a specific type of exception, for example
  1211. @code{&programming-error}; Guile maintains a set of custom transformers
  1212. for the various @var{key} values that have been used historically.
  1213. @end deffn
  1214. @deffn {Scheme Procedure} exception-kind exn
  1215. If @var{exn} is an exception created via
  1216. @code{make-exception-from-throw}, return the corresponding @var{key} for
  1217. the exception. Otherwise, unless @var{exn} is an exception of a type
  1218. with a known mapping to @code{throw}, return the symbol
  1219. @code{%exception}.
  1220. @end deffn
  1221. @deffn {Scheme Procedure} exception-args exn
  1222. If @var{exn} is an exception created via
  1223. @code{make-exception-from-throw}, return the corresponding @var{args}
  1224. for the exception. Otherwise, unless @var{exn} is an exception of a
  1225. type with a known mapping to @code{throw}, return @code{(list @var{exn})}.
  1226. @end deffn
  1227. @node Exceptions and C
  1228. @subsubsection Exceptions and C
  1229. There are some specific versions of Guile's original @code{catch} and
  1230. @code{with-throw-handler} exception-handling primitives that are still
  1231. widely used in C code.
  1232. @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)
  1233. @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)
  1234. The above @code{scm_catch_with_pre_unwind_handler} and @code{scm_catch}
  1235. take Scheme procedures as body and handler arguments.
  1236. @code{scm_c_catch} and @code{scm_internal_catch} are equivalents taking
  1237. C functions.
  1238. @var{body} is called as @code{@var{body} (@var{body_data})} with a catch
  1239. on exceptions of the given @var{tag} type. If an exception is caught,
  1240. @var{pre_unwind_handler} and @var{handler} are called as
  1241. @code{@var{handler} (@var{handler_data}, @var{key}, @var{args})}.
  1242. @var{key} and @var{args} are the @code{SCM} key and argument list from
  1243. the @code{throw}.
  1244. @tpindex scm_t_catch_body
  1245. @tpindex scm_t_catch_handler
  1246. @var{body} and @var{handler} should have the following prototypes.
  1247. @code{scm_t_catch_body} and @code{scm_t_catch_handler} are pointer
  1248. typedefs for these.
  1249. @example
  1250. SCM body (void *data);
  1251. SCM handler (void *data, SCM key, SCM args);
  1252. @end example
  1253. The @var{body_data} and @var{handler_data} parameters are passed to
  1254. the respective calls so an application can communicate extra
  1255. information to those functions.
  1256. If the data consists of an @code{SCM} object, care should be taken that
  1257. it isn't garbage collected while still required. If the @code{SCM} is a
  1258. local C variable, one way to protect it is to pass a pointer to that
  1259. variable as the data parameter, since the C compiler will then know the
  1260. value must be held on the stack. Another way is to use
  1261. @code{scm_remember_upto_here_1} (@pxref{Foreign Object Memory
  1262. Management}).
  1263. @end deftypefn
  1264. @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)
  1265. The above @code{scm_with_throw_handler} takes Scheme procedures as body
  1266. (thunk) and handler arguments. @code{scm_c_with_throw_handler} is an
  1267. equivalent taking C functions. See @code{scm_c_catch}
  1268. (@pxref{Exceptions and C}) for a description of the parameters, the
  1269. behaviour however of course follows @code{with-throw-handler}.
  1270. @end deftypefn
  1271. @node Error Reporting
  1272. @subsection Procedures for Signaling Errors
  1273. Guile provides a set of convenience procedures for signaling error
  1274. conditions that are implemented on top of the exception primitives just
  1275. described.
  1276. @deffn {Scheme Procedure} error msg arg @dots{}
  1277. Raise an error with key @code{misc-error} and a message constructed by
  1278. displaying @var{msg} and writing @var{arg} @enddots{}.
  1279. @end deffn
  1280. @deffn {Scheme Procedure} scm-error key subr message args data
  1281. @deffnx {C Function} scm_error_scm (key, subr, message, args, data)
  1282. Raise an error with key @var{key}. @var{subr} can be a string
  1283. naming the procedure associated with the error, or @code{#f}.
  1284. @var{message} is the error message string, possibly containing
  1285. @code{~S} and @code{~A} escapes. When an error is reported,
  1286. these are replaced by formatting the corresponding members of
  1287. @var{args}: @code{~A} (was @code{%s} in older versions of
  1288. Guile) formats using @code{display} and @code{~S} (was
  1289. @code{%S}) formats using @code{write}. @var{data} is a list or
  1290. @code{#f} depending on @var{key}: if @var{key} is
  1291. @code{system-error} then it should be a list containing the
  1292. Unix @code{errno} value; If @var{key} is @code{signal} then it
  1293. should be a list containing the Unix signal number; If
  1294. @var{key} is @code{out-of-range}, @code{wrong-type-arg},
  1295. or @code{keyword-argument-error},
  1296. it is a list containing the bad value; otherwise
  1297. it will usually be @code{#f}.
  1298. @end deffn
  1299. @deffn {Scheme Procedure} strerror err
  1300. @deffnx {C Function} scm_strerror (err)
  1301. Return the Unix error message corresponding to @var{err}, an integer
  1302. @code{errno} value.
  1303. When @code{setlocale} has been called (@pxref{Locales}), the message
  1304. is in the language and charset of @code{LC_MESSAGES}. (This is done
  1305. by the C library.)
  1306. @end deffn
  1307. @c begin (scm-doc-string "boot-9.scm" "false-if-exception")
  1308. @deffn syntax false-if-exception expr
  1309. Returns the result of evaluating its argument; however
  1310. if an exception occurs then @code{#f} is returned instead.
  1311. @end deffn
  1312. @c end
  1313. @node Dynamic Wind
  1314. @subsection Dynamic Wind
  1315. For Scheme code, the fundamental procedure to react to non-local entry
  1316. and exits of dynamic contexts is @code{dynamic-wind}. C code could
  1317. use @code{scm_internal_dynamic_wind}, but since C does not allow the
  1318. convenient construction of anonymous procedures that close over
  1319. lexical variables, this will be, well, inconvenient.
  1320. Therefore, Guile offers the functions @code{scm_dynwind_begin} and
  1321. @code{scm_dynwind_end} to delimit a dynamic extent. Within this
  1322. dynamic extent, which is called a @dfn{dynwind context}, you can
  1323. perform various @dfn{dynwind actions} that control what happens when
  1324. the dynwind context is entered or left. For example, you can register
  1325. a cleanup routine with @code{scm_dynwind_unwind_handler} that is
  1326. executed when the context is left. There are several other more
  1327. specialized dynwind actions as well, for example to temporarily block
  1328. the execution of asyncs or to temporarily change the current output
  1329. port. They are described elsewhere in this manual.
  1330. Here is an example that shows how to prevent memory leaks.
  1331. @example
  1332. /* Suppose there is a function called FOO in some library that you
  1333. would like to make available to Scheme code (or to C code that
  1334. follows the Scheme conventions).
  1335. FOO takes two C strings and returns a new string. When an error has
  1336. occurred in FOO, it returns NULL.
  1337. */
  1338. char *foo (char *s1, char *s2);
  1339. /* SCM_FOO interfaces the C function FOO to the Scheme way of life.
  1340. It takes care to free up all temporary strings in the case of
  1341. non-local exits.
  1342. */
  1343. SCM
  1344. scm_foo (SCM s1, SCM s2)
  1345. @{
  1346. char *c_s1, *c_s2, *c_res;
  1347. scm_dynwind_begin (0);
  1348. c_s1 = scm_to_locale_string (s1);
  1349. /* Call 'free (c_s1)' when the dynwind context is left.
  1350. */
  1351. scm_dynwind_unwind_handler (free, c_s1, SCM_F_WIND_EXPLICITLY);
  1352. c_s2 = scm_to_locale_string (s2);
  1353. /* Same as above, but more concisely.
  1354. */
  1355. scm_dynwind_free (c_s2);
  1356. c_res = foo (c_s1, c_s2);
  1357. if (c_res == NULL)
  1358. scm_report_out_of_memory ();
  1359. scm_dynwind_end ();
  1360. return scm_take_locale_string (res);
  1361. @}
  1362. @end example
  1363. @rnindex dynamic-wind
  1364. @deffn {Scheme Procedure} dynamic-wind in_guard thunk out_guard
  1365. @deffnx {C Function} scm_dynamic_wind (in_guard, thunk, out_guard)
  1366. All three arguments must be 0-argument procedures.
  1367. @var{in_guard} is called, then @var{thunk}, then
  1368. @var{out_guard}.
  1369. If, any time during the execution of @var{thunk}, the
  1370. dynamic extent of the @code{dynamic-wind} expression is escaped
  1371. non-locally, @var{out_guard} is called. If the dynamic extent of
  1372. the dynamic-wind is re-entered, @var{in_guard} is called. Thus
  1373. @var{in_guard} and @var{out_guard} may be called any number of
  1374. times.
  1375. @lisp
  1376. (define x 'normal-binding)
  1377. @result{} x
  1378. (define a-cont
  1379. (call-with-current-continuation
  1380. (lambda (escape)
  1381. (let ((old-x x))
  1382. (dynamic-wind
  1383. ;; in-guard:
  1384. ;;
  1385. (lambda () (set! x 'special-binding))
  1386. ;; thunk
  1387. ;;
  1388. (lambda () (display x) (newline)
  1389. (call-with-current-continuation escape)
  1390. (display x) (newline)
  1391. x)
  1392. ;; out-guard:
  1393. ;;
  1394. (lambda () (set! x old-x)))))))
  1395. ;; Prints:
  1396. special-binding
  1397. ;; Evaluates to:
  1398. @result{} a-cont
  1399. x
  1400. @result{} normal-binding
  1401. (a-cont #f)
  1402. ;; Prints:
  1403. special-binding
  1404. ;; Evaluates to:
  1405. @result{} a-cont ;; the value of the (define a-cont...)
  1406. x
  1407. @result{} normal-binding
  1408. a-cont
  1409. @result{} special-binding
  1410. @end lisp
  1411. @end deffn
  1412. @deftp {C Type} scm_t_dynwind_flags
  1413. This is an enumeration of several flags that modify the behavior of
  1414. @code{scm_dynwind_begin}. The flags are listed in the following
  1415. table.
  1416. @table @code
  1417. @item SCM_F_DYNWIND_REWINDABLE
  1418. The dynamic context is @dfn{rewindable}. This means that it can be
  1419. reentered non-locally (via the invocation of a continuation). The
  1420. default is that a dynwind context can not be reentered non-locally.
  1421. @end table
  1422. @end deftp
  1423. @deftypefn {C Function} void scm_dynwind_begin (scm_t_dynwind_flags flags)
  1424. The function @code{scm_dynwind_begin} starts a new dynamic context and
  1425. makes it the `current' one.
  1426. The @var{flags} argument determines the default behavior of the
  1427. context. Normally, use 0. This will result in a context that can not
  1428. be reentered with a captured continuation. When you are prepared to
  1429. handle reentries, include @code{SCM_F_DYNWIND_REWINDABLE} in
  1430. @var{flags}.
  1431. Being prepared for reentry means that the effects of unwind handlers
  1432. can be undone on reentry. In the example above, we want to prevent a
  1433. memory leak on non-local exit and thus register an unwind handler that
  1434. frees the memory. But once the memory is freed, we can not get it
  1435. back on reentry. Thus reentry can not be allowed.
  1436. The consequence is that continuations become less useful when
  1437. non-reentrant contexts are captured, but you don't need to worry
  1438. about that too much.
  1439. The context is ended either implicitly when a non-local exit happens,
  1440. or explicitly with @code{scm_dynwind_end}. You must make sure that a
  1441. dynwind context is indeed ended properly. If you fail to call
  1442. @code{scm_dynwind_end} for each @code{scm_dynwind_begin}, the behavior
  1443. is undefined.
  1444. @end deftypefn
  1445. @deftypefn {C Function} void scm_dynwind_end ()
  1446. End the current dynamic context explicitly and make the previous one
  1447. current.
  1448. @end deftypefn
  1449. @deftp {C Type} scm_t_wind_flags
  1450. This is an enumeration of several flags that modify the behavior of
  1451. @code{scm_dynwind_unwind_handler} and
  1452. @code{scm_dynwind_rewind_handler}. The flags are listed in the
  1453. following table.
  1454. @table @code
  1455. @item SCM_F_WIND_EXPLICITLY
  1456. @vindex SCM_F_WIND_EXPLICITLY
  1457. The registered action is also carried out when the dynwind context is
  1458. entered or left locally.
  1459. @end table
  1460. @end deftp
  1461. @deftypefn {C Function} void scm_dynwind_unwind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
  1462. @deftypefnx {C Function} void scm_dynwind_unwind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
  1463. Arranges for @var{func} to be called with @var{data} as its arguments
  1464. when the current context ends implicitly. If @var{flags} contains
  1465. @code{SCM_F_WIND_EXPLICITLY}, @var{func} is also called when the
  1466. context ends explicitly with @code{scm_dynwind_end}.
  1467. The function @code{scm_dynwind_unwind_handler_with_scm} takes care that
  1468. @var{data} is protected from garbage collection.
  1469. @end deftypefn
  1470. @deftypefn {C Function} void scm_dynwind_rewind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
  1471. @deftypefnx {C Function} void scm_dynwind_rewind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
  1472. Arrange for @var{func} to be called with @var{data} as its argument when
  1473. the current context is restarted by rewinding the stack. When @var{flags}
  1474. contains @code{SCM_F_WIND_EXPLICITLY}, @var{func} is called immediately
  1475. as well.
  1476. The function @code{scm_dynwind_rewind_handler_with_scm} takes care that
  1477. @var{data} is protected from garbage collection.
  1478. @end deftypefn
  1479. @deftypefn {C Function} void scm_dynwind_free (void *mem)
  1480. Arrange for @var{mem} to be freed automatically whenever the current
  1481. context is exited, whether normally or non-locally.
  1482. @code{scm_dynwind_free (mem)} is an equivalent shorthand for
  1483. @code{scm_dynwind_unwind_handler (free, mem, SCM_F_WIND_EXPLICITLY)}.
  1484. @end deftypefn
  1485. @node Fluids and Dynamic States
  1486. @subsection Fluids and Dynamic States
  1487. @cindex fluids
  1488. A @emph{fluid} is a variable whose value is associated with the dynamic
  1489. extent of a function call. In the same way that an operating system
  1490. runs a process with a given set of current input and output ports (or
  1491. file descriptors), in Guile you can arrange to call a function while
  1492. binding a fluid to a particular value. That association between fluid
  1493. and value will exist during the dynamic extent of the function call.
  1494. Fluids are therefore a building block for implementing dynamically
  1495. scoped variables. Dynamically scoped variables are useful when you want
  1496. to set a variable to a value during some dynamic extent in the execution
  1497. of your program and have them revert to their original value when the
  1498. control flow is outside of this dynamic extent. See the description of
  1499. @code{with-fluids} below for details. This association between fluids,
  1500. values, and dynamic extents is robust to multiple entries (as when a
  1501. captured continuation is invoked more than once) and early exits (for
  1502. example, when throwing exceptions).
  1503. Guile uses fluids to implement parameters (@pxref{Parameters}). Usually
  1504. you just want to use parameters directly. However it can be useful to
  1505. know what a fluid is and how it works, so that's what this section is
  1506. about.
  1507. The current set of fluid-value associations can be captured in a
  1508. @emph{dynamic state} object. A dynamic extent is simply that: a
  1509. snapshot of the current fluid-value associations. Guile users can
  1510. capture the current dynamic state with @code{current-dynamic-state} and
  1511. restore it later via @code{with-dynamic-state} or similar procedures.
  1512. This facility is especially useful when implementing lightweight
  1513. thread-like abstractions.
  1514. New fluids are created with @code{make-fluid} and @code{fluid?} is
  1515. used for testing whether an object is actually a fluid. The values
  1516. stored in a fluid can be accessed with @code{fluid-ref} and
  1517. @code{fluid-set!}.
  1518. @xref{Thread Local Variables}, for further notes on fluids, threads,
  1519. parameters, and dynamic states.
  1520. @deffn {Scheme Procedure} make-fluid [dflt]
  1521. @deffnx {C Function} scm_make_fluid ()
  1522. @deffnx {C Function} scm_make_fluid_with_default (dflt)
  1523. Return a newly created fluid, whose initial value is @var{dflt}, or
  1524. @code{#f} if @var{dflt} is not given.
  1525. Fluids are objects that can hold one
  1526. value per dynamic state. That is, modifications to this value are
  1527. only visible to code that executes with the same dynamic state as
  1528. the modifying code. When a new dynamic state is constructed, it
  1529. inherits the values from its parent. Because each thread normally executes
  1530. with its own dynamic state, you can use fluids for thread local storage.
  1531. @end deffn
  1532. @deffn {Scheme Procedure} make-unbound-fluid
  1533. @deffnx {C Function} scm_make_unbound_fluid ()
  1534. Return a new fluid that is initially unbound (instead of being
  1535. implicitly bound to some definite value).
  1536. @end deffn
  1537. @deffn {Scheme Procedure} fluid? obj
  1538. @deffnx {C Function} scm_fluid_p (obj)
  1539. Return @code{#t} if @var{obj} is a fluid; otherwise, return
  1540. @code{#f}.
  1541. @end deffn
  1542. @deffn {Scheme Procedure} fluid-ref fluid
  1543. @deffnx {C Function} scm_fluid_ref (fluid)
  1544. Return the value associated with @var{fluid} in the current
  1545. dynamic root. If @var{fluid} has not been set, then return
  1546. its default value. Calling @code{fluid-ref} on an unbound fluid produces
  1547. a runtime error.
  1548. @end deffn
  1549. @deffn {Scheme Procedure} fluid-set! fluid value
  1550. @deffnx {C Function} scm_fluid_set_x (fluid, value)
  1551. Set the value associated with @var{fluid} in the current dynamic root.
  1552. @end deffn
  1553. @deffn {Scheme Procedure} fluid-ref* fluid depth
  1554. @deffnx {C Function} scm_fluid_ref_star (fluid, depth)
  1555. Return the @var{depth}th oldest value associated with @var{fluid} in the
  1556. current thread. If @var{depth} equals or exceeds the number of values
  1557. that have been assigned to @var{fluid}, return the default value of the
  1558. fluid. @code{(fluid-ref* f 0)} is equivalent to @code{(fluid-ref f)}.
  1559. @code{fluid-ref*} is useful when you want to maintain a stack-like
  1560. structure in a fluid, such as the stack of current exception handlers.
  1561. Using @code{fluid-ref*} instead of an explicit stack allows any partial
  1562. continuation captured by @code{call-with-prompt} to only capture the
  1563. bindings made within the limits of the prompt instead of the entire
  1564. continuation. @xref{Prompts}, for more on delimited continuations.
  1565. @end deffn
  1566. @deffn {Scheme Procedure} fluid-unset! fluid
  1567. @deffnx {C Function} scm_fluid_unset_x (fluid)
  1568. Disassociate the given fluid from any value, making it unbound.
  1569. @end deffn
  1570. @deffn {Scheme Procedure} fluid-bound? fluid
  1571. @deffnx {C Function} scm_fluid_bound_p (fluid)
  1572. Returns @code{#t} if the given fluid is bound to a value, otherwise
  1573. @code{#f}.
  1574. @end deffn
  1575. @code{with-fluids*} temporarily changes the values of one or more fluids,
  1576. so that the given procedure and each procedure called by it access the
  1577. given values. After the procedure returns, the old values are restored.
  1578. @deffn {Scheme Procedure} with-fluid* fluid value thunk
  1579. @deffnx {C Function} scm_with_fluid (fluid, value, thunk)
  1580. Set @var{fluid} to @var{value} temporarily, and call @var{thunk}.
  1581. @var{thunk} must be a procedure with no argument.
  1582. @end deffn
  1583. @deffn {Scheme Procedure} with-fluids* fluids values thunk
  1584. @deffnx {C Function} scm_with_fluids (fluids, values, thunk)
  1585. Set @var{fluids} to @var{values} temporary, and call @var{thunk}.
  1586. @var{fluids} must be a list of fluids and @var{values} must be the
  1587. same number of their values to be applied. Each substitution is done
  1588. in the order given. @var{thunk} must be a procedure with no argument.
  1589. It is called inside a @code{dynamic-wind} and the fluids are
  1590. set/restored when control enter or leaves the established dynamic
  1591. extent.
  1592. @end deffn
  1593. @deffn {Scheme Macro} with-fluids ((fluid value) @dots{}) body1 body2 @dots{}
  1594. Execute body @var{body1} @var{body2} @dots{} while each @var{fluid} is
  1595. set to the corresponding @var{value}. Both @var{fluid} and @var{value}
  1596. are evaluated and @var{fluid} must yield a fluid. The body is executed
  1597. inside a @code{dynamic-wind} and the fluids are set/restored when
  1598. control enter or leaves the established dynamic extent.
  1599. @end deffn
  1600. @deftypefn {C Function} SCM scm_c_with_fluids (SCM fluids, SCM vals, SCM (*cproc)(void *), void *data)
  1601. @deftypefnx {C Function} SCM scm_c_with_fluid (SCM fluid, SCM val, SCM (*cproc)(void *), void *data)
  1602. The function @code{scm_c_with_fluids} is like @code{scm_with_fluids}
  1603. except that it takes a C function to call instead of a Scheme thunk.
  1604. The function @code{scm_c_with_fluid} is similar but only allows one
  1605. fluid to be set instead of a list.
  1606. @end deftypefn
  1607. @deftypefn {C Function} void scm_dynwind_fluid (SCM fluid, SCM val)
  1608. This function must be used inside a pair of calls to
  1609. @code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
  1610. Wind}). During the dynwind context, the fluid @var{fluid} is set to
  1611. @var{val}.
  1612. More precisely, the value of the fluid is swapped with a `backup'
  1613. value whenever the dynwind context is entered or left. The backup
  1614. value is initialized with the @var{val} argument.
  1615. @end deftypefn
  1616. @deffn {Scheme Procedure} dynamic-state? obj
  1617. @deffnx {C Function} scm_dynamic_state_p (obj)
  1618. Return @code{#t} if @var{obj} is a dynamic state object;
  1619. return @code{#f} otherwise.
  1620. @end deffn
  1621. @deftypefn {C Procedure} int scm_is_dynamic_state (SCM obj)
  1622. Return non-zero if @var{obj} is a dynamic state object;
  1623. return zero otherwise.
  1624. @end deftypefn
  1625. @deffn {Scheme Procedure} current-dynamic-state
  1626. @deffnx {C Function} scm_current_dynamic_state ()
  1627. Return a snapshot of the current fluid-value associations as a fresh
  1628. dynamic state object.
  1629. @end deffn
  1630. @deffn {Scheme Procedure} set-current-dynamic-state state
  1631. @deffnx {C Function} scm_set_current_dynamic_state (state)
  1632. Restore the saved fluid-value associations from @var{state}, replacing
  1633. the current fluid-value associations. Return the current fluid-value
  1634. associatoins as a dynamic state object, as in
  1635. @code{current-dynamic-state}.
  1636. @end deffn
  1637. @deffn {Scheme Procedure} with-dynamic-state state proc
  1638. @deffnx {C Function} scm_with_dynamic_state (state, proc)
  1639. Call @var{proc} while the fluid bindings from @var{state} have been made
  1640. current, saving the current fluid bindings. When control leaves the
  1641. invocation of @var{proc}, restore the saved bindings, saving instead the
  1642. fluid bindings from inside the call. If control later re-enters
  1643. @var{proc}, restore those saved bindings, saving the current bindings,
  1644. and so on.
  1645. @end deffn
  1646. @deftypefn {C Procedure} void scm_dynwind_current_dynamic_state (SCM state)
  1647. Set the current dynamic state to @var{state} for the current dynwind
  1648. context. Like @code{with-dynamic-state}, but in terms of Guile's
  1649. ``dynwind'' C API.
  1650. @end deftypefn
  1651. @deftypefn {C Procedure} {void *} scm_c_with_dynamic_state (SCM state, void *(*func)(void *), void *data)
  1652. Like @code{scm_with_dynamic_state}, but call @var{func} with
  1653. @var{data}.
  1654. @end deftypefn
  1655. @node Parameters
  1656. @subsection Parameters
  1657. @cindex SRFI-39
  1658. @cindex parameter object
  1659. @tindex Parameter
  1660. Parameters are Guile's facility for dynamically bound variables.
  1661. On the most basic level, a parameter object is a procedure. Calling it
  1662. with no arguments returns its value. Calling it with one argument sets
  1663. the value.
  1664. @example
  1665. (define my-param (make-parameter 123))
  1666. (my-param) @result{} 123
  1667. (my-param 456)
  1668. (my-param) @result{} 456
  1669. @end example
  1670. The @code{parameterize} special form establishes new locations for
  1671. parameters, those new locations having effect within the dynamic extent
  1672. of the @code{parameterize} body. Leaving restores the previous
  1673. locations. Re-entering (through a saved continuation) will again use
  1674. the new locations.
  1675. @example
  1676. (parameterize ((my-param 789))
  1677. (my-param)) @result{} 789
  1678. (my-param) @result{} 456
  1679. @end example
  1680. Parameters are like dynamically bound variables in other Lisp dialects.
  1681. They allow an application to establish parameter settings (as the name
  1682. suggests) just for the execution of a particular bit of code, restoring
  1683. when done. Examples of such parameters might be case-sensitivity for a
  1684. search, or a prompt for user input.
  1685. Global variables are not as good as parameter objects for this sort of
  1686. thing. Changes to them are visible to all threads, but in Guile
  1687. parameter object locations are per-thread, thereby truly limiting the
  1688. effect of @code{parameterize} to just its dynamic execution.
  1689. Passing arguments to functions is thread-safe, but that soon becomes
  1690. tedious when there's more than a few or when they need to pass down
  1691. through several layers of calls before reaching the point they should
  1692. affect. Introducing a new setting to existing code is often easier with
  1693. a parameter object than adding arguments.
  1694. @deffn {Scheme Procedure} make-parameter init [converter]
  1695. Return a new parameter object, with initial value @var{init}.
  1696. If a @var{converter} is given, then a call @code{(@var{converter}
  1697. val)} is made for each value set, its return is the value stored.
  1698. Such a call is made for the @var{init} initial value too.
  1699. A @var{converter} allows values to be validated, or put into a
  1700. canonical form. For example,
  1701. @example
  1702. (define my-param (make-parameter 123
  1703. (lambda (val)
  1704. (if (not (number? val))
  1705. (error "must be a number"))
  1706. (inexact->exact val))))
  1707. (my-param 0.75)
  1708. (my-param) @result{} 3/4
  1709. @end example
  1710. @end deffn
  1711. @deffn {library syntax} parameterize ((param value) @dots{}) body1 body2 @dots{}
  1712. Establish a new dynamic scope with the given @var{param}s bound to new
  1713. locations and set to the given @var{value}s. @var{body1} @var{body2}
  1714. @dots{} is evaluated in that environment. The value returned is that of
  1715. last body form.
  1716. Each @var{param} is an expression which is evaluated to get the
  1717. parameter object. Often this will just be the name of a variable
  1718. holding the object, but it can be anything that evaluates to a
  1719. parameter.
  1720. The @var{param} expressions and @var{value} expressions are all
  1721. evaluated before establishing the new dynamic bindings, and they're
  1722. evaluated in an unspecified order.
  1723. For example,
  1724. @example
  1725. (define prompt (make-parameter "Type something: "))
  1726. (define (get-input)
  1727. (display (prompt))
  1728. ...)
  1729. (parameterize ((prompt "Type a number: "))
  1730. (get-input)
  1731. ...)
  1732. @end example
  1733. @end deffn
  1734. Parameter objects are implemented using fluids (@pxref{Fluids and
  1735. Dynamic States}), so each dynamic state has its own parameter
  1736. locations. That includes the separate locations when outside any
  1737. @code{parameterize} form. When a parameter is created it gets a
  1738. separate initial location in each dynamic state, all initialized to the
  1739. given @var{init} value.
  1740. New code should probably just use parameters instead of fluids, because
  1741. the interface is better. But for migrating old code or otherwise
  1742. providing interoperability, Guile provides the @code{fluid->parameter}
  1743. procedure:
  1744. @deffn {Scheme Procedure} fluid->parameter fluid [conv]
  1745. Make a parameter that wraps a fluid.
  1746. The value of the parameter will be the same as the value of the fluid.
  1747. If the parameter is rebound in some dynamic extent, perhaps via
  1748. @code{parameterize}, the new value will be run through the optional
  1749. @var{conv} procedure, as with any parameter. Note that unlike
  1750. @code{make-parameter}, @var{conv} is not applied to the initial value.
  1751. @end deffn
  1752. As alluded to above, because each thread usually has a separate dynamic
  1753. state, each thread has its own locations behind parameter objects, and
  1754. changes in one thread are not visible to any other. When a new dynamic
  1755. state or thread is created, the values of parameters in the originating
  1756. context are copied, into new locations.
  1757. @cindex SRFI-39
  1758. Guile's parameters conform to SRFI-39 (@pxref{SRFI-39}).
  1759. @node Handling Errors
  1760. @subsection How to Handle Errors
  1761. Guile is currently in a transition from its historical @code{catch} and
  1762. @code{throw} error handling and signaling operators to the new
  1763. structured exception facility; @xref{Exceptions}. However in the
  1764. meantime, here is some documentation on errors and the older
  1765. @code{catch} and @code{throw} interface.
  1766. Errors are always thrown with a @var{key} and four arguments:
  1767. @itemize @bullet
  1768. @item
  1769. @var{key}: a symbol which indicates the type of error. The symbols used
  1770. by libguile are listed below.
  1771. @item
  1772. @var{subr}: the name of the procedure from which the error is thrown, or
  1773. @code{#f}.
  1774. @item
  1775. @var{message}: a string (possibly language and system dependent)
  1776. describing the error. The tokens @code{~A} and @code{~S} can be
  1777. embedded within the message: they will be replaced with members of the
  1778. @var{args} list when the message is printed. @code{~A} indicates an
  1779. argument printed using @code{display}, while @code{~S} indicates an
  1780. argument printed using @code{write}. @var{message} can also be
  1781. @code{#f}, to allow it to be derived from the @var{key} by the error
  1782. handler (may be useful if the @var{key} is to be thrown from both C and
  1783. Scheme).
  1784. @item
  1785. @var{args}: a list of arguments to be used to expand @code{~A} and
  1786. @code{~S} tokens in @var{message}. Can also be @code{#f} if no
  1787. arguments are required.
  1788. @item
  1789. @var{rest}: a list of any additional objects required. e.g., when the
  1790. key is @code{'system-error}, this contains the C errno value. Can also
  1791. be @code{#f} if no additional objects are required.
  1792. @end itemize
  1793. In addition to @code{catch} and @code{throw}, the following Scheme
  1794. facilities are available:
  1795. @deffn {Scheme Procedure} display-error frame port subr message args rest
  1796. @deffnx {C Function} scm_display_error (frame, port, subr, message, args, rest)
  1797. Display an error message to the output port @var{port}.
  1798. @var{frame} is the frame in which the error occurred, @var{subr} is
  1799. the name of the procedure in which the error occurred and
  1800. @var{message} is the actual error message, which may contain
  1801. formatting instructions. These will format the arguments in
  1802. the list @var{args} accordingly. @var{rest} is currently
  1803. ignored.
  1804. @end deffn
  1805. The following are the error keys defined by libguile and the situations
  1806. in which they are used:
  1807. @itemize @bullet
  1808. @item
  1809. @cindex @code{error-signal}
  1810. @code{error-signal}: thrown after receiving an unhandled fatal signal
  1811. such as SIGSEGV, SIGBUS, SIGFPE etc. The @var{rest} argument in the throw
  1812. contains the coded signal number (at present this is not the same as the
  1813. usual Unix signal number).
  1814. @item
  1815. @cindex @code{system-error}
  1816. @code{system-error}: thrown after the operating system indicates an
  1817. error condition. The @var{rest} argument in the throw contains the
  1818. errno value.
  1819. @item
  1820. @cindex @code{numerical-overflow}
  1821. @code{numerical-overflow}: numerical overflow.
  1822. @item
  1823. @cindex @code{out-of-range}
  1824. @code{out-of-range}: the arguments to a procedure do not fall within the
  1825. accepted domain.
  1826. @item
  1827. @cindex @code{wrong-type-arg}
  1828. @code{wrong-type-arg}: an argument to a procedure has the wrong type.
  1829. @item
  1830. @cindex @code{wrong-number-of-args}
  1831. @code{wrong-number-of-args}: a procedure was called with the wrong number
  1832. of arguments.
  1833. @item
  1834. @cindex @code{memory-allocation-error}
  1835. @code{memory-allocation-error}: memory allocation error.
  1836. @item
  1837. @cindex @code{stack-overflow}
  1838. @code{stack-overflow}: stack overflow error.
  1839. @item
  1840. @cindex @code{regular-expression-syntax}
  1841. @code{regular-expression-syntax}: errors generated by the regular
  1842. expression library.
  1843. @item
  1844. @cindex @code{misc-error}
  1845. @code{misc-error}: other errors.
  1846. @end itemize
  1847. @subsubsection C Support
  1848. In the following C functions, @var{SUBR} and @var{MESSAGE} parameters
  1849. can be @code{NULL} to give the effect of @code{#f} described above.
  1850. @deftypefn {C Function} SCM scm_error (SCM @var{key}, char *@var{subr}, char *@var{message}, SCM @var{args}, SCM @var{rest})
  1851. Throw an error, as per @code{scm-error} (@pxref{Error Reporting}).
  1852. @end deftypefn
  1853. @deftypefn {C Function} void scm_syserror (char *@var{subr})
  1854. @deftypefnx {C Function} void scm_syserror_msg (char *@var{subr}, char *@var{message}, SCM @var{args})
  1855. Throw an error with key @code{system-error} and supply @code{errno} in
  1856. the @var{rest} argument. For @code{scm_syserror} the message is
  1857. generated using @code{strerror}.
  1858. Care should be taken that any code in between the failing operation
  1859. and the call to these routines doesn't change @code{errno}.
  1860. @end deftypefn
  1861. @deftypefn {C Function} void scm_num_overflow (char *@var{subr})
  1862. @deftypefnx {C Function} void scm_out_of_range (char *@var{subr}, SCM @var{bad_value})
  1863. @deftypefnx {C Function} void scm_wrong_num_args (SCM @var{proc})
  1864. @deftypefnx {C Function} void scm_wrong_type_arg (char *@var{subr}, int @var{argnum}, SCM @var{bad_value})
  1865. @deftypefnx {C Function} void scm_wrong_type_arg_msg (char *@var{subr}, int @var{argnum}, SCM @var{bad_value}, const char *@var{expected})
  1866. @deftypefnx {C Function} void scm_misc_error (const char *@var{subr}, const char *@var{message}, SCM @var{args})
  1867. Throw an error with the various keys described above.
  1868. In @code{scm_wrong_num_args}, @var{proc} should be a Scheme symbol
  1869. which is the name of the procedure incorrectly invoked. The other
  1870. routines take the name of the invoked procedure as a C string.
  1871. In @code{scm_wrong_type_arg_msg}, @var{expected} is a C string
  1872. describing the type of argument that was expected.
  1873. In @code{scm_misc_error}, @var{message} is the error message string,
  1874. possibly containing @code{simple-format} escapes (@pxref{Simple
  1875. Output}), and the corresponding arguments in the @var{args} list.
  1876. @end deftypefn
  1877. @subsubsection Signalling Type Errors
  1878. Every function visible at the Scheme level should aggressively check the
  1879. types of its arguments, to avoid misinterpreting a value, and perhaps
  1880. causing a segmentation fault. Guile provides some macros to make this
  1881. easier.
  1882. @deftypefn Macro void SCM_ASSERT (int @var{test}, SCM @var{obj}, unsigned int @var{position}, const char *@var{subr})
  1883. @deftypefnx Macro void SCM_ASSERT_TYPE (int @var{test}, SCM @var{obj}, unsigned int @var{position}, const char *@var{subr}, const char *@var{expected})
  1884. If @var{test} is zero, signal a ``wrong type argument'' error,
  1885. attributed to the subroutine named @var{subr}, operating on the value
  1886. @var{obj}, which is the @var{position}'th argument of @var{subr}.
  1887. In @code{SCM_ASSERT_TYPE}, @var{expected} is a C string describing the
  1888. type of argument that was expected.
  1889. @end deftypefn
  1890. @deftypefn Macro int SCM_ARG1
  1891. @deftypefnx Macro int SCM_ARG2
  1892. @deftypefnx Macro int SCM_ARG3
  1893. @deftypefnx Macro int SCM_ARG4
  1894. @deftypefnx Macro int SCM_ARG5
  1895. @deftypefnx Macro int SCM_ARG6
  1896. @deftypefnx Macro int SCM_ARG7
  1897. One of the above values can be used for @var{position} to indicate the
  1898. number of the argument of @var{subr} which is being checked.
  1899. Alternatively, a positive integer number can be used, which allows to
  1900. check arguments after the seventh. However, for parameter numbers up to
  1901. seven it is preferable to use @code{SCM_ARGN} instead of the
  1902. corresponding raw number, since it will make the code easier to
  1903. understand.
  1904. @end deftypefn
  1905. @deftypefn Macro int SCM_ARGn
  1906. Passing a value of zero or @code{SCM_ARGn} for @var{position} allows to
  1907. leave it unspecified which argument's type is incorrect. Again,
  1908. @code{SCM_ARGn} should be preferred over a raw zero constant.
  1909. @end deftypefn
  1910. @node Continuation Barriers
  1911. @subsection Continuation Barriers
  1912. The non-local flow of control caused by continuations might sometimes
  1913. not be wanted. You can use @code{with-continuation-barrier} to erect
  1914. fences that continuations can not pass.
  1915. @deffn {Scheme Procedure} with-continuation-barrier proc
  1916. @deffnx {C Function} scm_with_continuation_barrier (proc)
  1917. Call @var{proc} and return its result. Do not allow the invocation of
  1918. continuations that would leave or enter the dynamic extent of the call
  1919. to @code{with-continuation-barrier}. Such an attempt causes an error
  1920. to be signaled.
  1921. Throws (such as errors) that are not caught from within @var{proc} are
  1922. caught by @code{with-continuation-barrier}. In that case, a short
  1923. message is printed to the current error port and @code{#f} is returned.
  1924. Thus, @code{with-continuation-barrier} returns exactly once.
  1925. @end deffn
  1926. @deftypefn {C Function} {void *} scm_c_with_continuation_barrier (void *(*func) (void *), void *data)
  1927. Like @code{scm_with_continuation_barrier} but call @var{func} on
  1928. @var{data}. When an error is caught, @code{NULL} is returned.
  1929. @end deftypefn
  1930. @c Local Variables:
  1931. @c TeX-master: "guile.texi"
  1932. @c End: