api-evaluation.texi 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682
  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, 2005, 2006, 2009,
  4. @c 2010, 2011, 2012, 2013, 2014, 2020, 2021 Free Software Foundation, Inc.
  5. @c See the file guile.texi for copying conditions.
  6. @node Read/Load/Eval/Compile
  7. @section Reading and Evaluating Scheme Code
  8. This chapter describes Guile functions that are concerned with reading,
  9. loading, evaluating, and compiling Scheme code at run time.
  10. @menu
  11. * Scheme Syntax:: Standard and extended Scheme syntax.
  12. * Scheme Read:: Reading Scheme code.
  13. * Annotated Scheme Read:: Reading Scheme code, for the compiler.
  14. * Scheme Write:: Writing Scheme values to a port.
  15. * Fly Evaluation:: Procedures for on the fly evaluation.
  16. * Compilation:: How to compile Scheme files and procedures.
  17. * Loading:: Loading Scheme code from file.
  18. * Load Paths:: Where Guile looks for code.
  19. * Character Encoding of Source Files:: Loading non-ASCII Scheme code from file.
  20. * Delayed Evaluation:: Postponing evaluation until it is needed.
  21. * Local Evaluation:: Evaluation in a local lexical environment.
  22. * Local Inclusion:: Compile-time inclusion of one file in another.
  23. * Sandboxed Evaluation:: Evaluation with limited capabilities.
  24. * REPL Servers:: Serving a REPL over a socket.
  25. * Cooperative REPL Servers:: REPL server for single-threaded applications.
  26. @end menu
  27. @node Scheme Syntax
  28. @subsection Scheme Syntax: Standard and Guile Extensions
  29. @menu
  30. * Expression Syntax::
  31. * Comments::
  32. * Block Comments::
  33. * Case Sensitivity::
  34. * Keyword Syntax::
  35. * Reader Extensions::
  36. @end menu
  37. @node Expression Syntax
  38. @subsubsection Expression Syntax
  39. An expression to be evaluated takes one of the following forms.
  40. @table @nicode
  41. @item @var{symbol}
  42. A symbol is evaluated by dereferencing. A binding of that symbol is
  43. sought and the value there used. For example,
  44. @example
  45. (define x 123)
  46. x @result{} 123
  47. @end example
  48. @item (@var{proc} @var{args}@dots{})
  49. A parenthesized expression is a function call. @var{proc} and each
  50. argument are evaluated, then the function (which @var{proc} evaluated
  51. to) is called with those arguments.
  52. The order in which @var{proc} and the arguments are evaluated is
  53. unspecified, so be careful when using expressions with side effects.
  54. @example
  55. (max 1 2 3) @result{} 3
  56. (define (get-some-proc) min)
  57. ((get-some-proc) 1 2 3) @result{} 1
  58. @end example
  59. The same sort of parenthesized form is used for a macro invocation,
  60. but in that case the arguments are not evaluated. See the
  61. descriptions of macros for more on this (@pxref{Macros}, and
  62. @pxref{Syntax Rules}).
  63. @item @var{constant}
  64. Number, string, character and boolean constants evaluate ``to
  65. themselves'', so can appear as literals.
  66. @example
  67. 123 @result{} 123
  68. 99.9 @result{} 99.9
  69. "hello" @result{} "hello"
  70. #\z @result{} #\z
  71. #t @result{} #t
  72. @end example
  73. Note that an application must not attempt to modify literal strings,
  74. since they may be in read-only memory.
  75. @item (quote @var{data})
  76. @itemx '@var{data}
  77. @findex quote
  78. @findex '
  79. Quoting is used to obtain a literal symbol (instead of a variable
  80. reference), a literal list (instead of a function call), or a literal
  81. vector. @nicode{'} is simply a shorthand for a @code{quote} form.
  82. For example,
  83. @example
  84. 'x @result{} x
  85. '(1 2 3) @result{} (1 2 3)
  86. '#(1 (2 3) 4) @result{} #(1 (2 3) 4)
  87. (quote x) @result{} x
  88. (quote (1 2 3)) @result{} (1 2 3)
  89. (quote #(1 (2 3) 4)) @result{} #(1 (2 3) 4)
  90. @end example
  91. Note that an application must not attempt to modify literal lists or
  92. vectors obtained from a @code{quote} form, since they may be in
  93. read-only memory.
  94. @item (quasiquote @var{data})
  95. @itemx `@var{data}
  96. @findex quasiquote
  97. @findex `
  98. Backquote quasi-quotation is like @code{quote}, but selected
  99. sub-expressions are evaluated. This is a convenient way to construct
  100. a list or vector structure most of which is constant, but at certain
  101. points should have expressions substituted.
  102. The same effect can always be had with suitable @code{list},
  103. @code{cons} or @code{vector} calls, but quasi-quoting is often easier.
  104. @table @nicode
  105. @item (unquote @var{expr})
  106. @itemx ,@var{expr}
  107. @findex unquote
  108. @findex ,
  109. Within the quasiquote @var{data}, @code{unquote} or @code{,} indicates
  110. an expression to be evaluated and inserted. The comma syntax @code{,}
  111. is simply a shorthand for an @code{unquote} form. For example,
  112. @example
  113. `(1 2 (* 9 9) 3 4) @result{} (1 2 (* 9 9) 3 4)
  114. `(1 2 ,(* 9 9) 3 4) @result{} (1 2 81 3 4)
  115. `(1 (unquote (+ 1 1)) 3) @result{} (1 2 3)
  116. `#(1 ,(/ 12 2)) @result{} #(1 6)
  117. @end example
  118. @item (unquote-splicing @var{expr})
  119. @itemx ,@@@var{expr}
  120. @findex unquote-splicing
  121. @findex ,@@
  122. Within the quasiquote @var{data}, @code{unquote-splicing} or
  123. @code{,@@} indicates an expression to be evaluated and the elements of
  124. the returned list inserted. @var{expr} must evaluate to a list. The
  125. ``comma-at'' syntax @code{,@@} is simply a shorthand for an
  126. @code{unquote-splicing} form.
  127. @example
  128. (define x '(2 3))
  129. `(1 ,x 4) @result{} (1 (2 3) 4)
  130. `(1 ,@@x 4) @result{} (1 2 3 4)
  131. `(1 (unquote-splicing (map 1+ x))) @result{} (1 3 4)
  132. `#(9 ,@@x 9) @result{} #(9 2 3 9)
  133. @end example
  134. Notice @code{,@@} differs from plain @code{,} in the way one level of
  135. nesting is stripped. For @code{,@@} the elements of a returned list
  136. are inserted, whereas with @code{,} it would be the list itself
  137. inserted.
  138. @end table
  139. @c
  140. @c FIXME: What can we say about the mutability of a quasiquote
  141. @c result? R5RS doesn't seem to specify anything, though where it
  142. @c says backquote without commas is the same as plain quote then
  143. @c presumably the "fixed" portions of a quasiquote expression must be
  144. @c treated as immutable.
  145. @c
  146. @end table
  147. @node Comments
  148. @subsubsection Comments
  149. @c FIXME::martin: Review me!
  150. Comments in Scheme source files are written by starting them with a
  151. semicolon character (@code{;}). The comment then reaches up to the end
  152. of the line. Comments can begin at any column, and the may be inserted
  153. on the same line as Scheme code.
  154. @lisp
  155. ; Comment
  156. ;; Comment too
  157. (define x 1) ; Comment after expression
  158. (let ((y 1))
  159. ;; Display something.
  160. (display y)
  161. ;;; Comment at left margin.
  162. (display (+ y 1)))
  163. @end lisp
  164. It is common to use a single semicolon for comments following
  165. expressions on a line, to use two semicolons for comments which are
  166. indented like code, and three semicolons for comments which start at
  167. column 0, even if they are inside an indented code block. This
  168. convention is used when indenting code in Emacs' Scheme mode.
  169. @node Block Comments
  170. @subsubsection Block Comments
  171. @cindex multiline comments
  172. @cindex block comments
  173. @cindex #!
  174. @cindex !#
  175. @c FIXME::martin: Review me!
  176. In addition to the standard line comments defined by R5RS, Guile has
  177. another comment type for multiline comments, called @dfn{block
  178. comments}. This type of comment begins with the character sequence
  179. @code{#!} and ends with the characters @code{!#}.
  180. These comments are compatible with the block
  181. comments in the Scheme Shell @file{scsh} (@pxref{The Scheme shell
  182. (scsh)}). The characters @code{#!} were chosen because they are the
  183. magic characters used in shell scripts for indicating that the name of
  184. the program for executing the script follows on the same line.
  185. Thus a Guile script often starts like this.
  186. @lisp
  187. #! /usr/local/bin/guile -s
  188. !#
  189. @end lisp
  190. More details on Guile scripting can be found in the scripting section
  191. (@pxref{Guile Scripting}).
  192. @cindex R6RS block comments
  193. @cindex SRFI-30 block comments
  194. Similarly, Guile (starting from version 2.0) supports nested block
  195. comments as specified by R6RS and
  196. @url{http://srfi.schemers.org/srfi-30/srfi-30.html, SRFI-30}:
  197. @lisp
  198. (+ 1 #| this is a #| nested |# block comment |# 2)
  199. @result{} 3
  200. @end lisp
  201. For backward compatibility, this syntax can be overridden with
  202. @code{read-hash-extend} (@pxref{Reader Extensions,
  203. @code{read-hash-extend}}).
  204. There is one special case where the contents of a comment can actually
  205. affect the interpretation of code. When a character encoding
  206. declaration, such as @code{coding: utf-8} appears in one of the first
  207. few lines of a source file, it indicates to Guile's default reader
  208. that this source code file is not ASCII. For details see @ref{Character
  209. Encoding of Source Files}.
  210. @node Case Sensitivity
  211. @subsubsection Case Sensitivity
  212. @cindex fold-case
  213. @cindex no-fold-case
  214. @c FIXME::martin: Review me!
  215. Scheme as defined in R5RS is not case sensitive when reading symbols.
  216. Guile, on the contrary is case sensitive by default, so the identifiers
  217. @lisp
  218. guile-whuzzy
  219. Guile-Whuzzy
  220. @end lisp
  221. are the same in R5RS Scheme, but are different in Guile.
  222. It is possible to turn off case sensitivity in Guile by setting the
  223. reader option @code{case-insensitive}. For more information on reader
  224. options, @xref{Scheme Read}.
  225. @lisp
  226. (read-enable 'case-insensitive)
  227. @end lisp
  228. It is also possible to disable (or enable) case sensitivity within a
  229. single file by placing the reader directives @code{#!fold-case} (or
  230. @code{#!no-fold-case}) within the file itself.
  231. @node Keyword Syntax
  232. @subsubsection Keyword Syntax
  233. @node Reader Extensions
  234. @subsubsection Reader Extensions
  235. @deffn {Scheme Procedure} read-hash-extend chr proc
  236. @deffnx {C Function} scm_read_hash_extend (chr, proc)
  237. Install the procedure @var{proc} for reading expressions
  238. starting with the character sequence @code{#} and @var{chr}.
  239. @var{proc} will be called with two arguments: the character
  240. @var{chr} and the port to read further data from. The object
  241. returned will be the return value of @code{read}.
  242. Passing @code{#f} for @var{proc} will remove a previous setting.
  243. @end deffn
  244. @node Scheme Read
  245. @subsection Reading Scheme Code
  246. @rnindex read
  247. @deffn {Scheme Procedure} read [port]
  248. @deffnx {C Function} scm_read (port)
  249. Read an s-expression from the input port @var{port}, or from
  250. the current input port if @var{port} is not specified.
  251. Any whitespace before the next token is discarded.
  252. @end deffn
  253. The behavior of Guile's Scheme reader can be modified by manipulating
  254. its read options.
  255. @cindex options - read
  256. @cindex read options
  257. @deffn {Scheme Procedure} read-options [setting]
  258. Display the current settings of the global read options. If
  259. @var{setting} is omitted, only a short form of the current read options
  260. is printed. Otherwise if @var{setting} is the symbol @code{help}, a
  261. complete options description is displayed.
  262. @end deffn
  263. The set of available options, and their default values, may be had by
  264. invoking @code{read-options} at the prompt.
  265. @smalllisp
  266. scheme@@(guile-user)> (read-options)
  267. (square-brackets keywords #f positions)
  268. scheme@@(guile-user)> (read-options 'help)
  269. positions yes Record positions of source code expressions.
  270. case-insensitive no Convert symbols to lower case.
  271. keywords #f Style of keyword recognition: #f, 'prefix or 'postfix.
  272. r6rs-hex-escapes no Use R6RS variable-length character and string hex escapes.
  273. square-brackets yes Treat `[' and `]' as parentheses, for R6RS compatibility.
  274. hungry-eol-escapes no In strings, consume leading whitespace after an
  275. escaped end-of-line.
  276. curly-infix no Support SRFI-105 curly infix expressions.
  277. r7rs-symbols no Support R7RS |...| symbol notation.
  278. @end smalllisp
  279. Note that Guile also includes a preliminary mechanism for setting read
  280. options on a per-port basis. For instance, the @code{case-insensitive}
  281. read option is set (or unset) on the port when the reader encounters the
  282. @code{#!fold-case} or @code{#!no-fold-case} reader directives.
  283. Similarly, the @code{#!curly-infix} reader directive sets the
  284. @code{curly-infix} read option on the port, and
  285. @code{#!curly-infix-and-bracket-lists} sets @code{curly-infix} and
  286. unsets @code{square-brackets} on the port (@pxref{SRFI-105}). There is
  287. currently no other way to access or set the per-port read options.
  288. The boolean options may be toggled with @code{read-enable} and
  289. @code{read-disable}. The non-boolean @code{keywords} option must be set
  290. using @code{read-set!}.
  291. @deffn {Scheme Procedure} read-enable option-name
  292. @deffnx {Scheme Procedure} read-disable option-name
  293. @deffnx {Scheme Syntax} read-set! option-name value
  294. Modify the read options. @code{read-enable} should be used with boolean
  295. options and switches them on, @code{read-disable} switches them off.
  296. @code{read-set!} can be used to set an option to a specific value. Due
  297. to historical oddities, it is a macro that expects an unquoted option
  298. name.
  299. @end deffn
  300. For example, to make @code{read} fold all symbols to their lower case
  301. (perhaps for compatibility with older Scheme code), you can enter:
  302. @lisp
  303. (read-enable 'case-insensitive)
  304. @end lisp
  305. For more information on the effect of the @code{r6rs-hex-escapes} and
  306. @code{hungry-eol-escapes} options, see (@pxref{String Syntax}).
  307. For more information on the @code{r7rs-symbols} option, see
  308. (@pxref{Symbol Read Syntax}).
  309. @node Annotated Scheme Read
  310. @subsection Reading Scheme Code, For the Compiler
  311. When something goes wrong with a Scheme program, the user will want to
  312. know how to fix it. This starts with identifying where the error
  313. occurred: we want to associate a source location with each component part
  314. of source code, and propagate that source location information through
  315. to the compiler or interpreter.
  316. For that, Guile provides @code{read-syntax}.
  317. @deffn {Scheme Procedure} read-syntax [port]
  318. Read an s-expression from the input port @var{port}, or from the current
  319. input port if @var{port} is not specified.
  320. If, after skipping white space and comments, no more bytes are available
  321. from @var{port}, return the end-of-file object. @xref{Binary I/O}.
  322. Otherwise, return an annotated datum. An annotated datum is a syntax
  323. object which associates a source location with a datum. For example:
  324. @example
  325. (call-with-input-string " foo" read-syntax)
  326. ; @result{} #<syntax:unknown file:1:2 foo>
  327. (call-with-input-string "(foo)" read-syntax)
  328. ; @result{}
  329. ; #<syntax:unknown file:1:0
  330. ; (#<syntax unknown file:1:1 foo>)>
  331. @end example
  332. As the second example shows, all fields of pairs and vectors are also
  333. annotated, recursively.
  334. @end deffn
  335. Most users are familiar with syntax objects in the context of macros,
  336. which use syntax objects to associate scope information with
  337. identifiers. @xref{Macros}. Here we use syntax objects to associate
  338. source location information with any datum, but without attaching scope
  339. information. The Scheme compiler (@code{compile}) and the interpreter
  340. (@code{eval}) can accept syntax objects directly as input, allowing them
  341. to associate source information with resulting code.
  342. @xref{Compilation}, and @xref{Fly Evaluation}.
  343. Note that there is a legacy interface for getting source locations into
  344. the Scheme compiler or interpreter, which is to use a side table that
  345. associates ``source properties'' with each subdatum returned by
  346. @code{read}, instead of wrapping the datums directly as in
  347. @code{read-syntax}. This has the disadvantage of not being able to
  348. annotate all kinds of datums. @xref{Source Properties}, for more
  349. information.
  350. @node Scheme Write
  351. @subsection Writing Scheme Values
  352. Any scheme value may be written to a port. Not all values may be read
  353. back in (@pxref{Scheme Read}), however.
  354. @rnindex write
  355. @rnindex print
  356. @deffn {Scheme Procedure} write obj [port]
  357. Send a representation of @var{obj} to @var{port} or to the current
  358. output port if not given.
  359. The output is designed to be machine readable, and can be read back
  360. with @code{read} (@pxref{Scheme Read}). Strings are printed in
  361. double quotes, with escapes if necessary, and characters are printed in
  362. @samp{#\} notation.
  363. @end deffn
  364. @rnindex display
  365. @deffn {Scheme Procedure} display obj [port]
  366. Send a representation of @var{obj} to @var{port} or to the current
  367. output port if not given.
  368. The output is designed for human readability, it differs from
  369. @code{write} in that strings are printed without double quotes and
  370. escapes, and characters are printed as per @code{write-char}, not in
  371. @samp{#\} form.
  372. @end deffn
  373. As was the case with the Scheme reader, there are a few options that
  374. affect the behavior of the Scheme printer.
  375. @cindex options - print
  376. @cindex print options
  377. @deffn {Scheme Procedure} print-options [setting]
  378. Display the current settings of the read options. If @var{setting} is
  379. omitted, only a short form of the current read options is
  380. printed. Otherwise if @var{setting} is the symbol @code{help}, a
  381. complete options description is displayed.
  382. @end deffn
  383. The set of available options, and their default values, may be had by
  384. invoking @code{print-options} at the prompt.
  385. @smalllisp
  386. scheme@@(guile-user)> (print-options)
  387. (quote-keywordish-symbols reader highlight-suffix "@}" highlight-prefix "@{")
  388. scheme@@(guile-user)> (print-options 'help)
  389. highlight-prefix @{ The string to print before highlighted values.
  390. highlight-suffix @} The string to print after highlighted values.
  391. quote-keywordish-symbols reader How to print symbols that have a colon
  392. as their first or last character. The
  393. value '#f' does not quote the colons;
  394. '#t' quotes them; 'reader' quotes them
  395. when the reader option 'keywords' is
  396. not '#f'.
  397. escape-newlines yes Render newlines as \n when printing
  398. using `write'.
  399. r7rs-symbols no Escape symbols using R7RS |...| symbol
  400. notation.
  401. @end smalllisp
  402. These options may be modified with the print-set! syntax.
  403. @deffn {Scheme Syntax} print-set! option-name value
  404. Modify the print options. Due to historical oddities, @code{print-set!}
  405. is a macro that expects an unquoted option name.
  406. @end deffn
  407. @node Fly Evaluation
  408. @subsection Procedures for On the Fly Evaluation
  409. Scheme has the lovely property that its expressions may be represented
  410. as data. The @code{eval} procedure takes a Scheme datum and evaluates
  411. it as code.
  412. @rnindex eval
  413. @c ARGFIXME environment/environment specifier
  414. @deffn {Scheme Procedure} eval exp module_or_state
  415. @deffnx {C Function} scm_eval (exp, module_or_state)
  416. Evaluate @var{exp}, a list representing a Scheme expression,
  417. in the top-level environment specified by @var{module_or_state}.
  418. While @var{exp} is evaluated (using @code{primitive-eval}),
  419. @var{module_or_state} is made the current module. The current module
  420. is reset to its previous value when @code{eval} returns.
  421. XXX - dynamic states.
  422. Example: (eval '(+ 1 2) (interaction-environment))
  423. @end deffn
  424. @rnindex interaction-environment
  425. @deffn {Scheme Procedure} interaction-environment
  426. @deffnx {C Function} scm_interaction_environment ()
  427. Return a specifier for the environment that contains
  428. implementation--defined bindings, typically a superset of those
  429. listed in the report. The intent is that this procedure will
  430. return the environment in which the implementation would
  431. evaluate expressions dynamically typed by the user.
  432. @end deffn
  433. @xref{Environments}, for other environments.
  434. One does not always receive code as Scheme data, of course, and this is
  435. especially the case for Guile's other language implementations
  436. (@pxref{Other Languages}). For the case in which all you have is a
  437. string, we have @code{eval-string}. There is a legacy version of this
  438. procedure in the default environment, but you really want the one from
  439. @code{(ice-9 eval-string)}, so load it up:
  440. @example
  441. (use-modules (ice-9 eval-string))
  442. @end example
  443. @deffn {Scheme Procedure} eval-string string [#:module=#f] [#:file=#f] @
  444. [#:line=#f] [#:column=#f] @
  445. [#:lang=(current-language)] @
  446. [#:compile?=#f]
  447. Parse @var{string} according to the current language, normally Scheme.
  448. Evaluate or compile the expressions it contains, in order, returning the
  449. last expression.
  450. If the @var{module} keyword argument is set, save a module excursion
  451. (@pxref{Module System Reflection}) and set the current module to
  452. @var{module} before evaluation.
  453. The @var{file}, @var{line}, and @var{column} keyword arguments can be
  454. used to indicate that the source string begins at a particular source
  455. location.
  456. Finally, @var{lang} is a language, defaulting to the current language,
  457. and the expression is compiled if @var{compile?} is true or there is no
  458. evaluator for the given language.
  459. @end deffn
  460. @deffn {C Function} scm_eval_string (string)
  461. @deffnx {C Function} scm_eval_string_in_module (string, module)
  462. These C bindings call @code{eval-string} from @code{(ice-9
  463. eval-string)}, evaluating within @var{module} or the current module.
  464. @end deffn
  465. @deftypefn {C Function} SCM scm_c_eval_string (const char *string)
  466. @code{scm_eval_string}, but taking a C string in locale encoding instead
  467. of an @code{SCM}.
  468. @end deftypefn
  469. @deffn {Scheme Procedure} apply proc arg @dots{} arglst
  470. @deffnx {C Function} scm_apply_0 (proc, arglst)
  471. @deffnx {C Function} scm_apply_1 (proc, arg1, arglst)
  472. @deffnx {C Function} scm_apply_2 (proc, arg1, arg2, arglst)
  473. @deffnx {C Function} scm_apply_3 (proc, arg1, arg2, arg3, arglst)
  474. @deffnx {C Function} scm_apply (proc, arg, rest)
  475. @rnindex apply
  476. Call @var{proc} with arguments @var{arg} @dots{} and the
  477. elements of the @var{arglst} list.
  478. @code{scm_apply} takes parameters corresponding to a Scheme level
  479. @code{(lambda (proc arg1 . rest) ...)}. So @var{arg1} and all but the
  480. last element of the @var{rest} list make up @var{arg} @dots{}, and the
  481. last element of @var{rest} is the @var{arglst} list. Or if @var{rest}
  482. is the empty list @code{SCM_EOL} then there's no @var{arg} @dots{}, and
  483. (@var{arg1}) is the @var{arglst}.
  484. @var{arglst} is not modified, but the @var{rest} list passed to
  485. @code{scm_apply} is modified.
  486. @end deffn
  487. @deffn {C Function} scm_call_0 (proc)
  488. @deffnx {C Function} scm_call_1 (proc, arg1)
  489. @deffnx {C Function} scm_call_2 (proc, arg1, arg2)
  490. @deffnx {C Function} scm_call_3 (proc, arg1, arg2, arg3)
  491. @deffnx {C Function} scm_call_4 (proc, arg1, arg2, arg3, arg4)
  492. @deffnx {C Function} scm_call_5 (proc, arg1, arg2, arg3, arg4, arg5)
  493. @deffnx {C Function} scm_call_6 (proc, arg1, arg2, arg3, arg4, arg5, arg6)
  494. @deffnx {C Function} scm_call_7 (proc, arg1, arg2, arg3, arg4, arg5, arg6, arg7)
  495. @deffnx {C Function} scm_call_8 (proc, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)
  496. @deffnx {C Function} scm_call_9 (proc, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9)
  497. Call @var{proc} with the given arguments.
  498. @end deffn
  499. @deffn {C Function} scm_call (proc, ...)
  500. Call @var{proc} with any number of arguments. The argument list must be
  501. terminated by @code{SCM_UNDEFINED}. For example:
  502. @example
  503. scm_call (scm_c_public_ref ("guile", "+"),
  504. scm_from_int (1),
  505. scm_from_int (2),
  506. SCM_UNDEFINED);
  507. @end example
  508. @end deffn
  509. @deffn {C Function} scm_call_n (proc, argv, nargs)
  510. Call @var{proc} with the array of arguments @var{argv}, as a
  511. @code{SCM*}. The length of the arguments should be passed in
  512. @var{nargs}, as a @code{size_t}.
  513. @end deffn
  514. @deffn {Scheme Procedure} primitive-eval exp
  515. @deffnx {C Function} scm_primitive_eval (exp)
  516. Evaluate @var{exp} in the top-level environment specified by
  517. the current module.
  518. @end deffn
  519. @node Compilation
  520. @subsection Compiling Scheme Code
  521. The @code{eval} procedure directly interprets the S-expression
  522. representation of Scheme. An alternate strategy for evaluation is to
  523. determine ahead of time what computations will be necessary to
  524. evaluate the expression, and then use that recipe to produce the
  525. desired results. This is known as @dfn{compilation}.
  526. While it is possible to compile simple Scheme expressions such as
  527. @code{(+ 2 2)} or even @code{"Hello world!"}, compilation is most
  528. interesting in the context of procedures. Compiling a lambda expression
  529. produces a compiled procedure, which is just like a normal procedure
  530. except typically much faster, because it can bypass the generic
  531. interpreter.
  532. Functions from system modules in a Guile installation are normally
  533. compiled already, so they load and run quickly.
  534. @cindex automatic compilation
  535. Note that well-written Scheme programs will not typically call the
  536. procedures in this section, for the same reason that it is often bad
  537. taste to use @code{eval}. By default, Guile automatically compiles any
  538. files it encounters that have not been compiled yet (@pxref{Invoking
  539. Guile, @code{--auto-compile}}). The compiler can also be invoked
  540. explicitly from the shell as @code{guild compile foo.scm}.
  541. (Why are calls to @code{eval} and @code{compile} usually in bad taste?
  542. Because they are limited, in that they can only really make sense for
  543. top-level expressions. Also, most needs for ``compile-time''
  544. computation are fulfilled by macros and closures. Of course one good
  545. counterexample is the REPL itself, or any code that reads expressions
  546. from a port.)
  547. Automatic compilation generally works transparently, without any need
  548. for user intervention. However Guile does not yet do proper dependency
  549. tracking, so that if file @file{@var{a}.scm} uses macros from
  550. @file{@var{b}.scm}, and @var{@var{b}.scm} changes, @code{@var{a}.scm}
  551. would not be automatically recompiled. To forcibly invalidate the
  552. auto-compilation cache, pass the @code{--fresh-auto-compile} option to
  553. Guile, or set the @code{GUILE_AUTO_COMPILE} environment variable to
  554. @code{fresh} (instead of to @code{0} or @code{1}).
  555. For more information on the compiler itself, see @ref{Compiling to the
  556. Virtual Machine}. For information on the virtual machine, see @ref{A
  557. Virtual Machine for Guile}.
  558. The command-line interface to Guile's compiler is the @command{guild
  559. compile} command:
  560. @deffn {Command} {guild compile} [@option{option}...] @var{file}...
  561. Compile @var{file}, a source file, and store bytecode in the compilation cache
  562. or in the file specified by the @option{-o} option. The following options are
  563. available:
  564. @table @option
  565. @item -L @var{dir}
  566. @itemx --load-path=@var{dir}
  567. Add @var{dir} to the front of the module load path.
  568. @item -o @var{ofile}
  569. @itemx --output=@var{ofile}
  570. Write output bytecode to @var{ofile}. By convention, bytecode file
  571. names end in @code{.go}. When @option{-o} is omitted, the output file
  572. name is as for @code{compile-file} (see below).
  573. @item -x @var{extension}
  574. Recognize @var{extension} as a valid source file name extension.
  575. For example, to compile R6RS code, you might want to pass @command{-x
  576. .sls} so that files ending in @file{.sls} can be found.
  577. @item -W @var{warning}
  578. @itemx --warn=@var{warning}
  579. @cindex warnings, compiler
  580. Enable specific warning passes; use @code{-Whelp} for a list of
  581. available options. The default is @code{-W1}, which enables a number of
  582. common warnings. Pass @code{-W0} to disable all warnings.
  583. @item -O @var{opt}
  584. @itemx --optimize=@var{opt}
  585. @cindex optimizations, compiler
  586. Enable or disable specific compiler optimizations; use @code{-Ohelp} for
  587. a list of available options. The default is @code{-O2}, which enables
  588. most optimizations. @code{-O0} is recommended if compilation speed is
  589. more important than the speed of the compiled code. Pass
  590. @code{-Ono-@var{opt}} to disable a specific compiler pass. Any number
  591. of @code{-O} options can be passed to the compiler, with later ones
  592. taking precedence.
  593. @item --r6rs
  594. @itemx --r7rs
  595. Compile in an environment whose default bindings, reader options, and
  596. load paths are adapted for specific Scheme standards. @xref{R6RS
  597. Support}, and @xref{R7RS Support}.
  598. @item -f @var{lang}
  599. @itemx --from=@var{lang}
  600. Use @var{lang} as the source language of @var{file}. If this option is omitted,
  601. @code{scheme} is assumed.
  602. @item -t @var{lang}
  603. @itemx --to=@var{lang}
  604. Use @var{lang} as the target language of @var{file}. If this option is omitted,
  605. @code{rtl} is assumed.
  606. @item -T @var{target}
  607. @itemx --target=@var{target}
  608. Produce code for @var{target} instead of @var{%host-type} (@pxref{Build
  609. Config, %host-type}). Target must be a valid GNU triplet, such as
  610. @code{armv5tel-unknown-linux-gnueabi} (@pxref{Specifying Target
  611. Triplets,,, autoconf, GNU Autoconf Manual}).
  612. @end table
  613. Each @var{file} is assumed to be UTF-8-encoded, unless it contains a
  614. coding declaration as recognized by @code{file-encoding}
  615. (@pxref{Character Encoding of Source Files}).
  616. @end deffn
  617. The compiler can also be invoked directly by Scheme code. These
  618. interfaces are in their own module:
  619. @example
  620. (use-modules (system base compile))
  621. @end example
  622. @deffn {Scheme Procedure} compile exp [#:env=#f] @
  623. [#:from=(current-language)] @
  624. [#:to=value] [#:opts='()] @
  625. [#:optimization-level=(default-optimization-level)] @
  626. [#:warning-level=(default-warning-level)]
  627. Compile the expression @var{exp} in the environment @var{env}. If
  628. @var{exp} is a procedure, the result will be a compiled procedure;
  629. otherwise @code{compile} is mostly equivalent to @code{eval}.
  630. For a discussion of languages and compiler options, @xref{Compiling to
  631. the Virtual Machine}.
  632. @end deffn
  633. @deffn {Scheme Procedure} compile-file file [#:output-file=#f] @
  634. [#:from=(current-language)] [#:to='rtl] @
  635. [#:env=(default-environment from)] @
  636. [#:opts='()] @
  637. [#:optimization-level=(default-optimization-level)] @
  638. [#:warning-level=(default-warning-level)] @
  639. [#:canonicalization='relative]
  640. Compile the file named @var{file}.
  641. Output will be written to a @var{output-file}. If you do not supply an
  642. output file name, output is written to a file in the cache directory, as
  643. computed by @code{(compiled-file-name @var{file})}.
  644. @var{from} and @var{to} specify the source and target languages.
  645. @xref{Compiling to the Virtual Machine}, for more information on these
  646. options, and on @var{env} and @var{opts}.
  647. As with @command{guild compile}, @var{file} is assumed to be
  648. UTF-8-encoded unless it contains a coding declaration.
  649. @end deffn
  650. @deffn {Scheme Parameter} default-optimization-level
  651. The default optimization level, as an integer from 0 to 9. The default
  652. is 2.
  653. @end deffn
  654. @deffn {Scheme Parameter} default-warning-level
  655. The default warning level, as an integer from 0 to 9. The default is 1.
  656. @end deffn
  657. @xref{Parameters}, for more on how to set parameters.
  658. @deffn {Scheme Procedure} compiled-file-name file
  659. Compute a cached location for a compiled version of a Scheme file named
  660. @var{file}.
  661. This file will usually be below the @file{$HOME/.cache/guile/ccache}
  662. directory, depending on the value of the @env{XDG_CACHE_HOME}
  663. environment variable. The intention is that @code{compiled-file-name}
  664. provides a fallback location for caching auto-compiled files. If you
  665. want to place a compile file in the @code{%load-compiled-path}, you
  666. should pass the @var{output-file} option to @code{compile-file},
  667. explicitly.
  668. @end deffn
  669. @defvr {Scheme Variable} %auto-compilation-options
  670. This variable contains the options passed to the @code{compile-file}
  671. procedure when auto-compiling source files. By default, it enables
  672. useful compilation warnings. It can be customized from @file{~/.guile}.
  673. @end defvr
  674. @node Loading
  675. @subsection Loading Scheme Code from File
  676. @rnindex load
  677. @deffn {Scheme Procedure} load filename [reader]
  678. Load @var{filename} and evaluate its contents in the top-level
  679. environment.
  680. @var{reader} if provided should be either @code{#f}, or a procedure with
  681. the signature @code{(lambda (port) @dots{})} which reads the next
  682. expression from @var{port}. If @var{reader} is @code{#f} or absent,
  683. Guile's built-in @code{read} procedure is used (@pxref{Scheme Read}).
  684. The @var{reader} argument takes effect by setting the value of the
  685. @code{current-reader} fluid (see below) before loading the file, and
  686. restoring its previous value when loading is complete. The Scheme code
  687. inside @var{filename} can itself change the current reader procedure on
  688. the fly by setting @code{current-reader} fluid.
  689. If the variable @code{%load-hook} is defined, it should be bound to a
  690. procedure that will be called before any code is loaded. See
  691. documentation for @code{%load-hook} later in this section.
  692. @end deffn
  693. @deffn {Scheme Procedure} load-compiled filename
  694. Load the compiled file named @var{filename}.
  695. Compiling a source file (@pxref{Read/Load/Eval/Compile}) and then
  696. calling @code{load-compiled} on the resulting file is equivalent to
  697. calling @code{load} on the source file.
  698. @end deffn
  699. @deffn {Scheme Procedure} primitive-load filename
  700. @deffnx {C Function} scm_primitive_load (filename)
  701. Load the file named @var{filename} and evaluate its contents in the
  702. top-level environment. @var{filename} must either be a full pathname or
  703. be a pathname relative to the current directory. If the variable
  704. @code{%load-hook} is defined, it should be bound to a procedure that
  705. will be called before any code is loaded. See the documentation for
  706. @code{%load-hook} later in this section.
  707. @end deffn
  708. @deftypefn {C Function} SCM scm_c_primitive_load (const char *filename)
  709. @code{scm_primitive_load}, but taking a C string instead of an
  710. @code{SCM}.
  711. @end deftypefn
  712. @defvar current-reader
  713. @code{current-reader} holds the read procedure that is currently being
  714. used by the above loading procedures to read expressions (from the file
  715. that they are loading). @code{current-reader} is a fluid, so it has an
  716. independent value in each dynamic root and should be read and set using
  717. @code{fluid-ref} and @code{fluid-set!} (@pxref{Fluids and Dynamic
  718. States}).
  719. Changing @code{current-reader} is typically useful to introduce local
  720. syntactic changes, such that code following the @code{fluid-set!} call
  721. is read using the newly installed reader. The @code{current-reader}
  722. change should take place at evaluation time when the code is evaluated,
  723. or at compilation time when the code is compiled:
  724. @findex eval-when
  725. @example
  726. (eval-when (compile eval)
  727. (fluid-set! current-reader my-own-reader))
  728. @end example
  729. The @code{eval-when} form above ensures that the @code{current-reader}
  730. change occurs at the right time.
  731. @end defvar
  732. @defvar %load-hook
  733. A procedure to be called @code{(%load-hook @var{filename})} whenever a
  734. file is loaded, or @code{#f} for no such call. @code{%load-hook} is
  735. used by all of the loading functions (@code{load} and
  736. @code{primitive-load}, and @code{load-from-path} and
  737. @code{primitive-load-path} documented in the next section).
  738. For example an application can set this to show what's loaded,
  739. @example
  740. (set! %load-hook (lambda (filename)
  741. (format #t "Loading ~a ...\n" filename)))
  742. (load-from-path "foo.scm")
  743. @print{} Loading /usr/local/share/guile/site/foo.scm ...
  744. @end example
  745. @end defvar
  746. @deffn {Scheme Procedure} current-load-port
  747. @deffnx {C Function} scm_current_load_port ()
  748. Return the current-load-port.
  749. The load port is used internally by @code{primitive-load}.
  750. @end deffn
  751. @node Load Paths
  752. @subsection Load Paths
  753. The procedure in the previous section look for Scheme code in the file
  754. system at specific location. Guile also has some procedures to search
  755. the load path for code.
  756. @defvar %load-path
  757. List of directories which should be searched for Scheme modules and
  758. libraries. When Guile starts up, @code{%load-path} is initialized to
  759. the default load path @code{(list (%library-dir) (%site-dir)
  760. (%global-site-dir) (%package-data-dir))}. The @env{GUILE_LOAD_PATH}
  761. environment variable can be used to prepend or append additional
  762. directories (@pxref{Environment Variables}).
  763. @xref{Build Config}, for more on @code{%site-dir} and related
  764. procedures.
  765. @end defvar
  766. @deffn {Scheme Procedure} load-from-path filename
  767. Similar to @code{load}, but searches for @var{filename} in the load
  768. paths. Preferentially loads a compiled version of the file, if it is
  769. available and up-to-date.
  770. @end deffn
  771. A user can extend the load path by calling @code{add-to-load-path}.
  772. @deffn {Scheme Syntax} add-to-load-path dir
  773. Add @var{dir} to the load path.
  774. @end deffn
  775. For example, a script might include this form to add the directory that
  776. it is in to the load path:
  777. @example
  778. (add-to-load-path (dirname (current-filename)))
  779. @end example
  780. It's better to use @code{add-to-load-path} than to modify
  781. @code{%load-path} directly, because @code{add-to-load-path} takes care
  782. of modifying the path both at compile-time and at run-time.
  783. @deffn {Scheme Procedure} primitive-load-path filename [exception-on-not-found]
  784. @deffnx {C Function} scm_primitive_load_path (filename)
  785. Search @code{%load-path} for the file named @var{filename} and
  786. load it into the top-level environment. If @var{filename} is a
  787. relative pathname and is not found in the list of search paths,
  788. an error is signaled. Preferentially loads a compiled version of the
  789. file, if it is available and up-to-date.
  790. If @var{filename} is a relative pathname and is not found in the list of
  791. search paths, one of three things may happen, depending on the optional
  792. second argument, @var{exception-on-not-found}. If it is @code{#f},
  793. @code{#f} will be returned. If it is a procedure, it will be called
  794. with no arguments. (This allows a distinction to be made between
  795. exceptions raised by loading a file, and exceptions related to the
  796. loader itself.) Otherwise an error is signaled.
  797. For compatibility with Guile 1.8 and earlier, the C function takes only
  798. one argument, which can be either a string (the file name) or an
  799. argument list.
  800. @end deffn
  801. @deffn {Scheme Procedure} %search-load-path filename
  802. @deffnx {C Function} scm_sys_search_load_path (filename)
  803. Search @code{%load-path} for the file named @var{filename}, which must
  804. be readable by the current user. If @var{filename} is found in the list
  805. of paths to search or is an absolute pathname, return its full pathname.
  806. Otherwise, return @code{#f}. Filenames may have any of the optional
  807. extensions in the @code{%load-extensions} list; @code{%search-load-path}
  808. will try each extension automatically.
  809. @end deffn
  810. @defvar %load-extensions
  811. A list of default file extensions for files containing Scheme code.
  812. @code{%search-load-path} tries each of these extensions when looking for
  813. a file to load. By default, @code{%load-extensions} is bound to the
  814. list @code{("" ".scm")}.
  815. @end defvar
  816. As mentioned above, when Guile searches the @code{%load-path} for a
  817. source file, it will also search the @code{%load-compiled-path} for a
  818. corresponding compiled file. If the compiled file is as new or newer
  819. than the source file, it will be loaded instead of the source file,
  820. using @code{load-compiled}.
  821. @defvar %load-compiled-path
  822. Like @code{%load-path}, but for compiled files. By default, this path
  823. has two entries: one for compiled files from Guile itself, and one for
  824. site packages. The @env{GUILE_LOAD_COMPILED_PATH} environment variable
  825. can be used to prepend or append additional directories
  826. (@pxref{Environment Variables}).
  827. @end defvar
  828. When @code{primitive-load-path} searches the @code{%load-compiled-path}
  829. for a corresponding compiled file for a relative path it does so by
  830. appending @code{.go} to the relative path. For example, searching for
  831. @code{ice-9/popen} could find
  832. @code{/usr/lib/guile/3.0/ccache/ice-9/popen.go}, and use it instead of
  833. @code{/usr/share/guile/3.0/ice-9/popen.scm}.
  834. If @code{primitive-load-path} does not find a corresponding @code{.go}
  835. file in the @code{%load-compiled-path}, or the @code{.go} file is out of
  836. date, it will search for a corresponding auto-compiled file in the
  837. fallback path, possibly creating one if one does not exist.
  838. @xref{Installing Site Packages}, for more on how to correctly install
  839. site packages. @xref{Modules and the File System}, for more on the
  840. relationship between load paths and modules. @xref{Compilation}, for
  841. more on the fallback path and auto-compilation.
  842. Finally, there are a couple of helper procedures for general path
  843. manipulation.
  844. @deffn {Scheme Procedure} parse-path path [tail]
  845. @deffnx {C Function} scm_parse_path (path, tail)
  846. Parse @var{path}, which is expected to be a colon-separated string, into
  847. a list and return the resulting list with @var{tail} appended. If
  848. @var{path} is @code{#f}, @var{tail} is returned.
  849. @end deffn
  850. @deffn {Scheme Procedure} parse-path-with-ellipsis path base
  851. @deffnx {C Function} scm_parse_path_with_ellipsis (path, base)
  852. Parse @var{path}, which is expected to be a colon-separated string, into
  853. a list and return the resulting list with @var{base} (a list) spliced in
  854. place of the @code{...} path component, if present, or else @var{base}
  855. is added to the end. If @var{path} is @code{#f}, @var{base} is
  856. returned.
  857. @end deffn
  858. @deffn {Scheme Procedure} search-path path filename [extensions [require-exts?]]
  859. @deffnx {C Function} scm_search_path (path, filename, rest)
  860. Search @var{path} for a directory containing a file named
  861. @var{filename}. The file must be readable, and not a directory. If we
  862. find one, return its full filename; otherwise, return @code{#f}. If
  863. @var{filename} is absolute, return it unchanged. If given,
  864. @var{extensions} is a list of strings; for each directory in @var{path},
  865. we search for @var{filename} concatenated with each @var{extension}. If
  866. @var{require-exts?} is true, require that the returned file name have
  867. one of the given extensions; if @var{require-exts?} is not given, it
  868. defaults to @code{#f}.
  869. For compatibility with Guile 1.8 and earlier, the C function takes only
  870. three arguments.
  871. @end deffn
  872. @node Character Encoding of Source Files
  873. @subsection Character Encoding of Source Files
  874. @cindex source file encoding
  875. @cindex primitive-load
  876. @cindex load
  877. Scheme source code files are usually encoded in ASCII or UTF-8, but the
  878. built-in reader can interpret other character encodings as well. When
  879. Guile loads Scheme source code, it uses the @code{file-encoding}
  880. procedure (described below) to try to guess the encoding of the file.
  881. In the absence of any hints, UTF-8 is assumed. One way to provide a
  882. hint about the encoding of a source file is to place a coding
  883. declaration in the top 500 characters of the file.
  884. A coding declaration has the form @code{coding: XXXXXX}, where
  885. @code{XXXXXX} is the name of a character encoding in which the source
  886. code file has been encoded. The coding declaration must appear in a
  887. scheme comment. It can either be a semicolon-initiated comment, or the
  888. first block @code{#!} comment in the file.
  889. The name of the character encoding in the coding declaration is
  890. typically lower case and containing only letters, numbers, and hyphens,
  891. as recognized by @code{set-port-encoding!} (@pxref{Ports,
  892. @code{set-port-encoding!}}). Common examples of character encoding
  893. names are @code{utf-8} and @code{iso-8859-1},
  894. @url{http://www.iana.org/assignments/character-sets, as defined by
  895. IANA}. Thus, the coding declaration is mostly compatible with Emacs.
  896. However, there are some differences in encoding names recognized by
  897. Emacs and encoding names defined by IANA, the latter being essentially a
  898. subset of the former. For instance, @code{latin-1} is a valid encoding
  899. name for Emacs, but it's not according to the IANA standard, which Guile
  900. follows; instead, you should use @code{iso-8859-1}, which is both
  901. understood by Emacs and dubbed by IANA (IANA writes it uppercase but
  902. Emacs wants it lowercase and Guile is case insensitive.)
  903. For source code, only a subset of all possible character encodings can
  904. be interpreted by the built-in source code reader. Only those
  905. character encodings in which ASCII text appears unmodified can be
  906. used. This includes @code{UTF-8} and @code{ISO-8859-1} through
  907. @code{ISO-8859-15}. The multi-byte character encodings @code{UTF-16}
  908. and @code{UTF-32} may not be used because they are not compatible with
  909. ASCII.
  910. @cindex read
  911. @cindex encoding
  912. @cindex port encoding
  913. @findex set-port-encoding!
  914. There might be a scenario in which one would want to read non-ASCII
  915. code from a port, such as with the function @code{read}, instead of
  916. with @code{load}. If the port's character encoding is the same as the
  917. encoding of the code to be read by the port, not other special
  918. handling is necessary. The port will automatically do the character
  919. encoding conversion. The functions @code{setlocale} or by
  920. @code{set-port-encoding!} are used to set port encodings
  921. (@pxref{Ports}).
  922. If a port is used to read code of unknown character encoding, it can
  923. accomplish this in three steps. First, the character encoding of the
  924. port should be set to ISO-8859-1 using @code{set-port-encoding!}.
  925. Then, the procedure @code{file-encoding}, described below, is used to
  926. scan for a coding declaration when reading from the port. As a side
  927. effect, it rewinds the port after its scan is complete. After that,
  928. the port's character encoding should be set to the encoding returned
  929. by @code{file-encoding}, if any, again by using
  930. @code{set-port-encoding!}. Then the code can be read as normal.
  931. Alternatively, one can use the @code{#:guess-encoding} keyword argument
  932. of @code{open-file} and related procedures. @xref{File Ports}.
  933. @deffn {Scheme Procedure} file-encoding port
  934. @deffnx {C Function} scm_file_encoding (port)
  935. Attempt to scan the first few hundred bytes from the @var{port} for
  936. hints about its character encoding. Return a string containing the
  937. encoding name or @code{#f} if the encoding cannot be determined. The
  938. port is rewound.
  939. Currently, the only supported method is to look for an Emacs-like
  940. character coding declaration (@pxref{Recognize Coding, how Emacs
  941. recognizes file encoding,, emacs, The GNU Emacs Reference Manual}). The
  942. coding declaration is of the form @code{coding: XXXXX} and must appear
  943. in a Scheme comment. Additional heuristics may be added in the future.
  944. @end deffn
  945. @node Delayed Evaluation
  946. @subsection Delayed Evaluation
  947. @cindex delayed evaluation
  948. @cindex promises
  949. Promises are a convenient way to defer a calculation until its result
  950. is actually needed, and to run such a calculation only once. Also
  951. @pxref{SRFI-45}.
  952. @deffn syntax delay expr
  953. @rnindex delay
  954. Return a promise object which holds the given @var{expr} expression,
  955. ready to be evaluated by a later @code{force}.
  956. @end deffn
  957. @deffn {Scheme Procedure} promise? obj
  958. @deffnx {C Function} scm_promise_p (obj)
  959. Return true if @var{obj} is a promise.
  960. @end deffn
  961. @rnindex force
  962. @deffn {Scheme Procedure} force p
  963. @deffnx {C Function} scm_force (p)
  964. Return the value obtained from evaluating the @var{expr} in the given
  965. promise @var{p}. If @var{p} has previously been forced then its
  966. @var{expr} is not evaluated again, instead the value obtained at that
  967. time is simply returned.
  968. During a @code{force}, an @var{expr} can call @code{force} again on
  969. its own promise, resulting in a recursive evaluation of that
  970. @var{expr}. The first evaluation to return gives the value for the
  971. promise. Higher evaluations run to completion in the normal way, but
  972. their results are ignored, @code{force} always returns the first
  973. value.
  974. @end deffn
  975. @node Local Evaluation
  976. @subsection Local Evaluation
  977. Guile includes a facility to capture a lexical environment, and later
  978. evaluate a new expression within that environment. This code is
  979. implemented in a module.
  980. @example
  981. (use-modules (ice-9 local-eval))
  982. @end example
  983. @deffn syntax the-environment
  984. Captures and returns a lexical environment for use with
  985. @code{local-eval} or @code{local-compile}.
  986. @end deffn
  987. @deffn {Scheme Procedure} local-eval exp env
  988. @deffnx {C Function} scm_local_eval (exp, env)
  989. @deffnx {Scheme Procedure} local-compile exp env [opts=()]
  990. Evaluate or compile the expression @var{exp} in the lexical environment
  991. @var{env}.
  992. @end deffn
  993. Here is a simple example, illustrating that it is the variable
  994. that gets captured, not just its value at one point in time.
  995. @example
  996. (define e (let ((x 100)) (the-environment)))
  997. (define fetch-x (local-eval '(lambda () x) e))
  998. (fetch-x)
  999. @result{} 100
  1000. (local-eval '(set! x 42) e)
  1001. (fetch-x)
  1002. @result{} 42
  1003. @end example
  1004. While @var{exp} is evaluated within the lexical environment of
  1005. @code{(the-environment)}, it has the dynamic environment of the call to
  1006. @code{local-eval}.
  1007. @code{local-eval} and @code{local-compile} can only evaluate
  1008. expressions, not definitions.
  1009. @example
  1010. (local-eval '(define foo 42)
  1011. (let ((x 100)) (the-environment)))
  1012. @result{} syntax error: definition in expression context
  1013. @end example
  1014. Note that the current implementation of @code{(the-environment)} only
  1015. captures ``normal'' lexical bindings, and pattern variables bound by
  1016. @code{syntax-case}. It does not currently capture local syntax
  1017. transformers bound by @code{let-syntax}, @code{letrec-syntax} or
  1018. non-top-level @code{define-syntax} forms. Any attempt to reference such
  1019. captured syntactic keywords via @code{local-eval} or
  1020. @code{local-compile} produces an error.
  1021. @node Local Inclusion
  1022. @subsection Local Inclusion
  1023. This section has discussed various means of linking Scheme code
  1024. together: fundamentally, loading up files at run-time using @code{load}
  1025. and @code{load-compiled}. Guile provides another option to compose
  1026. parts of programs together at expansion-time instead of at run-time.
  1027. @deffn {Scheme Syntax} include file-name
  1028. Open @var{file-name}, at expansion-time, and read the Scheme forms that
  1029. it contains, splicing them into the location of the @code{include},
  1030. within a @code{begin}.
  1031. If @var{file-name} is a relative path, it is searched for relative to
  1032. the path that contains the file that the @code{include} form appears in.
  1033. @end deffn
  1034. If you are a C programmer, if @code{load} in Scheme is like
  1035. @code{dlopen} in C, consider @code{include} to be like the C
  1036. preprocessor's @code{#include}. When you use @code{include}, it is as
  1037. if the contents of the included file were typed in instead of the
  1038. @code{include} form.
  1039. Because the code is included at compile-time, it is available to the
  1040. macroexpander. Syntax definitions in the included file are available to
  1041. later code in the form in which the @code{include} appears, without the
  1042. need for @code{eval-when}. (@xref{Eval When}.)
  1043. For the same reason, compiling a form that uses @code{include} results
  1044. in one compilation unit, composed of multiple files. Loading the
  1045. compiled file is one @code{stat} operation for the compilation unit,
  1046. instead of @code{2*@var{n}} in the case of @code{load} (once for each
  1047. loaded source file, and once each corresponding compiled file, in the
  1048. best case).
  1049. Unlike @code{load}, @code{include} also works within nested lexical
  1050. contexts. It so happens that the optimizer works best within a lexical
  1051. context, because all of the uses of bindings in a lexical context are
  1052. visible, so composing files by including them within a @code{(let ()
  1053. ...)} can sometimes lead to important speed improvements.
  1054. On the other hand, @code{include} does have all the disadvantages of
  1055. early binding: once the code with the @code{include} is compiled, no
  1056. change to the included file is reflected in the future behavior of the
  1057. including form.
  1058. Also, the particular form of @code{include}, which requires an absolute
  1059. path, or a path relative to the current directory at compile-time, is
  1060. not very amenable to compiling the source in one place, but then
  1061. installing the source to another place. For this reason, Guile provides
  1062. another form, @code{include-from-path}, which looks for the source file
  1063. to include within a load path.
  1064. @deffn {Scheme Syntax} include-from-path file-name
  1065. Like @code{include}, but instead of expecting @code{file-name} to be an
  1066. absolute file name, it is expected to be a relative path to search in
  1067. the @code{%load-path}.
  1068. @end deffn
  1069. @code{include-from-path} is more useful when you want to install all of
  1070. the source files for a package (as you should!). It makes it possible
  1071. to evaluate an installed file from source, instead of relying on the
  1072. @code{.go} file being up to date.
  1073. @node Sandboxed Evaluation
  1074. @subsection Sandboxed Evaluation
  1075. Sometimes you would like to evaluate code that comes from an untrusted
  1076. party. The safest way to do this is to buy a new computer, evaluate the
  1077. code on that computer, then throw the machine away. However if you are
  1078. unwilling to take this simple approach, Guile does include a limited
  1079. ``sandbox'' facility that can allow untrusted code to be evaluated with
  1080. some confidence.
  1081. To use the sandboxed evaluator, load its module:
  1082. @example
  1083. (use-modules (ice-9 sandbox))
  1084. @end example
  1085. Guile's sandboxing facility starts with the ability to restrict the time
  1086. and space used by a piece of code.
  1087. @deffn {Scheme Procedure} call-with-time-limit limit thunk limit-reached
  1088. Call @var{thunk}, but cancel it if @var{limit} seconds of wall-clock
  1089. time have elapsed. If the computation is canceled, call
  1090. @var{limit-reached} in tail position. @var{thunk} must not disable
  1091. interrupts or prevent an abort via a @code{dynamic-wind} unwind handler.
  1092. @end deffn
  1093. @deffn {Scheme Procedure} call-with-allocation-limit limit thunk limit-reached
  1094. Call @var{thunk}, but cancel it if @var{limit} bytes have been
  1095. allocated. If the computation is canceled, call @var{limit-reached} in
  1096. tail position. @var{thunk} must not disable interrupts or prevent an
  1097. abort via a @code{dynamic-wind} unwind handler.
  1098. This limit applies to both stack and heap allocation. The computation
  1099. will not be aborted before @var{limit} bytes have been allocated, but
  1100. for the heap allocation limit, the check may be postponed until the next garbage collection.
  1101. Note that as a current shortcoming, the heap size limit applies to all
  1102. threads; concurrent allocation by other unrelated threads counts towards
  1103. the allocation limit.
  1104. @end deffn
  1105. @deffn {Scheme Procedure} call-with-time-and-allocation-limits time-limit allocation-limit thunk
  1106. Invoke @var{thunk} in a dynamic extent in which its execution is limited
  1107. to @var{time-limit} seconds of wall-clock time, and its allocation to
  1108. @var{allocation-limit} bytes. @var{thunk} must not disable interrupts
  1109. or prevent an abort via a @code{dynamic-wind} unwind handler.
  1110. If successful, return all values produced by invoking @var{thunk}. Any
  1111. uncaught exception thrown by the thunk will propagate out. If the time
  1112. or allocation limit is exceeded, an exception will be thrown to the
  1113. @code{limit-exceeded} key.
  1114. @end deffn
  1115. The time limit and stack limit are both very precise, but the heap limit
  1116. only gets checked asynchronously, after a garbage collection. In
  1117. particular, if the heap is already very large, the number of allocated
  1118. bytes between garbage collections will be large, and therefore the
  1119. precision of the check is reduced.
  1120. Additionally, due to the mechanism used by the allocation limit (the
  1121. @code{after-gc-hook}), large single allocations like @code{(make-vector
  1122. #e1e7)} are only detected after the allocation completes, even if the
  1123. allocation itself causes garbage collection. It's possible therefore
  1124. for user code to not only exceed the allocation limit set, but also to
  1125. exhaust all available memory, causing out-of-memory conditions at any
  1126. allocation site. Failure to allocate memory in Guile itself should be
  1127. safe and cause an exception to be thrown, but most systems are not
  1128. designed to handle @code{malloc} failures. An allocation failure may
  1129. therefore exercise unexpected code paths in your system, so it is a
  1130. weakness of the sandbox (and therefore an interesting point of attack).
  1131. The main sandbox interface is @code{eval-in-sandbox}.
  1132. @deffn {Scheme Procedure} eval-in-sandbox exp [#:time-limit 0.1] @
  1133. [#:allocation-limit #e10e6] @
  1134. [#:bindings all-pure-bindings] @
  1135. [#:module (make-sandbox-module bindings)] @
  1136. [#:sever-module? #t]
  1137. Evaluate the Scheme expression @var{exp} within an isolated
  1138. "sandbox". Limit its execution to @var{time-limit} seconds of
  1139. wall-clock time, and limit its allocation to @var{allocation-limit}
  1140. bytes.
  1141. The evaluation will occur in @var{module}, which defaults to the result
  1142. of calling @code{make-sandbox-module} on @var{bindings}, which itself
  1143. defaults to @code{all-pure-bindings}. This is the core of the
  1144. sandbox: creating a scope for the expression that is @dfn{safe}.
  1145. A safe sandbox module has two characteristics. Firstly, it will not
  1146. allow the expression being evaluated to avoid being canceled due to
  1147. time or allocation limits. This ensures that the expression terminates
  1148. in a timely fashion.
  1149. Secondly, a safe sandbox module will prevent the evaluation from
  1150. receiving information from previous evaluations, or from affecting
  1151. future evaluations. All combinations of binding sets exported by
  1152. @code{(ice-9 sandbox)} form safe sandbox modules.
  1153. The @var{bindings} should be given as a list of import sets. One import
  1154. set is a list whose car names an interface, like @code{(ice-9 q)}, and
  1155. whose cdr is a list of imports. An import is either a bare symbol or a
  1156. pair of @code{(@var{out} . @var{in})}, where @var{out} and @var{in} are
  1157. both symbols and denote the name under which a binding is exported from
  1158. the module, and the name under which to make the binding available,
  1159. respectively. Note that @var{bindings} is only used as an input to the
  1160. default initializer for the @var{module} argument; if you pass
  1161. @code{#:module}, @var{bindings} is unused. If @var{sever-module?} is
  1162. true (the default), the module will be unlinked from the global module
  1163. tree after the evaluation returns, to allow @var{mod} to be
  1164. garbage-collected.
  1165. If successful, return all values produced by @var{exp}. Any uncaught
  1166. exception thrown by the expression will propagate out. If the time or
  1167. allocation limit is exceeded, an exception will be thrown to the
  1168. @code{limit-exceeded} key.
  1169. @end deffn
  1170. Constructing a safe sandbox module is tricky in general. Guile defines
  1171. an easy way to construct safe modules from predefined sets of bindings.
  1172. Before getting to that interface, here are some general notes on safety.
  1173. @enumerate
  1174. @item The time and allocation limits rely on the ability to interrupt
  1175. and cancel a computation. For this reason, no binding included in a
  1176. sandbox module should be able to indefinitely postpone interrupt
  1177. handling, nor should a binding be able to prevent an abort. In practice
  1178. this second consideration means that @code{dynamic-wind} should not be
  1179. included in any binding set.
  1180. @item The time and allocation limits apply only to the
  1181. @code{eval-in-sandbox} call. If the call returns a procedure which is
  1182. later called, no limit is ``automatically'' in place. Users of
  1183. @code{eval-in-sandbox} have to be very careful to reimpose limits when
  1184. calling procedures that escape from sandboxes.
  1185. @item Similarly, the dynamic environment of the @code{eval-in-sandbox}
  1186. call is not necessarily in place when any procedure that escapes from
  1187. the sandbox is later called.
  1188. This detail prevents us from exposing @code{primitive-eval} to the
  1189. sandbox, for two reasons. The first is that it's possible for legacy
  1190. code to forge references to any binding, if the
  1191. @code{allow-legacy-syntax-objects?} parameter is true. The default for
  1192. this parameter is true; @pxref{Syntax Transformer Helpers} for the
  1193. details. The parameter is bound to @code{#f} for the duration of the
  1194. @code{eval-in-sandbox} call itself, but that will not be in place during
  1195. calls to escaped procedures.
  1196. The second reason we don't expose @code{primitive-eval} is that
  1197. @code{primitive-eval} implicitly works in the current module, which for
  1198. an escaped procedure will probably be different than the module that is
  1199. current for the @code{eval-in-sandbox} call itself.
  1200. The common denominator here is that if an interface exposed to the
  1201. sandbox relies on dynamic environments, it is easy to mistakenly grant
  1202. the sandboxed procedure additional capabilities in the form of bindings
  1203. that it should not have access to. For this reason, the default sets of
  1204. predefined bindings do not depend on any dynamically scoped value.
  1205. @item Mutation may allow a sandboxed evaluation to break some invariant
  1206. in users of data supplied to it. A lot of code culturally doesn't
  1207. expect mutation, but if you hand mutable data to a sandboxed evaluation
  1208. and you also grant mutating capabilities to that evaluation, then the
  1209. sandboxed code may indeed mutate that data. The default set of bindings
  1210. to the sandbox do not include any mutating primitives.
  1211. Relatedly, @code{set!} may allow a sandbox to mutate a primitive,
  1212. invalidating many system-wide invariants. Guile is currently quite
  1213. permissive when it comes to imported bindings and mutability. Although
  1214. @code{set!} to a module-local or lexically bound variable would be fine,
  1215. we don't currently have an easy way to disallow @code{set!} to an
  1216. imported binding, so currently no binding set includes @code{set!}.
  1217. @item Mutation may allow a sandboxed evaluation to keep state, or
  1218. make a communication mechanism with other code. On the one hand this
  1219. sounds cool, but on the other hand maybe this is part of your threat
  1220. model. Again, the default set of bindings doesn't include mutating
  1221. primitives, preventing sandboxed evaluations from keeping state.
  1222. @item The sandbox should probably not be able to open a network
  1223. connection, or write to a file, or open a file from disk. The default
  1224. binding set includes no interaction with the operating system.
  1225. @end enumerate
  1226. If you, dear reader, find the above discussion interesting, you will
  1227. enjoy Jonathan Rees' dissertation, ``A Security Kernel Based on the
  1228. Lambda Calculus''.
  1229. @defvr {Scheme Variable} all-pure-bindings
  1230. All ``pure'' bindings that together form a safe subset of those bindings
  1231. available by default to Guile user code.
  1232. @end defvr
  1233. @defvr {Scheme Variable} all-pure-and-impure-bindings
  1234. Like @code{all-pure-bindings}, but additionally including mutating
  1235. primitives like @code{vector-set!}. This set is still safe in the sense
  1236. mentioned above, with the caveats about mutation.
  1237. @end defvr
  1238. The components of these composite sets are as follows:
  1239. @defvr {Scheme Variable} alist-bindings
  1240. @defvrx {Scheme Variable} array-bindings
  1241. @defvrx {Scheme Variable} bit-bindings
  1242. @defvrx {Scheme Variable} bitvector-bindings
  1243. @defvrx {Scheme Variable} char-bindings
  1244. @defvrx {Scheme Variable} char-set-bindings
  1245. @defvrx {Scheme Variable} clock-bindings
  1246. @defvrx {Scheme Variable} core-bindings
  1247. @defvrx {Scheme Variable} error-bindings
  1248. @defvrx {Scheme Variable} fluid-bindings
  1249. @defvrx {Scheme Variable} hash-bindings
  1250. @defvrx {Scheme Variable} iteration-bindings
  1251. @defvrx {Scheme Variable} keyword-bindings
  1252. @defvrx {Scheme Variable} list-bindings
  1253. @defvrx {Scheme Variable} macro-bindings
  1254. @defvrx {Scheme Variable} nil-bindings
  1255. @defvrx {Scheme Variable} number-bindings
  1256. @defvrx {Scheme Variable} pair-bindings
  1257. @defvrx {Scheme Variable} predicate-bindings
  1258. @defvrx {Scheme Variable} procedure-bindings
  1259. @defvrx {Scheme Variable} promise-bindings
  1260. @defvrx {Scheme Variable} prompt-bindings
  1261. @defvrx {Scheme Variable} regexp-bindings
  1262. @defvrx {Scheme Variable} sort-bindings
  1263. @defvrx {Scheme Variable} srfi-4-bindings
  1264. @defvrx {Scheme Variable} string-bindings
  1265. @defvrx {Scheme Variable} symbol-bindings
  1266. @defvrx {Scheme Variable} unspecified-bindings
  1267. @defvrx {Scheme Variable} variable-bindings
  1268. @defvrx {Scheme Variable} vector-bindings
  1269. @defvrx {Scheme Variable} version-bindings
  1270. The components of @code{all-pure-bindings}.
  1271. @end defvr
  1272. @defvr {Scheme Variable} mutating-alist-bindings
  1273. @defvrx {Scheme Variable} mutating-array-bindings
  1274. @defvrx {Scheme Variable} mutating-bitvector-bindings
  1275. @defvrx {Scheme Variable} mutating-fluid-bindings
  1276. @defvrx {Scheme Variable} mutating-hash-bindings
  1277. @defvrx {Scheme Variable} mutating-list-bindings
  1278. @defvrx {Scheme Variable} mutating-pair-bindings
  1279. @defvrx {Scheme Variable} mutating-sort-bindings
  1280. @defvrx {Scheme Variable} mutating-srfi-4-bindings
  1281. @defvrx {Scheme Variable} mutating-string-bindings
  1282. @defvrx {Scheme Variable} mutating-variable-bindings
  1283. @defvrx {Scheme Variable} mutating-vector-bindings
  1284. The additional components of @code{all-pure-and-impure-bindings}.
  1285. @end defvr
  1286. Finally, what do you do with a binding set? What is a binding set
  1287. anyway? @code{make-sandbox-module} is here for you.
  1288. @deffn {Scheme Procedure} make-sandbox-module bindings
  1289. Return a fresh module that only contains @var{bindings}.
  1290. The @var{bindings} should be given as a list of import sets. One import
  1291. set is a list whose car names an interface, like @code{(ice-9 q)}, and
  1292. whose cdr is a list of imports. An import is either a bare symbol or a
  1293. pair of @code{(@var{out} . @var{in})}, where @var{out} and @var{in} are
  1294. both symbols and denote the name under which a binding is exported from
  1295. the module, and the name under which to make the binding available,
  1296. respectively.
  1297. @end deffn
  1298. So you see that binding sets are just lists, and
  1299. @code{all-pure-and-impure-bindings} is really just the result of
  1300. appending all of the component binding sets.
  1301. @node REPL Servers
  1302. @subsection REPL Servers
  1303. @cindex REPL server
  1304. The procedures in this section are provided by
  1305. @lisp
  1306. (use-modules (system repl server))
  1307. @end lisp
  1308. When an application is written in Guile, it is often convenient to
  1309. allow the user to be able to interact with it by evaluating Scheme
  1310. expressions in a REPL.
  1311. The procedures of this module allow you to spawn a @dfn{REPL server},
  1312. which permits interaction over a local or TCP connection. Guile itself
  1313. uses them internally to implement the @option{--listen} switch,
  1314. @ref{Command-line Options}.
  1315. @deffn {Scheme Procedure} make-tcp-server-socket [#:host=#f] @
  1316. [#:addr] [#:port=37146]
  1317. Return a stream socket bound to a given address @var{addr} and port
  1318. number @var{port}. If the @var{host} is given, and @var{addr} is not,
  1319. then the @var{host} string is converted to an address. If neither is
  1320. given, we use the loopback address.
  1321. @end deffn
  1322. @deffn {Scheme Procedure} make-unix-domain-server-socket [#:path="/tmp/guile-socket"]
  1323. Return a UNIX domain socket, bound to a given @var{path}.
  1324. @end deffn
  1325. @deffn {Scheme Procedure} run-server [server-socket]
  1326. @deffnx {Scheme Procedure} spawn-server [server-socket]
  1327. Create and run a REPL, making it available over the given
  1328. @var{server-socket}. If @var{server-socket} is not provided, it
  1329. defaults to the socket created by calling @code{make-tcp-server-socket}
  1330. with no arguments.
  1331. @code{run-server} runs the server in the current thread, whereas
  1332. @code{spawn-server} runs the server in a new thread.
  1333. @end deffn
  1334. @deffn {Scheme Procedure} stop-server-and-clients!
  1335. Closes the connection on all running server sockets.
  1336. Please note that in the current implementation, the REPL threads are
  1337. canceled without unwinding their stacks. If any of them are holding
  1338. mutexes or are within a critical section, the results are unspecified.
  1339. @end deffn
  1340. @node Cooperative REPL Servers
  1341. @subsection Cooperative REPL Servers
  1342. @cindex Cooperative REPL server
  1343. The procedures in this section are provided by
  1344. @lisp
  1345. (use-modules (system repl coop-server))
  1346. @end lisp
  1347. Whereas ordinary REPL servers run in their own threads (@pxref{REPL
  1348. Servers}), sometimes it is more convenient to provide REPLs that run at
  1349. specified times within an existing thread, for example in programs
  1350. utilizing an event loop or in single-threaded programs. This allows for
  1351. safe access and mutation of a program's data structures from the REPL,
  1352. without concern for thread synchronization.
  1353. Although the REPLs are run in the thread that calls
  1354. @code{spawn-coop-repl-server} and @code{poll-coop-repl-server},
  1355. dedicated threads are spawned so that the calling thread is not blocked.
  1356. The spawned threads read input for the REPLs and to listen for new
  1357. connections.
  1358. Cooperative REPL servers must be polled periodically to evaluate any
  1359. pending expressions by calling @code{poll-coop-repl-server} with the
  1360. object returned from @code{spawn-coop-repl-server}. The thread that
  1361. calls @code{poll-coop-repl-server} will be blocked for as long as the
  1362. expression takes to be evaluated or if the debugger is entered.
  1363. @deffn {Scheme Procedure} spawn-coop-repl-server [server-socket]
  1364. Create and return a new cooperative REPL server object, and spawn a new
  1365. thread to listen for connections on @var{server-socket}. Proper
  1366. functioning of the REPL server requires that
  1367. @code{poll-coop-repl-server} be called periodically on the returned
  1368. server object.
  1369. @end deffn
  1370. @deffn {Scheme Procedure} poll-coop-repl-server coop-server
  1371. Poll the cooperative REPL server @var{coop-server} and apply a pending
  1372. operation if there is one, such as evaluating an expression typed at the
  1373. REPL prompt. This procedure must be called from the same thread that
  1374. called @code{spawn-coop-repl-server}.
  1375. @end deffn
  1376. @c Local Variables:
  1377. @c TeX-master: "guile.texi"
  1378. @c End: