api-evaluation.texi 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617
  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 --r6rs
  557. @itemx --r7rs
  558. Compile in an environment whose default bindings, reader options, and
  559. load paths are adapted for specific Scheme standards. @xref{R6RS
  560. Support}, and @xref{R7RS Support}.
  561. @item -f @var{lang}
  562. @itemx --from=@var{lang}
  563. Use @var{lang} as the source language of @var{file}. If this option is omitted,
  564. @code{scheme} is assumed.
  565. @item -t @var{lang}
  566. @itemx --to=@var{lang}
  567. Use @var{lang} as the target language of @var{file}. If this option is omitted,
  568. @code{rtl} is assumed.
  569. @item -T @var{target}
  570. @itemx --target=@var{target}
  571. Produce code for @var{target} instead of @var{%host-type} (@pxref{Build
  572. Config, %host-type}). Target must be a valid GNU triplet, such as
  573. @code{armv5tel-unknown-linux-gnueabi} (@pxref{Specifying Target
  574. Triplets,,, autoconf, GNU Autoconf Manual}).
  575. @end table
  576. Each @var{file} is assumed to be UTF-8-encoded, unless it contains a
  577. coding declaration as recognized by @code{file-encoding}
  578. (@pxref{Character Encoding of Source Files}).
  579. @end deffn
  580. The compiler can also be invoked directly by Scheme code using the procedures
  581. below:
  582. @deffn {Scheme Procedure} compile exp [#:env=#f] @
  583. [#:from=(current-language)] @
  584. [#:to=value] [#:opts=()]
  585. Compile the expression @var{exp} in the environment @var{env}. If
  586. @var{exp} is a procedure, the result will be a compiled procedure;
  587. otherwise @code{compile} is mostly equivalent to @code{eval}.
  588. For a discussion of languages and compiler options, @xref{Compiling to
  589. the Virtual Machine}.
  590. @end deffn
  591. @deffn {Scheme Procedure} compile-file file [#:output-file=#f] @
  592. [#:from=(current-language)] [#:to='rtl] @
  593. [#:env=(default-environment from)] @
  594. [#:opts='()] @
  595. [#:canonicalization='relative]
  596. Compile the file named @var{file}.
  597. Output will be written to a @var{output-file}. If you do not supply an
  598. output file name, output is written to a file in the cache directory, as
  599. computed by @code{(compiled-file-name @var{file})}.
  600. @var{from} and @var{to} specify the source and target languages.
  601. @xref{Compiling to the Virtual Machine}, for more information on these
  602. options, and on @var{env} and @var{opts}.
  603. As with @command{guild compile}, @var{file} is assumed to be
  604. UTF-8-encoded unless it contains a coding declaration.
  605. @end deffn
  606. @deffn {Scheme Procedure} compiled-file-name file
  607. Compute a cached location for a compiled version of a Scheme file named
  608. @var{file}.
  609. This file will usually be below the @file{$HOME/.cache/guile/ccache}
  610. directory, depending on the value of the @env{XDG_CACHE_HOME}
  611. environment variable. The intention is that @code{compiled-file-name}
  612. provides a fallback location for caching auto-compiled files. If you
  613. want to place a compile file in the @code{%load-compiled-path}, you
  614. should pass the @var{output-file} option to @code{compile-file},
  615. explicitly.
  616. @end deffn
  617. @defvr {Scheme Variable} %auto-compilation-options
  618. This variable contains the options passed to the @code{compile-file}
  619. procedure when auto-compiling source files. By default, it enables
  620. useful compilation warnings. It can be customized from @file{~/.guile}.
  621. @end defvr
  622. @node Loading
  623. @subsection Loading Scheme Code from File
  624. @rnindex load
  625. @deffn {Scheme Procedure} load filename [reader]
  626. Load @var{filename} and evaluate its contents in the top-level
  627. environment.
  628. @var{reader} if provided should be either @code{#f}, or a procedure with
  629. the signature @code{(lambda (port) @dots{})} which reads the next
  630. expression from @var{port}. If @var{reader} is @code{#f} or absent,
  631. Guile's built-in @code{read} procedure is used (@pxref{Scheme Read}).
  632. The @var{reader} argument takes effect by setting the value of the
  633. @code{current-reader} fluid (see below) before loading the file, and
  634. restoring its previous value when loading is complete. The Scheme code
  635. inside @var{filename} can itself change the current reader procedure on
  636. the fly by setting @code{current-reader} fluid.
  637. If the variable @code{%load-hook} is defined, it should be bound to a
  638. procedure that will be called before any code is loaded. See
  639. documentation for @code{%load-hook} later in this section.
  640. @end deffn
  641. @deffn {Scheme Procedure} load-compiled filename
  642. Load the compiled file named @var{filename}.
  643. Compiling a source file (@pxref{Read/Load/Eval/Compile}) and then
  644. calling @code{load-compiled} on the resulting file is equivalent to
  645. calling @code{load} on the source file.
  646. @end deffn
  647. @deffn {Scheme Procedure} primitive-load filename
  648. @deffnx {C Function} scm_primitive_load (filename)
  649. Load the file named @var{filename} and evaluate its contents in the
  650. top-level environment. @var{filename} must either be a full pathname or
  651. be a pathname relative to the current directory. If the variable
  652. @code{%load-hook} is defined, it should be bound to a procedure that
  653. will be called before any code is loaded. See the documentation for
  654. @code{%load-hook} later in this section.
  655. @end deffn
  656. @deftypefn {C Function} SCM scm_c_primitive_load (const char *filename)
  657. @code{scm_primitive_load}, but taking a C string instead of an
  658. @code{SCM}.
  659. @end deftypefn
  660. @defvar current-reader
  661. @code{current-reader} holds the read procedure that is currently being
  662. used by the above loading procedures to read expressions (from the file
  663. that they are loading). @code{current-reader} is a fluid, so it has an
  664. independent value in each dynamic root and should be read and set using
  665. @code{fluid-ref} and @code{fluid-set!} (@pxref{Fluids and Dynamic
  666. States}).
  667. Changing @code{current-reader} is typically useful to introduce local
  668. syntactic changes, such that code following the @code{fluid-set!} call
  669. is read using the newly installed reader. The @code{current-reader}
  670. change should take place at evaluation time when the code is evaluated,
  671. or at compilation time when the code is compiled:
  672. @findex eval-when
  673. @example
  674. (eval-when (compile eval)
  675. (fluid-set! current-reader my-own-reader))
  676. @end example
  677. The @code{eval-when} form above ensures that the @code{current-reader}
  678. change occurs at the right time.
  679. @end defvar
  680. @defvar %load-hook
  681. A procedure to be called @code{(%load-hook @var{filename})} whenever a
  682. file is loaded, or @code{#f} for no such call. @code{%load-hook} is
  683. used by all of the loading functions (@code{load} and
  684. @code{primitive-load}, and @code{load-from-path} and
  685. @code{primitive-load-path} documented in the next section).
  686. For example an application can set this to show what's loaded,
  687. @example
  688. (set! %load-hook (lambda (filename)
  689. (format #t "Loading ~a ...\n" filename)))
  690. (load-from-path "foo.scm")
  691. @print{} Loading /usr/local/share/guile/site/foo.scm ...
  692. @end example
  693. @end defvar
  694. @deffn {Scheme Procedure} current-load-port
  695. @deffnx {C Function} scm_current_load_port ()
  696. Return the current-load-port.
  697. The load port is used internally by @code{primitive-load}.
  698. @end deffn
  699. @node Load Paths
  700. @subsection Load Paths
  701. The procedure in the previous section look for Scheme code in the file
  702. system at specific location. Guile also has some procedures to search
  703. the load path for code.
  704. @defvar %load-path
  705. List of directories which should be searched for Scheme modules and
  706. libraries. When Guile starts up, @code{%load-path} is initialized to
  707. the default load path @code{(list (%library-dir) (%site-dir)
  708. (%global-site-dir) (%package-data-dir))}. The @env{GUILE_LOAD_PATH}
  709. environment variable can be used to prepend or append additional
  710. directories (@pxref{Environment Variables}).
  711. @xref{Build Config}, for more on @code{%site-dir} and related
  712. procedures.
  713. @end defvar
  714. @deffn {Scheme Procedure} load-from-path filename
  715. Similar to @code{load}, but searches for @var{filename} in the load
  716. paths. Preferentially loads a compiled version of the file, if it is
  717. available and up-to-date.
  718. @end deffn
  719. A user can extend the load path by calling @code{add-to-load-path}.
  720. @deffn {Scheme Syntax} add-to-load-path dir
  721. Add @var{dir} to the load path.
  722. @end deffn
  723. For example, a script might include this form to add the directory that
  724. it is in to the load path:
  725. @example
  726. (add-to-load-path (dirname (current-filename)))
  727. @end example
  728. It's better to use @code{add-to-load-path} than to modify
  729. @code{%load-path} directly, because @code{add-to-load-path} takes care
  730. of modifying the path both at compile-time and at run-time.
  731. @deffn {Scheme Procedure} primitive-load-path filename [exception-on-not-found]
  732. @deffnx {C Function} scm_primitive_load_path (filename)
  733. Search @code{%load-path} for the file named @var{filename} and
  734. load it into the top-level environment. If @var{filename} is a
  735. relative pathname and is not found in the list of search paths,
  736. an error is signalled. Preferentially loads a compiled version of the
  737. file, if it is available and up-to-date.
  738. If @var{filename} is a relative pathname and is not found in the list of
  739. search paths, one of three things may happen, depending on the optional
  740. second argument, @var{exception-on-not-found}. If it is @code{#f},
  741. @code{#f} will be returned. If it is a procedure, it will be called
  742. with no arguments. (This allows a distinction to be made between
  743. exceptions raised by loading a file, and exceptions related to the
  744. loader itself.) Otherwise an error is signalled.
  745. For compatibility with Guile 1.8 and earlier, the C function takes only
  746. one argument, which can be either a string (the file name) or an
  747. argument list.
  748. @end deffn
  749. @deffn {Scheme Procedure} %search-load-path filename
  750. @deffnx {C Function} scm_sys_search_load_path (filename)
  751. Search @code{%load-path} for the file named @var{filename}, which must
  752. be readable by the current user. If @var{filename} is found in the list
  753. of paths to search or is an absolute pathname, return its full pathname.
  754. Otherwise, return @code{#f}. Filenames may have any of the optional
  755. extensions in the @code{%load-extensions} list; @code{%search-load-path}
  756. will try each extension automatically.
  757. @end deffn
  758. @defvar %load-extensions
  759. A list of default file extensions for files containing Scheme code.
  760. @code{%search-load-path} tries each of these extensions when looking for
  761. a file to load. By default, @code{%load-extensions} is bound to the
  762. list @code{("" ".scm")}.
  763. @end defvar
  764. As mentioned above, when Guile searches the @code{%load-path} for a
  765. source file, it will also search the @code{%load-compiled-path} for a
  766. corresponding compiled file. If the compiled file is as new or newer
  767. than the source file, it will be loaded instead of the source file,
  768. using @code{load-compiled}.
  769. @defvar %load-compiled-path
  770. Like @code{%load-path}, but for compiled files. By default, this path
  771. has two entries: one for compiled files from Guile itself, and one for
  772. site packages. The @env{GUILE_LOAD_COMPILED_PATH} environment variable
  773. can be used to prepend or append additional directories
  774. (@pxref{Environment Variables}).
  775. @end defvar
  776. When @code{primitive-load-path} searches the @code{%load-compiled-path}
  777. for a corresponding compiled file for a relative path it does so by
  778. appending @code{.go} to the relative path. For example, searching for
  779. @code{ice-9/popen} could find
  780. @code{/usr/lib/guile/3.0/ccache/ice-9/popen.go}, and use it instead of
  781. @code{/usr/share/guile/3.0/ice-9/popen.scm}.
  782. If @code{primitive-load-path} does not find a corresponding @code{.go}
  783. file in the @code{%load-compiled-path}, or the @code{.go} file is out of
  784. date, it will search for a corresponding auto-compiled file in the
  785. fallback path, possibly creating one if one does not exist.
  786. @xref{Installing Site Packages}, for more on how to correctly install
  787. site packages. @xref{Modules and the File System}, for more on the
  788. relationship between load paths and modules. @xref{Compilation}, for
  789. more on the fallback path and auto-compilation.
  790. Finally, there are a couple of helper procedures for general path
  791. manipulation.
  792. @deffn {Scheme Procedure} parse-path path [tail]
  793. @deffnx {C Function} scm_parse_path (path, tail)
  794. Parse @var{path}, which is expected to be a colon-separated string, into
  795. a list and return the resulting list with @var{tail} appended. If
  796. @var{path} is @code{#f}, @var{tail} is returned.
  797. @end deffn
  798. @deffn {Scheme Procedure} parse-path-with-ellipsis path base
  799. @deffnx {C Function} scm_parse_path_with_ellipsis (path, base)
  800. Parse @var{path}, which is expected to be a colon-separated string, into
  801. a list and return the resulting list with @var{base} (a list) spliced in
  802. place of the @code{...} path component, if present, or else @var{base}
  803. is added to the end. If @var{path} is @code{#f}, @var{base} is
  804. returned.
  805. @end deffn
  806. @deffn {Scheme Procedure} search-path path filename [extensions [require-exts?]]
  807. @deffnx {C Function} scm_search_path (path, filename, rest)
  808. Search @var{path} for a directory containing a file named
  809. @var{filename}. The file must be readable, and not a directory. If we
  810. find one, return its full filename; otherwise, return @code{#f}. If
  811. @var{filename} is absolute, return it unchanged. If given,
  812. @var{extensions} is a list of strings; for each directory in @var{path},
  813. we search for @var{filename} concatenated with each @var{extension}. If
  814. @var{require-exts?} is true, require that the returned file name have
  815. one of the given extensions; if @var{require-exts?} is not given, it
  816. defaults to @code{#f}.
  817. For compatibility with Guile 1.8 and earlier, the C function takes only
  818. three arguments.
  819. @end deffn
  820. @node Character Encoding of Source Files
  821. @subsection Character Encoding of Source Files
  822. @cindex source file encoding
  823. @cindex primitive-load
  824. @cindex load
  825. Scheme source code files are usually encoded in ASCII or UTF-8, but the
  826. built-in reader can interpret other character encodings as well. When
  827. Guile loads Scheme source code, it uses the @code{file-encoding}
  828. procedure (described below) to try to guess the encoding of the file.
  829. In the absence of any hints, UTF-8 is assumed. One way to provide a
  830. hint about the encoding of a source file is to place a coding
  831. declaration in the top 500 characters of the file.
  832. A coding declaration has the form @code{coding: XXXXXX}, where
  833. @code{XXXXXX} is the name of a character encoding in which the source
  834. code file has been encoded. The coding declaration must appear in a
  835. scheme comment. It can either be a semicolon-initiated comment, or the
  836. first block @code{#!} comment in the file.
  837. The name of the character encoding in the coding declaration is
  838. typically lower case and containing only letters, numbers, and hyphens,
  839. as recognized by @code{set-port-encoding!} (@pxref{Ports,
  840. @code{set-port-encoding!}}). Common examples of character encoding
  841. names are @code{utf-8} and @code{iso-8859-1},
  842. @url{http://www.iana.org/assignments/character-sets, as defined by
  843. IANA}. Thus, the coding declaration is mostly compatible with Emacs.
  844. However, there are some differences in encoding names recognized by
  845. Emacs and encoding names defined by IANA, the latter being essentially a
  846. subset of the former. For instance, @code{latin-1} is a valid encoding
  847. name for Emacs, but it's not according to the IANA standard, which Guile
  848. follows; instead, you should use @code{iso-8859-1}, which is both
  849. understood by Emacs and dubbed by IANA (IANA writes it uppercase but
  850. Emacs wants it lowercase and Guile is case insensitive.)
  851. For source code, only a subset of all possible character encodings can
  852. be interpreted by the built-in source code reader. Only those
  853. character encodings in which ASCII text appears unmodified can be
  854. used. This includes @code{UTF-8} and @code{ISO-8859-1} through
  855. @code{ISO-8859-15}. The multi-byte character encodings @code{UTF-16}
  856. and @code{UTF-32} may not be used because they are not compatible with
  857. ASCII.
  858. @cindex read
  859. @cindex encoding
  860. @cindex port encoding
  861. @findex set-port-encoding!
  862. There might be a scenario in which one would want to read non-ASCII
  863. code from a port, such as with the function @code{read}, instead of
  864. with @code{load}. If the port's character encoding is the same as the
  865. encoding of the code to be read by the port, not other special
  866. handling is necessary. The port will automatically do the character
  867. encoding conversion. The functions @code{setlocale} or by
  868. @code{set-port-encoding!} are used to set port encodings
  869. (@pxref{Ports}).
  870. If a port is used to read code of unknown character encoding, it can
  871. accomplish this in three steps. First, the character encoding of the
  872. port should be set to ISO-8859-1 using @code{set-port-encoding!}.
  873. Then, the procedure @code{file-encoding}, described below, is used to
  874. scan for a coding declaration when reading from the port. As a side
  875. effect, it rewinds the port after its scan is complete. After that,
  876. the port's character encoding should be set to the encoding returned
  877. by @code{file-encoding}, if any, again by using
  878. @code{set-port-encoding!}. Then the code can be read as normal.
  879. Alternatively, one can use the @code{#:guess-encoding} keyword argument
  880. of @code{open-file} and related procedures. @xref{File Ports}.
  881. @deffn {Scheme Procedure} file-encoding port
  882. @deffnx {C Function} scm_file_encoding (port)
  883. Attempt to scan the first few hundred bytes from the @var{port} for
  884. hints about its character encoding. Return a string containing the
  885. encoding name or @code{#f} if the encoding cannot be determined. The
  886. port is rewound.
  887. Currently, the only supported method is to look for an Emacs-like
  888. character coding declaration (@pxref{Recognize Coding, how Emacs
  889. recognizes file encoding,, emacs, The GNU Emacs Reference Manual}). The
  890. coding declaration is of the form @code{coding: XXXXX} and must appear
  891. in a Scheme comment. Additional heuristics may be added in the future.
  892. @end deffn
  893. @node Delayed Evaluation
  894. @subsection Delayed Evaluation
  895. @cindex delayed evaluation
  896. @cindex promises
  897. Promises are a convenient way to defer a calculation until its result
  898. is actually needed, and to run such a calculation only once. Also
  899. @pxref{SRFI-45}.
  900. @deffn syntax delay expr
  901. @rnindex delay
  902. Return a promise object which holds the given @var{expr} expression,
  903. ready to be evaluated by a later @code{force}.
  904. @end deffn
  905. @deffn {Scheme Procedure} promise? obj
  906. @deffnx {C Function} scm_promise_p (obj)
  907. Return true if @var{obj} is a promise.
  908. @end deffn
  909. @rnindex force
  910. @deffn {Scheme Procedure} force p
  911. @deffnx {C Function} scm_force (p)
  912. Return the value obtained from evaluating the @var{expr} in the given
  913. promise @var{p}. If @var{p} has previously been forced then its
  914. @var{expr} is not evaluated again, instead the value obtained at that
  915. time is simply returned.
  916. During a @code{force}, an @var{expr} can call @code{force} again on
  917. its own promise, resulting in a recursive evaluation of that
  918. @var{expr}. The first evaluation to return gives the value for the
  919. promise. Higher evaluations run to completion in the normal way, but
  920. their results are ignored, @code{force} always returns the first
  921. value.
  922. @end deffn
  923. @node Local Evaluation
  924. @subsection Local Evaluation
  925. Guile includes a facility to capture a lexical environment, and later
  926. evaluate a new expression within that environment. This code is
  927. implemented in a module.
  928. @example
  929. (use-modules (ice-9 local-eval))
  930. @end example
  931. @deffn syntax the-environment
  932. Captures and returns a lexical environment for use with
  933. @code{local-eval} or @code{local-compile}.
  934. @end deffn
  935. @deffn {Scheme Procedure} local-eval exp env
  936. @deffnx {C Function} scm_local_eval (exp, env)
  937. @deffnx {Scheme Procedure} local-compile exp env [opts=()]
  938. Evaluate or compile the expression @var{exp} in the lexical environment
  939. @var{env}.
  940. @end deffn
  941. Here is a simple example, illustrating that it is the variable
  942. that gets captured, not just its value at one point in time.
  943. @example
  944. (define e (let ((x 100)) (the-environment)))
  945. (define fetch-x (local-eval '(lambda () x) e))
  946. (fetch-x)
  947. @result{} 100
  948. (local-eval '(set! x 42) e)
  949. (fetch-x)
  950. @result{} 42
  951. @end example
  952. While @var{exp} is evaluated within the lexical environment of
  953. @code{(the-environment)}, it has the dynamic environment of the call to
  954. @code{local-eval}.
  955. @code{local-eval} and @code{local-compile} can only evaluate
  956. expressions, not definitions.
  957. @example
  958. (local-eval '(define foo 42)
  959. (let ((x 100)) (the-environment)))
  960. @result{} syntax error: definition in expression context
  961. @end example
  962. Note that the current implementation of @code{(the-environment)} only
  963. captures ``normal'' lexical bindings, and pattern variables bound by
  964. @code{syntax-case}. It does not currently capture local syntax
  965. transformers bound by @code{let-syntax}, @code{letrec-syntax} or
  966. non-top-level @code{define-syntax} forms. Any attempt to reference such
  967. captured syntactic keywords via @code{local-eval} or
  968. @code{local-compile} produces an error.
  969. @node Local Inclusion
  970. @subsection Local Inclusion
  971. This section has discussed various means of linking Scheme code
  972. together: fundamentally, loading up files at run-time using @code{load}
  973. and @code{load-compiled}. Guile provides another option to compose
  974. parts of programs together at expansion-time instead of at run-time.
  975. @deffn {Scheme Syntax} include file-name
  976. Open @var{file-name}, at expansion-time, and read the Scheme forms that
  977. it contains, splicing them into the location of the @code{include},
  978. within a @code{begin}.
  979. If @var{file-name} is a relative path, it is searched for relative to
  980. the path that contains the file that the @code{include} form appears in.
  981. @end deffn
  982. If you are a C programmer, if @code{load} in Scheme is like
  983. @code{dlopen} in C, consider @code{include} to be like the C
  984. preprocessor's @code{#include}. When you use @code{include}, it is as
  985. if the contents of the included file were typed in instead of the
  986. @code{include} form.
  987. Because the code is included at compile-time, it is available to the
  988. macroexpander. Syntax definitions in the included file are available to
  989. later code in the form in which the @code{include} appears, without the
  990. need for @code{eval-when}. (@xref{Eval When}.)
  991. For the same reason, compiling a form that uses @code{include} results
  992. in one compilation unit, composed of multiple files. Loading the
  993. compiled file is one @code{stat} operation for the compilation unit,
  994. instead of @code{2*@var{n}} in the case of @code{load} (once for each
  995. loaded source file, and once each corresponding compiled file, in the
  996. best case).
  997. Unlike @code{load}, @code{include} also works within nested lexical
  998. contexts. It so happens that the optimizer works best within a lexical
  999. context, because all of the uses of bindings in a lexical context are
  1000. visible, so composing files by including them within a @code{(let ()
  1001. ...)} can sometimes lead to important speed improvements.
  1002. On the other hand, @code{include} does have all the disadvantages of
  1003. early binding: once the code with the @code{include} is compiled, no
  1004. change to the included file is reflected in the future behavior of the
  1005. including form.
  1006. Also, the particular form of @code{include}, which requires an absolute
  1007. path, or a path relative to the current directory at compile-time, is
  1008. not very amenable to compiling the source in one place, but then
  1009. installing the source to another place. For this reason, Guile provides
  1010. another form, @code{include-from-path}, which looks for the source file
  1011. to include within a load path.
  1012. @deffn {Scheme Syntax} include-from-path file-name
  1013. Like @code{include}, but instead of expecting @code{file-name} to be an
  1014. absolute file name, it is expected to be a relative path to search in
  1015. the @code{%load-path}.
  1016. @end deffn
  1017. @code{include-from-path} is more useful when you want to install all of
  1018. the source files for a package (as you should!). It makes it possible
  1019. to evaluate an installed file from source, instead of relying on the
  1020. @code{.go} file being up to date.
  1021. @node Sandboxed Evaluation
  1022. @subsection Sandboxed Evaluation
  1023. Sometimes you would like to evaluate code that comes from an untrusted
  1024. party. The safest way to do this is to buy a new computer, evaluate the
  1025. code on that computer, then throw the machine away. However if you are
  1026. unwilling to take this simple approach, Guile does include a limited
  1027. ``sandbox'' facility that can allow untrusted code to be evaluated with
  1028. some confidence.
  1029. To use the sandboxed evaluator, load its module:
  1030. @example
  1031. (use-modules (ice-9 sandbox))
  1032. @end example
  1033. Guile's sandboxing facility starts with the ability to restrict the time
  1034. and space used by a piece of code.
  1035. @deffn {Scheme Procedure} call-with-time-limit limit thunk limit-reached
  1036. Call @var{thunk}, but cancel it if @var{limit} seconds of wall-clock
  1037. time have elapsed. If the computation is cancelled, call
  1038. @var{limit-reached} in tail position. @var{thunk} must not disable
  1039. interrupts or prevent an abort via a @code{dynamic-wind} unwind handler.
  1040. @end deffn
  1041. @deffn {Scheme Procedure} call-with-allocation-limit limit thunk limit-reached
  1042. Call @var{thunk}, but cancel it if @var{limit} bytes have been
  1043. allocated. If the computation is cancelled, call @var{limit-reached} in
  1044. tail position. @var{thunk} must not disable interrupts or prevent an
  1045. abort via a @code{dynamic-wind} unwind handler.
  1046. This limit applies to both stack and heap allocation. The computation
  1047. will not be aborted before @var{limit} bytes have been allocated, but
  1048. for the heap allocation limit, the check may be postponed until the next garbage collection.
  1049. Note that as a current shortcoming, the heap size limit applies to all
  1050. threads; concurrent allocation by other unrelated threads counts towards
  1051. the allocation limit.
  1052. @end deffn
  1053. @deffn {Scheme Procedure} call-with-time-and-allocation-limits time-limit allocation-limit thunk
  1054. Invoke @var{thunk} in a dynamic extent in which its execution is limited
  1055. to @var{time-limit} seconds of wall-clock time, and its allocation to
  1056. @var{allocation-limit} bytes. @var{thunk} must not disable interrupts
  1057. or prevent an abort via a @code{dynamic-wind} unwind handler.
  1058. If successful, return all values produced by invoking @var{thunk}. Any
  1059. uncaught exception thrown by the thunk will propagate out. If the time
  1060. or allocation limit is exceeded, an exception will be thrown to the
  1061. @code{limit-exceeded} key.
  1062. @end deffn
  1063. The time limit and stack limit are both very precise, but the heap limit
  1064. only gets checked asynchronously, after a garbage collection. In
  1065. particular, if the heap is already very large, the number of allocated
  1066. bytes between garbage collections will be large, and therefore the
  1067. precision of the check is reduced.
  1068. Additionally, due to the mechanism used by the allocation limit (the
  1069. @code{after-gc-hook}), large single allocations like @code{(make-vector
  1070. #e1e7)} are only detected after the allocation completes, even if the
  1071. allocation itself causes garbage collection. It's possible therefore
  1072. for user code to not only exceed the allocation limit set, but also to
  1073. exhaust all available memory, causing out-of-memory conditions at any
  1074. allocation site. Failure to allocate memory in Guile itself should be
  1075. safe and cause an exception to be thrown, but most systems are not
  1076. designed to handle @code{malloc} failures. An allocation failure may
  1077. therefore exercise unexpected code paths in your system, so it is a
  1078. weakness of the sandbox (and therefore an interesting point of attack).
  1079. The main sandbox interface is @code{eval-in-sandbox}.
  1080. @deffn {Scheme Procedure} eval-in-sandbox exp [#:time-limit 0.1] @
  1081. [#:allocation-limit #e10e6] @
  1082. [#:bindings all-pure-bindings] @
  1083. [#:module (make-sandbox-module bindings)] @
  1084. [#:sever-module? #t]
  1085. Evaluate the Scheme expression @var{exp} within an isolated
  1086. "sandbox". Limit its execution to @var{time-limit} seconds of
  1087. wall-clock time, and limit its allocation to @var{allocation-limit}
  1088. bytes.
  1089. The evaluation will occur in @var{module}, which defaults to the result
  1090. of calling @code{make-sandbox-module} on @var{bindings}, which itself
  1091. defaults to @code{all-pure-bindings}. This is the core of the
  1092. sandbox: creating a scope for the expression that is @dfn{safe}.
  1093. A safe sandbox module has two characteristics. Firstly, it will not
  1094. allow the expression being evaluated to avoid being cancelled due to
  1095. time or allocation limits. This ensures that the expression terminates
  1096. in a timely fashion.
  1097. Secondly, a safe sandbox module will prevent the evaluation from
  1098. receiving information from previous evaluations, or from affecting
  1099. future evaluations. All combinations of binding sets exported by
  1100. @code{(ice-9 sandbox)} form safe sandbox modules.
  1101. The @var{bindings} should be given as a list of import sets. One import
  1102. set is a list whose car names an interface, like @code{(ice-9 q)}, and
  1103. whose cdr is a list of imports. An import is either a bare symbol or a
  1104. pair of @code{(@var{out} . @var{in})}, where @var{out} and @var{in} are
  1105. both symbols and denote the name under which a binding is exported from
  1106. the module, and the name under which to make the binding available,
  1107. respectively. Note that @var{bindings} is only used as an input to the
  1108. default initializer for the @var{module} argument; if you pass
  1109. @code{#:module}, @var{bindings} is unused. If @var{sever-module?} is
  1110. true (the default), the module will be unlinked from the global module
  1111. tree after the evaluation returns, to allow @var{mod} to be
  1112. garbage-collected.
  1113. If successful, return all values produced by @var{exp}. Any uncaught
  1114. exception thrown by the expression will propagate out. If the time or
  1115. allocation limit is exceeded, an exception will be thrown to the
  1116. @code{limit-exceeded} key.
  1117. @end deffn
  1118. Constructing a safe sandbox module is tricky in general. Guile defines
  1119. an easy way to construct safe modules from predefined sets of bindings.
  1120. Before getting to that interface, here are some general notes on safety.
  1121. @enumerate
  1122. @item The time and allocation limits rely on the ability to interrupt
  1123. and cancel a computation. For this reason, no binding included in a
  1124. sandbox module should be able to indefinitely postpone interrupt
  1125. handling, nor should a binding be able to prevent an abort. In practice
  1126. this second consideration means that @code{dynamic-wind} should not be
  1127. included in any binding set.
  1128. @item The time and allocation limits apply only to the
  1129. @code{eval-in-sandbox} call. If the call returns a procedure which is
  1130. later called, no limit is ``automatically'' in place. Users of
  1131. @code{eval-in-sandbox} have to be very careful to reimpose limits when
  1132. calling procedures that escape from sandboxes.
  1133. @item Similarly, the dynamic environment of the @code{eval-in-sandbox}
  1134. call is not necessarily in place when any procedure that escapes from
  1135. the sandbox is later called.
  1136. This detail prevents us from exposing @code{primitive-eval} to the
  1137. sandbox, for two reasons. The first is that it's possible for legacy
  1138. code to forge references to any binding, if the
  1139. @code{allow-legacy-syntax-objects?} parameter is true. The default for
  1140. this parameter is true; @pxref{Syntax Transformer Helpers} for the
  1141. details. The parameter is bound to @code{#f} for the duration of the
  1142. @code{eval-in-sandbox} call itself, but that will not be in place during
  1143. calls to escaped procedures.
  1144. The second reason we don't expose @code{primitive-eval} is that
  1145. @code{primitive-eval} implicitly works in the current module, which for
  1146. an escaped procedure will probably be different than the module that is
  1147. current for the @code{eval-in-sandbox} call itself.
  1148. The common denominator here is that if an interface exposed to the
  1149. sandbox relies on dynamic environments, it is easy to mistakenly grant
  1150. the sandboxed procedure additional capabilities in the form of bindings
  1151. that it should not have access to. For this reason, the default sets of
  1152. predefined bindings do not depend on any dynamically scoped value.
  1153. @item Mutation may allow a sandboxed evaluation to break some invariant
  1154. in users of data supplied to it. A lot of code culturally doesn't
  1155. expect mutation, but if you hand mutable data to a sandboxed evaluation
  1156. and you also grant mutating capabilities to that evaluation, then the
  1157. sandboxed code may indeed mutate that data. The default set of bindings
  1158. to the sandbox do not include any mutating primitives.
  1159. Relatedly, @code{set!} may allow a sandbox to mutate a primitive,
  1160. invalidating many system-wide invariants. Guile is currently quite
  1161. permissive when it comes to imported bindings and mutability. Although
  1162. @code{set!} to a module-local or lexically bound variable would be fine,
  1163. we don't currently have an easy way to disallow @code{set!} to an
  1164. imported binding, so currently no binding set includes @code{set!}.
  1165. @item Mutation may allow a sandboxed evaluation to keep state, or
  1166. make a communication mechanism with other code. On the one hand this
  1167. sounds cool, but on the other hand maybe this is part of your threat
  1168. model. Again, the default set of bindings doesn't include mutating
  1169. primitives, preventing sandboxed evaluations from keeping state.
  1170. @item The sandbox should probably not be able to open a network
  1171. connection, or write to a file, or open a file from disk. The default
  1172. binding set includes no interaction with the operating system.
  1173. @end enumerate
  1174. If you, dear reader, find the above discussion interesting, you will
  1175. enjoy Jonathan Rees' dissertation, ``A Security Kernel Based on the
  1176. Lambda Calculus''.
  1177. @defvr {Scheme Variable} all-pure-bindings
  1178. All ``pure'' bindings that together form a safe subset of those bindings
  1179. available by default to Guile user code.
  1180. @end defvr
  1181. @defvr {Scheme Variable} all-pure-and-impure-bindings
  1182. Like @code{all-pure-bindings}, but additionally including mutating
  1183. primitives like @code{vector-set!}. This set is still safe in the sense
  1184. mentioned above, with the caveats about mutation.
  1185. @end defvr
  1186. The components of these composite sets are as follows:
  1187. @defvr {Scheme Variable} alist-bindings
  1188. @defvrx {Scheme Variable} array-bindings
  1189. @defvrx {Scheme Variable} bit-bindings
  1190. @defvrx {Scheme Variable} bitvector-bindings
  1191. @defvrx {Scheme Variable} char-bindings
  1192. @defvrx {Scheme Variable} char-set-bindings
  1193. @defvrx {Scheme Variable} clock-bindings
  1194. @defvrx {Scheme Variable} core-bindings
  1195. @defvrx {Scheme Variable} error-bindings
  1196. @defvrx {Scheme Variable} fluid-bindings
  1197. @defvrx {Scheme Variable} hash-bindings
  1198. @defvrx {Scheme Variable} iteration-bindings
  1199. @defvrx {Scheme Variable} keyword-bindings
  1200. @defvrx {Scheme Variable} list-bindings
  1201. @defvrx {Scheme Variable} macro-bindings
  1202. @defvrx {Scheme Variable} nil-bindings
  1203. @defvrx {Scheme Variable} number-bindings
  1204. @defvrx {Scheme Variable} pair-bindings
  1205. @defvrx {Scheme Variable} predicate-bindings
  1206. @defvrx {Scheme Variable} procedure-bindings
  1207. @defvrx {Scheme Variable} promise-bindings
  1208. @defvrx {Scheme Variable} prompt-bindings
  1209. @defvrx {Scheme Variable} regexp-bindings
  1210. @defvrx {Scheme Variable} sort-bindings
  1211. @defvrx {Scheme Variable} srfi-4-bindings
  1212. @defvrx {Scheme Variable} string-bindings
  1213. @defvrx {Scheme Variable} symbol-bindings
  1214. @defvrx {Scheme Variable} unspecified-bindings
  1215. @defvrx {Scheme Variable} variable-bindings
  1216. @defvrx {Scheme Variable} vector-bindings
  1217. @defvrx {Scheme Variable} version-bindings
  1218. The components of @code{all-pure-bindings}.
  1219. @end defvr
  1220. @defvr {Scheme Variable} mutating-alist-bindings
  1221. @defvrx {Scheme Variable} mutating-array-bindings
  1222. @defvrx {Scheme Variable} mutating-bitvector-bindings
  1223. @defvrx {Scheme Variable} mutating-fluid-bindings
  1224. @defvrx {Scheme Variable} mutating-hash-bindings
  1225. @defvrx {Scheme Variable} mutating-list-bindings
  1226. @defvrx {Scheme Variable} mutating-pair-bindings
  1227. @defvrx {Scheme Variable} mutating-sort-bindings
  1228. @defvrx {Scheme Variable} mutating-srfi-4-bindings
  1229. @defvrx {Scheme Variable} mutating-string-bindings
  1230. @defvrx {Scheme Variable} mutating-variable-bindings
  1231. @defvrx {Scheme Variable} mutating-vector-bindings
  1232. The additional components of @code{all-pure-and-impure-bindings}.
  1233. @end defvr
  1234. Finally, what do you do with a binding set? What is a binding set
  1235. anyway? @code{make-sandbox-module} is here for you.
  1236. @deffn {Scheme Procedure} make-sandbox-module bindings
  1237. Return a fresh module that only contains @var{bindings}.
  1238. The @var{bindings} should be given as a list of import sets. One import
  1239. set is a list whose car names an interface, like @code{(ice-9 q)}, and
  1240. whose cdr is a list of imports. An import is either a bare symbol or a
  1241. pair of @code{(@var{out} . @var{in})}, where @var{out} and @var{in} are
  1242. both symbols and denote the name under which a binding is exported from
  1243. the module, and the name under which to make the binding available,
  1244. respectively.
  1245. @end deffn
  1246. So you see that binding sets are just lists, and
  1247. @code{all-pure-and-impure-bindings} is really just the result of
  1248. appending all of the component binding sets.
  1249. @node REPL Servers
  1250. @subsection REPL Servers
  1251. @cindex REPL server
  1252. The procedures in this section are provided by
  1253. @lisp
  1254. (use-modules (system repl server))
  1255. @end lisp
  1256. When an application is written in Guile, it is often convenient to
  1257. allow the user to be able to interact with it by evaluating Scheme
  1258. expressions in a REPL.
  1259. The procedures of this module allow you to spawn a @dfn{REPL server},
  1260. which permits interaction over a local or TCP connection. Guile itself
  1261. uses them internally to implement the @option{--listen} switch,
  1262. @ref{Command-line Options}.
  1263. @deffn {Scheme Procedure} make-tcp-server-socket [#:host=#f] @
  1264. [#:addr] [#:port=37146]
  1265. Return a stream socket bound to a given address @var{addr} and port
  1266. number @var{port}. If the @var{host} is given, and @var{addr} is not,
  1267. then the @var{host} string is converted to an address. If neither is
  1268. given, we use the loopback address.
  1269. @end deffn
  1270. @deffn {Scheme Procedure} make-unix-domain-server-socket [#:path="/tmp/guile-socket"]
  1271. Return a UNIX domain socket, bound to a given @var{path}.
  1272. @end deffn
  1273. @deffn {Scheme Procedure} run-server [server-socket]
  1274. @deffnx {Scheme Procedure} spawn-server [server-socket]
  1275. Create and run a REPL, making it available over the given
  1276. @var{server-socket}. If @var{server-socket} is not provided, it
  1277. defaults to the socket created by calling @code{make-tcp-server-socket}
  1278. with no arguments.
  1279. @code{run-server} runs the server in the current thread, whereas
  1280. @code{spawn-server} runs the server in a new thread.
  1281. @end deffn
  1282. @deffn {Scheme Procedure} stop-server-and-clients!
  1283. Closes the connection on all running server sockets.
  1284. Please note that in the current implementation, the REPL threads are
  1285. cancelled without unwinding their stacks. If any of them are holding
  1286. mutexes or are within a critical section, the results are unspecified.
  1287. @end deffn
  1288. @node Cooperative REPL Servers
  1289. @subsection Cooperative REPL Servers
  1290. @cindex Cooperative REPL server
  1291. The procedures in this section are provided by
  1292. @lisp
  1293. (use-modules (system repl coop-server))
  1294. @end lisp
  1295. Whereas ordinary REPL servers run in their own threads (@pxref{REPL
  1296. Servers}), sometimes it is more convenient to provide REPLs that run at
  1297. specified times within an existing thread, for example in programs
  1298. utilizing an event loop or in single-threaded programs. This allows for
  1299. safe access and mutation of a program's data structures from the REPL,
  1300. without concern for thread synchronization.
  1301. Although the REPLs are run in the thread that calls
  1302. @code{spawn-coop-repl-server} and @code{poll-coop-repl-server},
  1303. dedicated threads are spawned so that the calling thread is not blocked.
  1304. The spawned threads read input for the REPLs and to listen for new
  1305. connections.
  1306. Cooperative REPL servers must be polled periodically to evaluate any
  1307. pending expressions by calling @code{poll-coop-repl-server} with the
  1308. object returned from @code{spawn-coop-repl-server}. The thread that
  1309. calls @code{poll-coop-repl-server} will be blocked for as long as the
  1310. expression takes to be evaluated or if the debugger is entered.
  1311. @deffn {Scheme Procedure} spawn-coop-repl-server [server-socket]
  1312. Create and return a new cooperative REPL server object, and spawn a new
  1313. thread to listen for connections on @var{server-socket}. Proper
  1314. functioning of the REPL server requires that
  1315. @code{poll-coop-repl-server} be called periodically on the returned
  1316. server object.
  1317. @end deffn
  1318. @deffn {Scheme Procedure} poll-coop-repl-server coop-server
  1319. Poll the cooperative REPL server @var{coop-server} and apply a pending
  1320. operation if there is one, such as evaluating an expression typed at the
  1321. REPL prompt. This procedure must be called from the same thread that
  1322. called @code{spawn-coop-repl-server}.
  1323. @end deffn
  1324. @c Local Variables:
  1325. @c TeX-master: "guile.texi"
  1326. @c End: