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