api-evaluation.texi 64 KB

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