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