c7bf97a3f58d2f7db312f671c13b792697020470
[bpt/guile.git] / doc / ref / api-evaluation.texi
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, 2010, 2011, 2012
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
6
7 @node Read/Load/Eval/Compile
8 @section Reading and Evaluating Scheme Code
9
10 This chapter describes Guile functions that are concerned with reading,
11 loading, evaluating, and compiling Scheme code at run time.
12
13 @menu
14 * Scheme Syntax:: Standard and extended Scheme syntax.
15 * Scheme Read:: Reading Scheme code.
16 * Scheme Write:: Writing Scheme values to a port.
17 * Fly Evaluation:: Procedures for on the fly evaluation.
18 * Compilation:: How to compile Scheme files and procedures.
19 * Loading:: Loading Scheme code from file.
20 * Load Paths:: Where Guile looks for code.
21 * Character Encoding of Source Files:: Loading non-ASCII Scheme code from file.
22 * Delayed Evaluation:: Postponing evaluation until it is needed.
23 * Local Evaluation:: Evaluation in a local lexical environment.
24 * Local Inclusion:: Compile-time inclusion of one file in another.
25 @end menu
26
27
28 @node Scheme Syntax
29 @subsection Scheme Syntax: Standard and Guile Extensions
30
31 @menu
32 * Expression Syntax::
33 * Comments::
34 * Block Comments::
35 * Case Sensitivity::
36 * Keyword Syntax::
37 * Reader Extensions::
38 @end menu
39
40
41 @node Expression Syntax
42 @subsubsection Expression Syntax
43
44 An expression to be evaluated takes one of the following forms.
45
46 @table @nicode
47
48 @item @var{symbol}
49 A symbol is evaluated by dereferencing. A binding of that symbol is
50 sought and the value there used. For example,
51
52 @example
53 (define x 123)
54 x @result{} 123
55 @end example
56
57 @item (@var{proc} @var{args}@dots{})
58 A parenthesised expression is a function call. @var{proc} and each
59 argument are evaluated, then the function (which @var{proc} evaluated
60 to) is called with those arguments.
61
62 The order in which @var{proc} and the arguments are evaluated is
63 unspecified, so be careful when using expressions with side effects.
64
65 @example
66 (max 1 2 3) @result{} 3
67
68 (define (get-some-proc) min)
69 ((get-some-proc) 1 2 3) @result{} 1
70 @end example
71
72 The same sort of parenthesised form is used for a macro invocation,
73 but in that case the arguments are not evaluated. See the
74 descriptions of macros for more on this (@pxref{Macros}, and
75 @pxref{Syntax Rules}).
76
77 @item @var{constant}
78 Number, string, character and boolean constants evaluate ``to
79 themselves'', so can appear as literals.
80
81 @example
82 123 @result{} 123
83 99.9 @result{} 99.9
84 "hello" @result{} "hello"
85 #\z @result{} #\z
86 #t @result{} #t
87 @end example
88
89 Note that an application must not attempt to modify literal strings,
90 since they may be in read-only memory.
91
92 @item (quote @var{data})
93 @itemx '@var{data}
94 @findex quote
95 @findex '
96 Quoting is used to obtain a literal symbol (instead of a variable
97 reference), a literal list (instead of a function call), or a literal
98 vector. @nicode{'} is simply a shorthand for a @code{quote} form.
99 For example,
100
101 @example
102 'x @result{} x
103 '(1 2 3) @result{} (1 2 3)
104 '#(1 (2 3) 4) @result{} #(1 (2 3) 4)
105 (quote x) @result{} x
106 (quote (1 2 3)) @result{} (1 2 3)
107 (quote #(1 (2 3) 4)) @result{} #(1 (2 3) 4)
108 @end example
109
110 Note that an application must not attempt to modify literal lists or
111 vectors obtained from a @code{quote} form, since they may be in
112 read-only memory.
113
114 @item (quasiquote @var{data})
115 @itemx `@var{data}
116 @findex quasiquote
117 @findex `
118 Backquote quasi-quotation is like @code{quote}, but selected
119 sub-expressions are evaluated. This is a convenient way to construct
120 a list or vector structure most of which is constant, but at certain
121 points should have expressions substituted.
122
123 The same effect can always be had with suitable @code{list},
124 @code{cons} or @code{vector} calls, but quasi-quoting is often easier.
125
126 @table @nicode
127
128 @item (unquote @var{expr})
129 @itemx ,@var{expr}
130 @findex unquote
131 @findex ,
132 Within the quasiquote @var{data}, @code{unquote} or @code{,} indicates
133 an expression to be evaluated and inserted. The comma syntax @code{,}
134 is simply a shorthand for an @code{unquote} form. For example,
135
136 @example
137 `(1 2 ,(* 9 9) 3 4) @result{} (1 2 81 3 4)
138 `(1 (unquote (+ 1 1)) 3) @result{} (1 2 3)
139 `#(1 ,(/ 12 2)) @result{} #(1 6)
140 @end example
141
142 @item (unquote-splicing @var{expr})
143 @itemx ,@@@var{expr}
144 @findex unquote-splicing
145 @findex ,@@
146 Within the quasiquote @var{data}, @code{unquote-splicing} or
147 @code{,@@} indicates an expression to be evaluated and the elements of
148 the returned list inserted. @var{expr} must evaluate to a list. The
149 ``comma-at'' syntax @code{,@@} is simply a shorthand for an
150 @code{unquote-splicing} form.
151
152 @example
153 (define x '(2 3))
154 `(1 ,@@x 4) @result{} (1 2 3 4)
155 `(1 (unquote-splicing (map 1+ x))) @result{} (1 3 4)
156 `#(9 ,@@x 9) @result{} #(9 2 3 9)
157 @end example
158
159 Notice @code{,@@} differs from plain @code{,} in the way one level of
160 nesting is stripped. For @code{,@@} the elements of a returned list
161 are inserted, whereas with @code{,} it would be the list itself
162 inserted.
163 @end table
164
165 @c
166 @c FIXME: What can we say about the mutability of a quasiquote
167 @c result? R5RS doesn't seem to specify anything, though where it
168 @c says backquote without commas is the same as plain quote then
169 @c presumably the "fixed" portions of a quasiquote expression must be
170 @c treated as immutable.
171 @c
172
173 @end table
174
175
176 @node Comments
177 @subsubsection Comments
178
179 @c FIXME::martin: Review me!
180
181 Comments in Scheme source files are written by starting them with a
182 semicolon character (@code{;}). The comment then reaches up to the end
183 of the line. Comments can begin at any column, and the may be inserted
184 on the same line as Scheme code.
185
186 @lisp
187 ; Comment
188 ;; Comment too
189 (define x 1) ; Comment after expression
190 (let ((y 1))
191 ;; Display something.
192 (display y)
193 ;;; Comment at left margin.
194 (display (+ y 1)))
195 @end lisp
196
197 It is common to use a single semicolon for comments following
198 expressions on a line, to use two semicolons for comments which are
199 indented like code, and three semicolons for comments which start at
200 column 0, even if they are inside an indented code block. This
201 convention is used when indenting code in Emacs' Scheme mode.
202
203
204 @node Block Comments
205 @subsubsection Block Comments
206 @cindex multiline comments
207 @cindex block comments
208 @cindex #!
209 @cindex !#
210
211 @c FIXME::martin: Review me!
212
213 In addition to the standard line comments defined by R5RS, Guile has
214 another comment type for multiline comments, called @dfn{block
215 comments}. This type of comment begins with the character sequence
216 @code{#!} and ends with the characters @code{!#}, which must appear on a
217 line of their own. These comments are compatible with the block
218 comments in the Scheme Shell @file{scsh} (@pxref{The Scheme shell
219 (scsh)}). The characters @code{#!} were chosen because they are the
220 magic characters used in shell scripts for indicating that the name of
221 the program for executing the script follows on the same line.
222
223 Thus a Guile script often starts like this.
224
225 @lisp
226 #! /usr/local/bin/guile -s
227 !#
228 @end lisp
229
230 More details on Guile scripting can be found in the scripting section
231 (@pxref{Guile Scripting}).
232
233 @cindex R6RS block comments
234 @cindex SRFI-30 block comments
235 Similarly, Guile (starting from version 2.0) supports nested block
236 comments as specified by R6RS and
237 @url{http://srfi.schemers.org/srfi-30/srfi-30.html, SRFI-30}:
238
239 @lisp
240 (+ #| this is a #| nested |# block comment |# 2)
241 @result{} 3
242 @end lisp
243
244 For backward compatibility, this syntax can be overridden with
245 @code{read-hash-extend} (@pxref{Reader Extensions,
246 @code{read-hash-extend}}).
247
248 There is one special case where the contents of a comment can actually
249 affect the interpretation of code. When a character encoding
250 declaration, such as @code{coding: utf-8} appears in one of the first
251 few lines of a source file, it indicates to Guile's default reader
252 that this source code file is not ASCII. For details see @ref{Character
253 Encoding of Source Files}.
254
255 @node Case Sensitivity
256 @subsubsection Case Sensitivity
257 @cindex fold-case
258 @cindex no-fold-case
259
260 @c FIXME::martin: Review me!
261
262 Scheme as defined in R5RS is not case sensitive when reading symbols.
263 Guile, on the contrary is case sensitive by default, so the identifiers
264
265 @lisp
266 guile-whuzzy
267 Guile-Whuzzy
268 @end lisp
269
270 are the same in R5RS Scheme, but are different in Guile.
271
272 It is possible to turn off case sensitivity in Guile by setting the
273 reader option @code{case-insensitive}. For more information on reader
274 options, @xref{Scheme Read}.
275
276 @lisp
277 (read-enable 'case-insensitive)
278 @end lisp
279
280 It is also possible to disable (or enable) case sensitivity within a
281 single file by placing the reader directives @code{#!fold-case} (or
282 @code{#!no-fold-case}) within the file itself.
283
284 @node Keyword Syntax
285 @subsubsection Keyword Syntax
286
287
288 @node Reader Extensions
289 @subsubsection Reader Extensions
290
291 @deffn {Scheme Procedure} read-hash-extend chr proc
292 @deffnx {C Function} scm_read_hash_extend (chr, proc)
293 Install the procedure @var{proc} for reading expressions
294 starting with the character sequence @code{#} and @var{chr}.
295 @var{proc} will be called with two arguments: the character
296 @var{chr} and the port to read further data from. The object
297 returned will be the return value of @code{read}.
298 Passing @code{#f} for @var{proc} will remove a previous setting.
299
300 @end deffn
301
302
303 @node Scheme Read
304 @subsection Reading Scheme Code
305
306 @rnindex read
307 @deffn {Scheme Procedure} read [port]
308 @deffnx {C Function} scm_read (port)
309 Read an s-expression from the input port @var{port}, or from
310 the current input port if @var{port} is not specified.
311 Any whitespace before the next token is discarded.
312 @end deffn
313
314 The behaviour of Guile's Scheme reader can be modified by manipulating
315 its read options.
316
317 @cindex options - read
318 @cindex read options
319 @deffn {Scheme Procedure} read-options [setting]
320 Display the current settings of the global read options. If
321 @var{setting} is omitted, only a short form of the current read options
322 is printed. Otherwise if @var{setting} is the symbol @code{help}, a
323 complete options description is displayed.
324 @end deffn
325
326 The set of available options, and their default values, may be had by
327 invoking @code{read-options} at the prompt.
328
329 @smalllisp
330 scheme@@(guile-user)> (read-options)
331 (square-brackets keywords #f positions)
332 scheme@@(guile-user)> (read-options 'help)
333 copy no Copy source code expressions.
334 positions yes Record positions of source code expressions.
335 case-insensitive no Convert symbols to lower case.
336 keywords #f Style of keyword recognition: #f, 'prefix or 'postfix.
337 r6rs-hex-escapes no Use R6RS variable-length character and string hex escapes.
338 square-brackets yes Treat `[' and `]' as parentheses, for R6RS compatibility.
339 hungry-eol-escapes no In strings, consume leading whitespace after an
340 escaped end-of-line.
341 @end smalllisp
342
343 Note that Guile also includes a preliminary mechanism for setting read
344 options on a per-port basis. For instance, the @code{case-insensitive}
345 read option is set (or unset) on the port when the reader encounters the
346 @code{#!fold-case} or @code{#!no-fold-case} reader directives. There is
347 currently no other way to access or set the per-port read options.
348
349 The boolean options may be toggled with @code{read-enable} and
350 @code{read-disable}. The non-boolean @code{keywords} option must be set
351 using @code{read-set!}.
352
353 @deffn {Scheme Procedure} read-enable option-name
354 @deffnx {Scheme Procedure} read-disable option-name
355 @deffnx {Scheme Syntax} read-set! option-name value
356 Modify the read options. @code{read-enable} should be used with boolean
357 options and switches them on, @code{read-disable} switches them off.
358
359 @code{read-set!} can be used to set an option to a specific value. Due
360 to historical oddities, it is a macro that expects an unquoted option
361 name.
362 @end deffn
363
364 For example, to make @code{read} fold all symbols to their lower case
365 (perhaps for compatibility with older Scheme code), you can enter:
366
367 @lisp
368 (read-enable 'case-insensitive)
369 @end lisp
370
371 For more information on the effect of the @code{r6rs-hex-escapes} and
372 @code{hungry-eol-escapes} options, see (@pxref{String Syntax}).
373
374
375 @node Scheme Write
376 @subsection Writing Scheme Values
377
378 Any scheme value may be written to a port. Not all values may be read
379 back in (@pxref{Scheme Read}), however.
380
381 @rnindex write
382 @rnindex print
383 @deffn {Scheme Procedure} write obj [port]
384 Send a representation of @var{obj} to @var{port} or to the current
385 output port if not given.
386
387 The output is designed to be machine readable, and can be read back
388 with @code{read} (@pxref{Scheme Read}). Strings are printed in
389 double quotes, with escapes if necessary, and characters are printed in
390 @samp{#\} notation.
391 @end deffn
392
393 @rnindex display
394 @deffn {Scheme Procedure} display obj [port]
395 Send a representation of @var{obj} to @var{port} or to the current
396 output port if not given.
397
398 The output is designed for human readability, it differs from
399 @code{write} in that strings are printed without double quotes and
400 escapes, and characters are printed as per @code{write-char}, not in
401 @samp{#\} form.
402 @end deffn
403
404 As was the case with the Scheme reader, there are a few options that
405 affect the behavior of the Scheme printer.
406
407 @cindex options - print
408 @cindex print options
409 @deffn {Scheme Procedure} print-options [setting]
410 Display the current settings of the read options. If @var{setting} is
411 omitted, only a short form of the current read options is
412 printed. Otherwise if @var{setting} is the symbol @code{help}, a
413 complete options description is displayed.
414 @end deffn
415
416 The set of available options, and their default values, may be had by
417 invoking @code{print-options} at the prompt.
418
419 @smalllisp
420 scheme@@(guile-user)> (print-options)
421 (quote-keywordish-symbols reader highlight-suffix "@}" highlight-prefix "@{")
422 scheme@@(guile-user)> (print-options 'help)
423 highlight-prefix @{ The string to print before highlighted values.
424 highlight-suffix @} The string to print after highlighted values.
425 quote-keywordish-symbols reader How to print symbols that have a colon
426 as their first or last character. The
427 value '#f' does not quote the colons;
428 '#t' quotes them; 'reader' quotes them
429 when the reader option 'keywords' is
430 not '#f'.
431 escape-newlines yes Render newlines as \n when printing
432 using `write'.
433 @end smalllisp
434
435 These options may be modified with the print-set! syntax.
436
437 @deffn {Scheme Syntax} print-set! option-name value
438 Modify the print options. Due to historical oddities, @code{print-set!}
439 is a macro that expects an unquoted option name.
440 @end deffn
441
442
443 @node Fly Evaluation
444 @subsection Procedures for On the Fly Evaluation
445
446 Scheme has the lovely property that its expressions may be represented
447 as data. The @code{eval} procedure takes a Scheme datum and evaluates
448 it as code.
449
450 @rnindex eval
451 @c ARGFIXME environment/environment specifier
452 @deffn {Scheme Procedure} eval exp module_or_state
453 @deffnx {C Function} scm_eval (exp, module_or_state)
454 Evaluate @var{exp}, a list representing a Scheme expression,
455 in the top-level environment specified by @var{module_or_state}.
456 While @var{exp} is evaluated (using @code{primitive-eval}),
457 @var{module_or_state} is made the current module. The current module
458 is reset to its previous value when @code{eval} returns.
459 XXX - dynamic states.
460 Example: (eval '(+ 1 2) (interaction-environment))
461 @end deffn
462
463 @rnindex interaction-environment
464 @deffn {Scheme Procedure} interaction-environment
465 @deffnx {C Function} scm_interaction_environment ()
466 Return a specifier for the environment that contains
467 implementation--defined bindings, typically a superset of those
468 listed in the report. The intent is that this procedure will
469 return the environment in which the implementation would
470 evaluate expressions dynamically typed by the user.
471 @end deffn
472
473 @xref{Environments}, for other environments.
474
475 One does not always receive code as Scheme data, of course, and this is
476 especially the case for Guile's other language implementations
477 (@pxref{Other Languages}). For the case in which all you have is a
478 string, we have @code{eval-string}. There is a legacy version of this
479 procedure in the default environment, but you really want the one from
480 @code{(ice-9 eval-string)}, so load it up:
481
482 @example
483 (use-modules (ice-9 eval-string))
484 @end example
485
486 @deffn {Scheme Procedure} eval-string string [module=#f] [file=#f] [line=#f] [column=#f] [lang=(current-language)] [compile?=#f]
487 Parse @var{string} according to the current language, normally Scheme.
488 Evaluate or compile the expressions it contains, in order, returning the
489 last expression.
490
491 If the @var{module} keyword argument is set, save a module excursion
492 (@pxref{Module System Reflection}) and set the current module to
493 @var{module} before evaluation.
494
495 The @var{file}, @var{line}, and @var{column} keyword arguments can be
496 used to indicate that the source string begins at a particular source
497 location.
498
499 Finally, @var{lang} is a language, defaulting to the current language,
500 and the expression is compiled if @var{compile?} is true or there is no
501 evaluator for the given language.
502 @end deffn
503
504 @deffn {C Function} scm_eval_string (string)
505 @deffnx {C Function} scm_eval_string_in_module (string, module)
506 These C bindings call @code{eval-string} from @code{(ice-9
507 eval-string)}, evaluating within @var{module} or the current module.
508 @end deffn
509
510 @deftypefn {C Function} SCM scm_c_eval_string (const char *string)
511 @code{scm_eval_string}, but taking a C string in locale encoding instead
512 of an @code{SCM}.
513 @end deftypefn
514
515 @deffn {Scheme Procedure} apply proc arg @dots{} arglst
516 @deffnx {C Function} scm_apply_0 (proc, arglst)
517 @deffnx {C Function} scm_apply_1 (proc, arg1, arglst)
518 @deffnx {C Function} scm_apply_2 (proc, arg1, arg2, arglst)
519 @deffnx {C Function} scm_apply_3 (proc, arg1, arg2, arg3, arglst)
520 @deffnx {C Function} scm_apply (proc, arg, rest)
521 @rnindex apply
522 Call @var{proc} with arguments @var{arg} @dots{} and the
523 elements of the @var{arglst} list.
524
525 @code{scm_apply} takes parameters corresponding to a Scheme level
526 @code{(lambda (proc arg1 . rest) ...)}. So @var{arg1} and all but the
527 last element of the @var{rest} list make up @var{arg} @dots{}, and the
528 last element of @var{rest} is the @var{arglst} list. Or if @var{rest}
529 is the empty list @code{SCM_EOL} then there's no @var{arg} @dots{}, and
530 (@var{arg1}) is the @var{arglst}.
531
532 @var{arglst} is not modified, but the @var{rest} list passed to
533 @code{scm_apply} is modified.
534 @end deffn
535
536 @deffn {C Function} scm_call_0 (proc)
537 @deffnx {C Function} scm_call_1 (proc, arg1)
538 @deffnx {C Function} scm_call_2 (proc, arg1, arg2)
539 @deffnx {C Function} scm_call_3 (proc, arg1, arg2, arg3)
540 @deffnx {C Function} scm_call_4 (proc, arg1, arg2, arg3, arg4)
541 @deffnx {C Function} scm_call_5 (proc, arg1, arg2, arg3, arg4, arg5)
542 @deffnx {C Function} scm_call_6 (proc, arg1, arg2, arg3, arg4, arg5, arg6)
543 @deffnx {C Function} scm_call_7 (proc, arg1, arg2, arg3, arg4, arg5, arg6, arg7)
544 @deffnx {C Function} scm_call_8 (proc, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)
545 @deffnx {C Function} scm_call_9 (proc, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9)
546 Call @var{proc} with the given arguments.
547 @end deffn
548
549 @deffn {C Function} scm_call (proc, ...)
550 Call @var{proc} with any number of arguments. The argument list must be
551 terminated by @code{SCM_UNDEFINED}. For example:
552
553 @example
554 scm_call (scm_c_public_ref ("guile", "+"),
555 scm_from_int (1),
556 scm_from_int (2),
557 SCM_UNDEFINED);
558 @end example
559 @end deffn
560
561 @deffn {C Function} scm_call_n (proc, argv, nargs)
562 Call @var{proc} with the array of arguments @var{argv}, as a
563 @code{SCM*}. The length of the arguments should be passed in
564 @var{nargs}, as a @code{size_t}.
565 @end deffn
566
567 @deffn {Scheme Procedure} apply:nconc2last lst
568 @deffnx {C Function} scm_nconc2last (lst)
569 @var{lst} should be a list (@var{arg1} @dots{} @var{argN}
570 @var{arglst}), with @var{arglst} being a list. This function returns
571 a list comprising @var{arg1} to @var{argN} plus the elements of
572 @var{arglst}. @var{lst} is modified to form the return. @var{arglst}
573 is not modified, though the return does share structure with it.
574
575 This operation collects up the arguments from a list which is
576 @code{apply} style parameters.
577 @end deffn
578
579 @deffn {Scheme Procedure} primitive-eval exp
580 @deffnx {C Function} scm_primitive_eval (exp)
581 Evaluate @var{exp} in the top-level environment specified by
582 the current module.
583 @end deffn
584
585
586 @node Compilation
587 @subsection Compiling Scheme Code
588
589 The @code{eval} procedure directly interprets the S-expression
590 representation of Scheme. An alternate strategy for evaluation is to
591 determine ahead of time what computations will be necessary to
592 evaluate the expression, and then use that recipe to produce the
593 desired results. This is known as @dfn{compilation}.
594
595 While it is possible to compile simple Scheme expressions such as
596 @code{(+ 2 2)} or even @code{"Hello world!"}, compilation is most
597 interesting in the context of procedures. Compiling a lambda expression
598 produces a compiled procedure, which is just like a normal procedure
599 except typically much faster, because it can bypass the generic
600 interpreter.
601
602 Functions from system modules in a Guile installation are normally
603 compiled already, so they load and run quickly.
604
605 @cindex automatic compilation
606 Note that well-written Scheme programs will not typically call the
607 procedures in this section, for the same reason that it is often bad
608 taste to use @code{eval}. By default, Guile automatically compiles any
609 files it encounters that have not been compiled yet (@pxref{Invoking
610 Guile, @code{--auto-compile}}). The compiler can also be invoked
611 explicitly from the shell as @code{guild compile foo.scm}.
612
613 (Why are calls to @code{eval} and @code{compile} usually in bad taste?
614 Because they are limited, in that they can only really make sense for
615 top-level expressions. Also, most needs for ``compile-time''
616 computation are fulfilled by macros and closures. Of course one good
617 counterexample is the REPL itself, or any code that reads expressions
618 from a port.)
619
620 Automatic compilation generally works transparently, without any need
621 for user intervention. However Guile does not yet do proper dependency
622 tracking, so that if file @file{@var{a}.scm} uses macros from
623 @file{@var{b}.scm}, and @var{@var{b}.scm} changes, @code{@var{a}.scm}
624 would not be automatically recompiled. To forcibly invalidate the
625 auto-compilation cache, pass the @code{--fresh-auto-compile} option to
626 Guile, or set the @code{GUILE_AUTO_COMPILE} environment variable to
627 @code{fresh} (instead of to @code{0} or @code{1}).
628
629 For more information on the compiler itself, see @ref{Compiling to the
630 Virtual Machine}. For information on the virtual machine, see @ref{A
631 Virtual Machine for Guile}.
632
633 The command-line interface to Guile's compiler is the @command{guild
634 compile} command:
635
636 @deffn {Command} {guild compile} [@option{option}...] @var{file}...
637 Compile @var{file}, a source file, and store bytecode in the compilation cache
638 or in the file specified by the @option{-o} option. The following options are
639 available:
640
641 @table @option
642
643 @item -L @var{dir}
644 @itemx --load-path=@var{dir}
645 Add @var{dir} to the front of the module load path.
646
647 @item -o @var{ofile}
648 @itemx --output=@var{ofile}
649 Write output bytecode to @var{ofile}. By convention, bytecode file
650 names end in @code{.go}. When @option{-o} is omitted, the output file
651 name is as for @code{compile-file} (see below).
652
653 @item -W @var{warning}
654 @itemx --warn=@var{warning}
655 @cindex warnings, compiler
656 Emit warnings of type @var{warning}; use @code{--warn=help} for a list
657 of available warnings and their description. Currently recognized
658 warnings include @code{unused-variable}, @code{unused-toplevel},
659 @code{unbound-variable}, @code{arity-mismatch}, and @code{format}.
660
661 @item -f @var{lang}
662 @itemx --from=@var{lang}
663 Use @var{lang} as the source language of @var{file}. If this option is omitted,
664 @code{scheme} is assumed.
665
666 @item -t @var{lang}
667 @itemx --to=@var{lang}
668 Use @var{lang} as the target language of @var{file}. If this option is omitted,
669 @code{objcode} is assumed.
670
671 @item -T @var{target}
672 @itemx --target=@var{target}
673 Produce bytecode for @var{target} instead of @var{%host-type}
674 (@pxref{Build Config, %host-type}). Target must be a valid GNU triplet,
675 such as @code{armv5tel-unknown-linux-gnueabi} (@pxref{Specifying Target
676 Triplets,,, autoconf, GNU Autoconf Manual}).
677
678 @end table
679
680 Each @var{file} is assumed to be UTF-8-encoded, unless it contains a
681 coding declaration as recognized by @code{file-encoding}
682 (@pxref{Character Encoding of Source Files}).
683 @end deffn
684
685 The compiler can also be invoked directly by Scheme code using the procedures
686 below:
687
688 @deffn {Scheme Procedure} compile exp [env=#f] [from=(current-language)] [to=value] [opts=()]
689 Compile the expression @var{exp} in the environment @var{env}. If
690 @var{exp} is a procedure, the result will be a compiled procedure;
691 otherwise @code{compile} is mostly equivalent to @code{eval}.
692
693 For a discussion of languages and compiler options, @xref{Compiling to
694 the Virtual Machine}.
695 @end deffn
696
697 @deffn {Scheme Procedure} compile-file file [output-file=#f] @
698 [from=(current-language)] [to='objcode] @
699 [env=(default-environment from)] [opts='()] @
700 [canonicalization 'relative]
701 Compile the file named @var{file}.
702
703 Output will be written to a @var{output-file}. If you do not supply an
704 output file name, output is written to a file in the cache directory, as
705 computed by @code{(compiled-file-name @var{file})}.
706
707 @var{from} and @var{to} specify the source and target languages.
708 @xref{Compiling to the Virtual Machine}, for more information on these
709 options, and on @var{env} and @var{opts}.
710
711 As with @command{guild compile}, @var{file} is assumed to be
712 UTF-8-encoded unless it contains a coding declaration.
713 @end deffn
714
715 @deffn {Scheme Procedure} compiled-file-name file
716 Compute a cached location for a compiled version of a Scheme file named
717 @var{file}.
718
719 This file will usually be below the @file{$HOME/.cache/guile/ccache}
720 directory, depending on the value of the @env{XDG_CACHE_HOME}
721 environment variable. The intention is that @code{compiled-file-name}
722 provides a fallback location for caching auto-compiled files. If you
723 want to place a compile file in the @code{%load-compiled-path}, you
724 should pass the @var{output-file} option to @code{compile-file},
725 explicitly.
726 @end deffn
727
728 @defvr {Scheme Variable} %auto-compilation-options
729 This variable contains the options passed to the @code{compile-file}
730 procedure when auto-compiling source files. By default, it enables
731 useful compilation warnings. It can be customized from @file{~/.guile}.
732 @end defvr
733
734 @node Loading
735 @subsection Loading Scheme Code from File
736
737 @rnindex load
738 @deffn {Scheme Procedure} load filename [reader]
739 Load @var{filename} and evaluate its contents in the top-level
740 environment.
741
742 @var{reader} if provided should be either @code{#f}, or a procedure with
743 the signature @code{(lambda (port) @dots{})} which reads the next
744 expression from @var{port}. If @var{reader} is @code{#f} or absent,
745 Guile's built-in @code{read} procedure is used (@pxref{Scheme Read}).
746
747 The @var{reader} argument takes effect by setting the value of the
748 @code{current-reader} fluid (see below) before loading the file, and
749 restoring its previous value when loading is complete. The Scheme code
750 inside @var{filename} can itself change the current reader procedure on
751 the fly by setting @code{current-reader} fluid.
752
753 If the variable @code{%load-hook} is defined, it should be bound to a
754 procedure that will be called before any code is loaded. See
755 documentation for @code{%load-hook} later in this section.
756 @end deffn
757
758 @deffn {Scheme Procedure} load-compiled filename
759 Load the compiled file named @var{filename}.
760
761 Compiling a source file (@pxref{Read/Load/Eval/Compile}) and then
762 calling @code{load-compiled} on the resulting file is equivalent to
763 calling @code{load} on the source file.
764 @end deffn
765
766 @deffn {Scheme Procedure} primitive-load filename
767 @deffnx {C Function} scm_primitive_load (filename)
768 Load the file named @var{filename} and evaluate its contents in the
769 top-level environment. @var{filename} must either be a full pathname or
770 be a pathname relative to the current directory. If the variable
771 @code{%load-hook} is defined, it should be bound to a procedure that
772 will be called before any code is loaded. See the documentation for
773 @code{%load-hook} later in this section.
774 @end deffn
775
776 @deftypefn {C Function} SCM scm_c_primitive_load (const char *filename)
777 @code{scm_primitive_load}, but taking a C string instead of an
778 @code{SCM}.
779 @end deftypefn
780
781 @defvar current-reader
782 @code{current-reader} holds the read procedure that is currently being
783 used by the above loading procedures to read expressions (from the file
784 that they are loading). @code{current-reader} is a fluid, so it has an
785 independent value in each dynamic root and should be read and set using
786 @code{fluid-ref} and @code{fluid-set!} (@pxref{Fluids and Dynamic
787 States}).
788
789 Changing @code{current-reader} is typically useful to introduce local
790 syntactic changes, such that code following the @code{fluid-set!} call
791 is read using the newly installed reader. The @code{current-reader}
792 change should take place at evaluation time when the code is evaluated,
793 or at compilation time when the code is compiled:
794
795 @findex eval-when
796 @example
797 (eval-when (compile eval)
798 (fluid-set! current-reader my-own-reader))
799 @end example
800
801 The @code{eval-when} form above ensures that the @code{current-reader}
802 change occurs at the right time.
803 @end defvar
804
805 @defvar %load-hook
806 A procedure to be called @code{(%load-hook @var{filename})} whenever a
807 file is loaded, or @code{#f} for no such call. @code{%load-hook} is
808 used by all of the loading functions (@code{load} and
809 @code{primitive-load}, and @code{load-from-path} and
810 @code{primitive-load-path} documented in the next section).
811
812 For example an application can set this to show what's loaded,
813
814 @example
815 (set! %load-hook (lambda (filename)
816 (format #t "Loading ~a ...\n" filename)))
817 (load-from-path "foo.scm")
818 @print{} Loading /usr/local/share/guile/site/foo.scm ...
819 @end example
820 @end defvar
821
822 @deffn {Scheme Procedure} current-load-port
823 @deffnx {C Function} scm_current_load_port ()
824 Return the current-load-port.
825 The load port is used internally by @code{primitive-load}.
826 @end deffn
827
828 @node Load Paths
829 @subsection Load Paths
830
831 The procedure in the previous section look for Scheme code in the file
832 system at specific location. Guile also has some procedures to search
833 the load path for code.
834
835 @cindex @env{GUILE_LOAD_PATH}
836 @defvar %load-path
837 List of directories which should be searched for Scheme modules and
838 libraries. @code{%load-path} is initialized when Guile starts up to
839 @code{(list (%site-dir) (%library-dir) (%package-data-dir))}, prepended
840 with the contents of the @env{GUILE_LOAD_PATH} environment variable, if
841 it is set. @xref{Build Config}, for more on @code{%site-dir} and
842 related procedures.
843 @end defvar
844
845 @deffn {Scheme Procedure} load-from-path filename
846 Similar to @code{load}, but searches for @var{filename} in the load
847 paths. Preferentially loads a compiled version of the file, if it is
848 available and up-to-date.
849 @end deffn
850
851 A user can extend the load path by calling @code{add-to-load-path}.
852
853 @deffn {Scheme Syntax} add-to-load-path dir
854 Add @var{dir} to the load path.
855 @end deffn
856
857 For example, a script might include this form to add the directory that
858 it is in to the load path:
859
860 @example
861 (add-to-load-path (dirname (current-filename)))
862 @end example
863
864 It's better to use @code{add-to-load-path} than to modify
865 @code{%load-path} directly, because @code{add-to-load-path} takes care
866 of modifying the path both at compile-time and at run-time.
867
868 @deffn {Scheme Procedure} primitive-load-path filename [exception-on-not-found]
869 @deffnx {C Function} scm_primitive_load_path (filename)
870 Search @code{%load-path} for the file named @var{filename} and
871 load it into the top-level environment. If @var{filename} is a
872 relative pathname and is not found in the list of search paths,
873 an error is signalled. Preferentially loads a compiled version of the
874 file, if it is available and up-to-date.
875
876 By default or if @var{exception-on-not-found} is true, an exception is
877 raised if @var{filename} is not found. If @var{exception-on-not-found}
878 is @code{#f} and @var{filename} is not found, no exception is raised and
879 @code{#f} is returned. For compatibility with Guile 1.8 and earlier,
880 the C function takes only one argument, which can be either a string
881 (the file name) or an argument list.
882 @end deffn
883
884 @deffn {Scheme Procedure} %search-load-path filename
885 @deffnx {C Function} scm_sys_search_load_path (filename)
886 Search @code{%load-path} for the file named @var{filename}, which must
887 be readable by the current user. If @var{filename} is found in the list
888 of paths to search or is an absolute pathname, return its full pathname.
889 Otherwise, return @code{#f}. Filenames may have any of the optional
890 extensions in the @code{%load-extensions} list; @code{%search-load-path}
891 will try each extension automatically.
892 @end deffn
893
894 @defvar %load-extensions
895 A list of default file extensions for files containing Scheme code.
896 @code{%search-load-path} tries each of these extensions when looking for
897 a file to load. By default, @code{%load-extensions} is bound to the
898 list @code{("" ".scm")}.
899 @end defvar
900
901 As mentioned above, when Guile searches the @code{%load-path} for a
902 source file, it will also search the @code{%load-compiled-path} for a
903 corresponding compiled file. If the compiled file is as new or newer
904 than the source file, it will be loaded instead of the source file,
905 using @code{load-compiled}.
906
907 @defvar %load-compiled-path
908 Like @code{%load-path}, but for compiled files. By default, this path
909 has two entries: one for compiled files from Guile itself, and one for
910 site packages.
911 @end defvar
912
913 When @code{primitive-load-path} searches the @code{%load-compiled-path}
914 for a corresponding compiled file for a relative path it does so by
915 appending @code{.go} to the relative path. For example, searching for
916 @code{ice-9/popen} could find
917 @code{/usr/lib/guile/2.0/ccache/ice-9/popen.go}, and use it instead of
918 @code{/usr/share/guile/2.0/ice-9/popen.scm}.
919
920 If @code{primitive-load-path} does not find a corresponding @code{.go}
921 file in the @code{%load-compiled-path}, or the @code{.go} file is out of
922 date, it will search for a corresponding auto-compiled file in the
923 fallback path, possibly creating one if one does not exist.
924
925 @xref{Installing Site Packages}, for more on how to correctly install
926 site packages. @xref{Modules and the File System}, for more on the
927 relationship between load paths and modules. @xref{Compilation}, for
928 more on the fallback path and auto-compilation.
929
930 Finally, there are a couple of helper procedures for general path
931 manipulation.
932
933 @deffn {Scheme Procedure} parse-path path [tail]
934 @deffnx {C Function} scm_parse_path (path, tail)
935 Parse @var{path}, which is expected to be a colon-separated string, into
936 a list and return the resulting list with @var{tail} appended. If
937 @var{path} is @code{#f}, @var{tail} is returned.
938 @end deffn
939
940 @deffn {Scheme Procedure} search-path path filename [extensions [require-exts?]]
941 @deffnx {C Function} scm_search_path (path, filename, rest)
942 Search @var{path} for a directory containing a file named
943 @var{filename}. The file must be readable, and not a directory. If we
944 find one, return its full filename; otherwise, return @code{#f}. If
945 @var{filename} is absolute, return it unchanged. If given,
946 @var{extensions} is a list of strings; for each directory in @var{path},
947 we search for @var{filename} concatenated with each @var{extension}. If
948 @var{require-exts?} is true, require that the returned file name have
949 one of the given extensions; if @var{require-exts?} is not given, it
950 defaults to @code{#f}.
951
952 For compatibility with Guile 1.8 and earlier, the C function takes only
953 three arguments.
954 @end deffn
955
956
957 @node Character Encoding of Source Files
958 @subsection Character Encoding of Source Files
959
960 @cindex source file encoding
961 @cindex primitive-load
962 @cindex load
963 Scheme source code files are usually encoded in ASCII, but, the
964 built-in reader can interpret other character encodings. The
965 procedure @code{primitive-load}, and by extension the functions that
966 call it, such as @code{load}, first scan the top 500 characters of the
967 file for a coding declaration.
968
969 A coding declaration has the form @code{coding: XXXXXX}, where
970 @code{XXXXXX} is the name of a character encoding in which the source
971 code file has been encoded. The coding declaration must appear in a
972 scheme comment. It can either be a semicolon-initiated comment or a block
973 @code{#!} comment.
974
975 The name of the character encoding in the coding declaration is
976 typically lower case and containing only letters, numbers, and hyphens,
977 as recognized by @code{set-port-encoding!} (@pxref{Ports,
978 @code{set-port-encoding!}}). Common examples of character encoding
979 names are @code{utf-8} and @code{iso-8859-1},
980 @url{http://www.iana.org/assignments/character-sets, as defined by
981 IANA}. Thus, the coding declaration is mostly compatible with Emacs.
982
983 However, there are some differences in encoding names recognized by
984 Emacs and encoding names defined by IANA, the latter being essentially a
985 subset of the former. For instance, @code{latin-1} is a valid encoding
986 name for Emacs, but it's not according to the IANA standard, which Guile
987 follows; instead, you should use @code{iso-8859-1}, which is both
988 understood by Emacs and dubbed by IANA (IANA writes it uppercase but
989 Emacs wants it lowercase and Guile is case insensitive.)
990
991 For source code, only a subset of all possible character encodings can
992 be interpreted by the built-in source code reader. Only those
993 character encodings in which ASCII text appears unmodified can be
994 used. This includes @code{UTF-8} and @code{ISO-8859-1} through
995 @code{ISO-8859-15}. The multi-byte character encodings @code{UTF-16}
996 and @code{UTF-32} may not be used because they are not compatible with
997 ASCII.
998
999 @cindex read
1000 @cindex encoding
1001 @cindex port encoding
1002 @findex set-port-encoding!
1003 There might be a scenario in which one would want to read non-ASCII
1004 code from a port, such as with the function @code{read}, instead of
1005 with @code{load}. If the port's character encoding is the same as the
1006 encoding of the code to be read by the port, not other special
1007 handling is necessary. The port will automatically do the character
1008 encoding conversion. The functions @code{setlocale} or by
1009 @code{set-port-encoding!} are used to set port encodings
1010 (@pxref{Ports}).
1011
1012 If a port is used to read code of unknown character encoding, it can
1013 accomplish this in three steps. First, the character encoding of the
1014 port should be set to ISO-8859-1 using @code{set-port-encoding!}.
1015 Then, the procedure @code{file-encoding}, described below, is used to
1016 scan for a coding declaration when reading from the port. As a side
1017 effect, it rewinds the port after its scan is complete. After that,
1018 the port's character encoding should be set to the encoding returned
1019 by @code{file-encoding}, if any, again by using
1020 @code{set-port-encoding!}. Then the code can be read as normal.
1021
1022 @deffn {Scheme Procedure} file-encoding port
1023 @deffnx {C Function} scm_file_encoding (port)
1024 Scan the port for an Emacs-like character coding declaration near the
1025 top of the contents of a port with random-accessible contents
1026 (@pxref{Recognize Coding, how Emacs recognizes file encoding,, emacs,
1027 The GNU Emacs Reference Manual}). The coding declaration is of the form
1028 @code{coding: XXXXX} and must appear in a Scheme comment. Return a
1029 string containing the character encoding of the file if a declaration
1030 was found, or @code{#f} otherwise. The port is rewound.
1031 @end deffn
1032
1033
1034 @node Delayed Evaluation
1035 @subsection Delayed Evaluation
1036 @cindex delayed evaluation
1037 @cindex promises
1038
1039 Promises are a convenient way to defer a calculation until its result
1040 is actually needed, and to run such a calculation only once.
1041
1042 @deffn syntax delay expr
1043 @rnindex delay
1044 Return a promise object which holds the given @var{expr} expression,
1045 ready to be evaluated by a later @code{force}.
1046 @end deffn
1047
1048 @deffn {Scheme Procedure} promise? obj
1049 @deffnx {C Function} scm_promise_p (obj)
1050 Return true if @var{obj} is a promise.
1051 @end deffn
1052
1053 @rnindex force
1054 @deffn {Scheme Procedure} force p
1055 @deffnx {C Function} scm_force (p)
1056 Return the value obtained from evaluating the @var{expr} in the given
1057 promise @var{p}. If @var{p} has previously been forced then its
1058 @var{expr} is not evaluated again, instead the value obtained at that
1059 time is simply returned.
1060
1061 During a @code{force}, an @var{expr} can call @code{force} again on
1062 its own promise, resulting in a recursive evaluation of that
1063 @var{expr}. The first evaluation to return gives the value for the
1064 promise. Higher evaluations run to completion in the normal way, but
1065 their results are ignored, @code{force} always returns the first
1066 value.
1067 @end deffn
1068
1069
1070 @node Local Evaluation
1071 @subsection Local Evaluation
1072
1073 Guile includes a facility to capture a lexical environment, and later
1074 evaluate a new expression within that environment. This code is
1075 implemented in a module.
1076
1077 @example
1078 (use-modules (ice-9 local-eval))
1079 @end example
1080
1081 @deffn syntax the-environment
1082 Captures and returns a lexical environment for use with
1083 @code{local-eval} or @code{local-compile}.
1084 @end deffn
1085
1086 @deffn {Scheme Procedure} local-eval exp env
1087 @deffnx {C Function} scm_local_eval (exp, env)
1088 @deffnx {Scheme Procedure} local-compile exp env [opts=()]
1089 Evaluate or compile the expression @var{exp} in the lexical environment
1090 @var{env}.
1091 @end deffn
1092
1093 Here is a simple example, illustrating that it is the variable
1094 that gets captured, not just its value at one point in time.
1095
1096 @example
1097 (define e (let ((x 100)) (the-environment)))
1098 (define fetch-x (local-eval '(lambda () x) e))
1099 (fetch-x)
1100 @result{} 100
1101 (local-eval '(set! x 42) e)
1102 (fetch-x)
1103 @result{} 42
1104 @end example
1105
1106 While @var{exp} is evaluated within the lexical environment of
1107 @code{(the-environment)}, it has the dynamic environment of the call to
1108 @code{local-eval}.
1109
1110 @code{local-eval} and @code{local-compile} can only evaluate
1111 expressions, not definitions.
1112
1113 @example
1114 (local-eval '(define foo 42)
1115 (let ((x 100)) (the-environment)))
1116 @result{} syntax error: definition in expression context
1117 @end example
1118
1119 Note that the current implementation of @code{(the-environment)} only
1120 captures ``normal'' lexical bindings, and pattern variables bound by
1121 @code{syntax-case}. It does not currently capture local syntax
1122 transformers bound by @code{let-syntax}, @code{letrec-syntax} or
1123 non-top-level @code{define-syntax} forms. Any attempt to reference such
1124 captured syntactic keywords via @code{local-eval} or
1125 @code{local-compile} produces an error.
1126
1127
1128 @node Local Inclusion
1129 @subsection Local Inclusion
1130
1131 This section has discussed various means of linking Scheme code
1132 together: fundamentally, loading up files at run-time using @code{load}
1133 and @code{load-compiled}. Guile provides another option to compose
1134 parts of programs together at expansion-time instead of at run-time.
1135
1136 @deffn {Scheme Syntax} include file-name
1137 Open @var{file-name}, at expansion-time, and read the Scheme forms that
1138 it contains, splicing them into the location of the @code{include},
1139 within a @code{begin}.
1140 @end deffn
1141
1142 If you are a C programmer, if @code{load} in Scheme is like
1143 @code{dlopen} in C, consider @code{include} to be like the C
1144 preprocessor's @code{#include}. When you use @code{include}, it is as
1145 if the contents of the included file were typed in instead of the
1146 @code{include} form.
1147
1148 Because the code is included at compile-time, it is available to the
1149 macroexpander. Syntax definitions in the included file are available to
1150 later code in the form in which the @code{include} appears, without the
1151 need for @code{eval-when}. (@xref{Eval When}.)
1152
1153 For the same reason, compiling a form that uses @code{include} results
1154 in one compilation unit, composed of multiple files. Loading the
1155 compiled file is one @code{stat} operation for the compilation unit,
1156 instead of @code{2*@var{n}} in the case of @code{load} (once for each
1157 loaded source file, and once each corresponding compiled file, in the
1158 best case).
1159
1160 Unlike @code{load}, @code{include} also works within nested lexical
1161 contexts. It so happens that the optimizer works best within a lexical
1162 context, because all of the uses of bindings in a lexical context are
1163 visible, so composing files by including them within a @code{(let ()
1164 ...)} can sometimes lead to important speed improvements.
1165
1166 On the other hand, @code{include} does have all the disadvantages of
1167 early binding: once the code with the @code{include} is compiled, no
1168 change to the included file is reflected in the future behavior of the
1169 including form.
1170
1171 Also, the particular form of @code{include}, which requires an absolute
1172 path, or a path relative to the current directory at compile-time, is
1173 not very amenable to compiling the source in one place, but then
1174 installing the source to another place. For this reason, Guile provides
1175 another form, @code{include-from-path}, which looks for the source file
1176 to include within a load path.
1177
1178 @deffn {Scheme Syntax} include-from-path file-name
1179 Like @code{include}, but instead of expecting @code{file-name} to be an
1180 absolute file name, it is expected to be a relative path to search in
1181 the @code{%load-path}.
1182 @end deffn
1183
1184 @code{include-from-path} is more useful when you want to install all of
1185 the source files for a package (as you should!). It makes it possible
1186 to evaluate an installed file from source, instead of relying on the
1187 @code{.go} file being up to date.
1188
1189 @c Local Variables:
1190 @c TeX-master: "guile.texi"
1191 @c End: