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