2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2009,
4 @c 2010, 2011, 2012, 2013, 2014 Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
7 @node Read/Load/Eval/Compile
8 @section Reading and Evaluating Scheme Code
10 This chapter describes Guile functions that are concerned with reading,
11 loading, evaluating, and compiling Scheme code at run time.
14 * Scheme Syntax:: Standard and extended Scheme syntax.
15 * Scheme Read:: Reading Scheme code.
16 * Scheme Write:: Writing Scheme values to a port.
17 * Fly Evaluation:: Procedures for on the fly evaluation.
18 * Compilation:: How to compile Scheme files and procedures.
19 * Loading:: Loading Scheme code from file.
20 * Load Paths:: Where Guile looks for code.
21 * Character Encoding of Source Files:: Loading non-ASCII Scheme code from file.
22 * Delayed Evaluation:: Postponing evaluation until it is needed.
23 * Local Evaluation:: Evaluation in a local lexical environment.
24 * Local Inclusion:: Compile-time inclusion of one file in another.
25 * REPL Servers:: Serving a REPL over a socket.
26 * Cooperative REPL Servers:: REPL server for single-threaded applications.
31 @subsection Scheme Syntax: Standard and Guile Extensions
43 @node Expression Syntax
44 @subsubsection Expression Syntax
46 An expression to be evaluated takes one of the following forms.
51 A symbol is evaluated by dereferencing. A binding of that symbol is
52 sought and the value there used. For example,
59 @item (@var{proc} @var{args}@dots{})
60 A parenthesised expression is a function call. @var{proc} and each
61 argument are evaluated, then the function (which @var{proc} evaluated
62 to) is called with those arguments.
64 The order in which @var{proc} and the arguments are evaluated is
65 unspecified, so be careful when using expressions with side effects.
68 (max 1 2 3) @result{} 3
70 (define (get-some-proc) min)
71 ((get-some-proc) 1 2 3) @result{} 1
74 The same sort of parenthesised form is used for a macro invocation,
75 but in that case the arguments are not evaluated. See the
76 descriptions of macros for more on this (@pxref{Macros}, and
77 @pxref{Syntax Rules}).
80 Number, string, character and boolean constants evaluate ``to
81 themselves'', so can appear as literals.
86 "hello" @result{} "hello"
91 Note that an application must not attempt to modify literal strings,
92 since they may be in read-only memory.
94 @item (quote @var{data})
98 Quoting is used to obtain a literal symbol (instead of a variable
99 reference), a literal list (instead of a function call), or a literal
100 vector. @nicode{'} is simply a shorthand for a @code{quote} form.
105 '(1 2 3) @result{} (1 2 3)
106 '#(1 (2 3) 4) @result{} #(1 (2 3) 4)
107 (quote x) @result{} x
108 (quote (1 2 3)) @result{} (1 2 3)
109 (quote #(1 (2 3) 4)) @result{} #(1 (2 3) 4)
112 Note that an application must not attempt to modify literal lists or
113 vectors obtained from a @code{quote} form, since they may be in
116 @item (quasiquote @var{data})
120 Backquote quasi-quotation is like @code{quote}, but selected
121 sub-expressions are evaluated. This is a convenient way to construct
122 a list or vector structure most of which is constant, but at certain
123 points should have expressions substituted.
125 The same effect can always be had with suitable @code{list},
126 @code{cons} or @code{vector} calls, but quasi-quoting is often easier.
130 @item (unquote @var{expr})
134 Within the quasiquote @var{data}, @code{unquote} or @code{,} indicates
135 an expression to be evaluated and inserted. The comma syntax @code{,}
136 is simply a shorthand for an @code{unquote} form. For example,
139 `(1 2 ,(* 9 9) 3 4) @result{} (1 2 81 3 4)
140 `(1 (unquote (+ 1 1)) 3) @result{} (1 2 3)
141 `#(1 ,(/ 12 2)) @result{} #(1 6)
144 @item (unquote-splicing @var{expr})
146 @findex unquote-splicing
148 Within the quasiquote @var{data}, @code{unquote-splicing} or
149 @code{,@@} indicates an expression to be evaluated and the elements of
150 the returned list inserted. @var{expr} must evaluate to a list. The
151 ``comma-at'' syntax @code{,@@} is simply a shorthand for an
152 @code{unquote-splicing} form.
156 `(1 ,@@x 4) @result{} (1 2 3 4)
157 `(1 (unquote-splicing (map 1+ x))) @result{} (1 3 4)
158 `#(9 ,@@x 9) @result{} #(9 2 3 9)
161 Notice @code{,@@} differs from plain @code{,} in the way one level of
162 nesting is stripped. For @code{,@@} the elements of a returned list
163 are inserted, whereas with @code{,} it would be the list itself
168 @c FIXME: What can we say about the mutability of a quasiquote
169 @c result? R5RS doesn't seem to specify anything, though where it
170 @c says backquote without commas is the same as plain quote then
171 @c presumably the "fixed" portions of a quasiquote expression must be
172 @c treated as immutable.
179 @subsubsection Comments
181 @c FIXME::martin: Review me!
183 Comments in Scheme source files are written by starting them with a
184 semicolon character (@code{;}). The comment then reaches up to the end
185 of the line. Comments can begin at any column, and the may be inserted
186 on the same line as Scheme code.
191 (define x 1) ; Comment after expression
193 ;; Display something.
195 ;;; Comment at left margin.
199 It is common to use a single semicolon for comments following
200 expressions on a line, to use two semicolons for comments which are
201 indented like code, and three semicolons for comments which start at
202 column 0, even if they are inside an indented code block. This
203 convention is used when indenting code in Emacs' Scheme mode.
207 @subsubsection Block Comments
208 @cindex multiline comments
209 @cindex block comments
213 @c FIXME::martin: Review me!
215 In addition to the standard line comments defined by R5RS, Guile has
216 another comment type for multiline comments, called @dfn{block
217 comments}. This type of comment begins with the character sequence
218 @code{#!} and ends with the characters @code{!#}.
220 These comments are compatible with the block
221 comments in the Scheme Shell @file{scsh} (@pxref{The Scheme shell
222 (scsh)}). The characters @code{#!} were chosen because they are the
223 magic characters used in shell scripts for indicating that the name of
224 the program for executing the script follows on the same line.
226 Thus a Guile script often starts like this.
229 #! /usr/local/bin/guile -s
233 More details on Guile scripting can be found in the scripting section
234 (@pxref{Guile Scripting}).
236 @cindex R6RS block comments
237 @cindex SRFI-30 block comments
238 Similarly, Guile (starting from version 2.0) supports nested block
239 comments as specified by R6RS and
240 @url{http://srfi.schemers.org/srfi-30/srfi-30.html, SRFI-30}:
243 (+ 1 #| this is a #| nested |# block comment |# 2)
247 For backward compatibility, this syntax can be overridden with
248 @code{read-hash-extend} (@pxref{Reader Extensions,
249 @code{read-hash-extend}}).
251 There is one special case where the contents of a comment can actually
252 affect the interpretation of code. When a character encoding
253 declaration, such as @code{coding: utf-8} appears in one of the first
254 few lines of a source file, it indicates to Guile's default reader
255 that this source code file is not ASCII. For details see @ref{Character
256 Encoding of Source Files}.
258 @node Case Sensitivity
259 @subsubsection Case Sensitivity
263 @c FIXME::martin: Review me!
265 Scheme as defined in R5RS is not case sensitive when reading symbols.
266 Guile, on the contrary is case sensitive by default, so the identifiers
273 are the same in R5RS Scheme, but are different in Guile.
275 It is possible to turn off case sensitivity in Guile by setting the
276 reader option @code{case-insensitive}. For more information on reader
277 options, @xref{Scheme Read}.
280 (read-enable 'case-insensitive)
283 It is also possible to disable (or enable) case sensitivity within a
284 single file by placing the reader directives @code{#!fold-case} (or
285 @code{#!no-fold-case}) within the file itself.
288 @subsubsection Keyword Syntax
291 @node Reader Extensions
292 @subsubsection Reader Extensions
294 @deffn {Scheme Procedure} read-hash-extend chr proc
295 @deffnx {C Function} scm_read_hash_extend (chr, proc)
296 Install the procedure @var{proc} for reading expressions
297 starting with the character sequence @code{#} and @var{chr}.
298 @var{proc} will be called with two arguments: the character
299 @var{chr} and the port to read further data from. The object
300 returned will be the return value of @code{read}.
301 Passing @code{#f} for @var{proc} will remove a previous setting.
307 @subsection Reading Scheme Code
310 @deffn {Scheme Procedure} read [port]
311 @deffnx {C Function} scm_read (port)
312 Read an s-expression from the input port @var{port}, or from
313 the current input port if @var{port} is not specified.
314 Any whitespace before the next token is discarded.
317 The behaviour of Guile's Scheme reader can be modified by manipulating
320 @cindex options - read
322 @deffn {Scheme Procedure} read-options [setting]
323 Display the current settings of the global read options. If
324 @var{setting} is omitted, only a short form of the current read options
325 is printed. Otherwise if @var{setting} is the symbol @code{help}, a
326 complete options description is displayed.
329 The set of available options, and their default values, may be had by
330 invoking @code{read-options} at the prompt.
333 scheme@@(guile-user)> (read-options)
334 (square-brackets keywords #f positions)
335 scheme@@(guile-user)> (read-options 'help)
336 copy no Copy source code expressions.
337 positions yes Record positions of source code expressions.
338 case-insensitive no Convert symbols to lower case.
339 keywords #f Style of keyword recognition: #f, 'prefix or 'postfix.
340 r6rs-hex-escapes no Use R6RS variable-length character and string hex escapes.
341 square-brackets yes Treat `[' and `]' as parentheses, for R6RS compatibility.
342 hungry-eol-escapes no In strings, consume leading whitespace after an
344 curly-infix no Support SRFI-105 curly infix expressions.
345 r7rs-symbols no Support R7RS |...| symbol notation.
348 Note that Guile also includes a preliminary mechanism for setting read
349 options on a per-port basis. For instance, the @code{case-insensitive}
350 read option is set (or unset) on the port when the reader encounters the
351 @code{#!fold-case} or @code{#!no-fold-case} reader directives.
352 Similarly, the @code{#!curly-infix} reader directive sets the
353 @code{curly-infix} read option on the port, and
354 @code{#!curly-infix-and-bracket-lists} sets @code{curly-infix} and
355 unsets @code{square-brackets} on the port (@pxref{SRFI-105}). There is
356 currently no other way to access or set the per-port read options.
358 The boolean options may be toggled with @code{read-enable} and
359 @code{read-disable}. The non-boolean @code{keywords} option must be set
360 using @code{read-set!}.
362 @deffn {Scheme Procedure} read-enable option-name
363 @deffnx {Scheme Procedure} read-disable option-name
364 @deffnx {Scheme Syntax} read-set! option-name value
365 Modify the read options. @code{read-enable} should be used with boolean
366 options and switches them on, @code{read-disable} switches them off.
368 @code{read-set!} can be used to set an option to a specific value. Due
369 to historical oddities, it is a macro that expects an unquoted option
373 For example, to make @code{read} fold all symbols to their lower case
374 (perhaps for compatibility with older Scheme code), you can enter:
377 (read-enable 'case-insensitive)
380 For more information on the effect of the @code{r6rs-hex-escapes} and
381 @code{hungry-eol-escapes} options, see (@pxref{String Syntax}).
383 For more information on the @code{r7rs-symbols} option, see
384 (@pxref{Symbol Read Syntax}).
388 @subsection Writing Scheme Values
390 Any scheme value may be written to a port. Not all values may be read
391 back in (@pxref{Scheme Read}), however.
395 @deffn {Scheme Procedure} write obj [port]
396 Send a representation of @var{obj} to @var{port} or to the current
397 output port if not given.
399 The output is designed to be machine readable, and can be read back
400 with @code{read} (@pxref{Scheme Read}). Strings are printed in
401 double quotes, with escapes if necessary, and characters are printed in
406 @deffn {Scheme Procedure} display obj [port]
407 Send a representation of @var{obj} to @var{port} or to the current
408 output port if not given.
410 The output is designed for human readability, it differs from
411 @code{write} in that strings are printed without double quotes and
412 escapes, and characters are printed as per @code{write-char}, not in
416 As was the case with the Scheme reader, there are a few options that
417 affect the behavior of the Scheme printer.
419 @cindex options - print
420 @cindex print options
421 @deffn {Scheme Procedure} print-options [setting]
422 Display the current settings of the read options. If @var{setting} is
423 omitted, only a short form of the current read options is
424 printed. Otherwise if @var{setting} is the symbol @code{help}, a
425 complete options description is displayed.
428 The set of available options, and their default values, may be had by
429 invoking @code{print-options} at the prompt.
432 scheme@@(guile-user)> (print-options)
433 (quote-keywordish-symbols reader highlight-suffix "@}" highlight-prefix "@{")
434 scheme@@(guile-user)> (print-options 'help)
435 highlight-prefix @{ The string to print before highlighted values.
436 highlight-suffix @} The string to print after highlighted values.
437 quote-keywordish-symbols reader How to print symbols that have a colon
438 as their first or last character. The
439 value '#f' does not quote the colons;
440 '#t' quotes them; 'reader' quotes them
441 when the reader option 'keywords' is
443 escape-newlines yes Render newlines as \n when printing
445 r7rs-symbols no Escape symbols using R7RS |...| symbol
449 These options may be modified with the print-set! syntax.
451 @deffn {Scheme Syntax} print-set! option-name value
452 Modify the print options. Due to historical oddities, @code{print-set!}
453 is a macro that expects an unquoted option name.
458 @subsection Procedures for On the Fly Evaluation
460 Scheme has the lovely property that its expressions may be represented
461 as data. The @code{eval} procedure takes a Scheme datum and evaluates
465 @c ARGFIXME environment/environment specifier
466 @deffn {Scheme Procedure} eval exp module_or_state
467 @deffnx {C Function} scm_eval (exp, module_or_state)
468 Evaluate @var{exp}, a list representing a Scheme expression,
469 in the top-level environment specified by @var{module_or_state}.
470 While @var{exp} is evaluated (using @code{primitive-eval}),
471 @var{module_or_state} is made the current module. The current module
472 is reset to its previous value when @code{eval} returns.
473 XXX - dynamic states.
474 Example: (eval '(+ 1 2) (interaction-environment))
477 @rnindex interaction-environment
478 @deffn {Scheme Procedure} interaction-environment
479 @deffnx {C Function} scm_interaction_environment ()
480 Return a specifier for the environment that contains
481 implementation--defined bindings, typically a superset of those
482 listed in the report. The intent is that this procedure will
483 return the environment in which the implementation would
484 evaluate expressions dynamically typed by the user.
487 @xref{Environments}, for other environments.
489 One does not always receive code as Scheme data, of course, and this is
490 especially the case for Guile's other language implementations
491 (@pxref{Other Languages}). For the case in which all you have is a
492 string, we have @code{eval-string}. There is a legacy version of this
493 procedure in the default environment, but you really want the one from
494 @code{(ice-9 eval-string)}, so load it up:
497 (use-modules (ice-9 eval-string))
500 @deffn {Scheme Procedure} eval-string string [#:module=#f] [#:file=#f] @
501 [#:line=#f] [#:column=#f] @
502 [#:lang=(current-language)] @
504 Parse @var{string} according to the current language, normally Scheme.
505 Evaluate or compile the expressions it contains, in order, returning the
508 If the @var{module} keyword argument is set, save a module excursion
509 (@pxref{Module System Reflection}) and set the current module to
510 @var{module} before evaluation.
512 The @var{file}, @var{line}, and @var{column} keyword arguments can be
513 used to indicate that the source string begins at a particular source
516 Finally, @var{lang} is a language, defaulting to the current language,
517 and the expression is compiled if @var{compile?} is true or there is no
518 evaluator for the given language.
521 @deffn {C Function} scm_eval_string (string)
522 @deffnx {C Function} scm_eval_string_in_module (string, module)
523 These C bindings call @code{eval-string} from @code{(ice-9
524 eval-string)}, evaluating within @var{module} or the current module.
527 @deftypefn {C Function} SCM scm_c_eval_string (const char *string)
528 @code{scm_eval_string}, but taking a C string in locale encoding instead
532 @deffn {Scheme Procedure} apply proc arg @dots{} arglst
533 @deffnx {C Function} scm_apply_0 (proc, arglst)
534 @deffnx {C Function} scm_apply_1 (proc, arg1, arglst)
535 @deffnx {C Function} scm_apply_2 (proc, arg1, arg2, arglst)
536 @deffnx {C Function} scm_apply_3 (proc, arg1, arg2, arg3, arglst)
537 @deffnx {C Function} scm_apply (proc, arg, rest)
539 Call @var{proc} with arguments @var{arg} @dots{} and the
540 elements of the @var{arglst} list.
542 @code{scm_apply} takes parameters corresponding to a Scheme level
543 @code{(lambda (proc arg1 . rest) ...)}. So @var{arg1} and all but the
544 last element of the @var{rest} list make up @var{arg} @dots{}, and the
545 last element of @var{rest} is the @var{arglst} list. Or if @var{rest}
546 is the empty list @code{SCM_EOL} then there's no @var{arg} @dots{}, and
547 (@var{arg1}) is the @var{arglst}.
549 @var{arglst} is not modified, but the @var{rest} list passed to
550 @code{scm_apply} is modified.
553 @deffn {C Function} scm_call_0 (proc)
554 @deffnx {C Function} scm_call_1 (proc, arg1)
555 @deffnx {C Function} scm_call_2 (proc, arg1, arg2)
556 @deffnx {C Function} scm_call_3 (proc, arg1, arg2, arg3)
557 @deffnx {C Function} scm_call_4 (proc, arg1, arg2, arg3, arg4)
558 @deffnx {C Function} scm_call_5 (proc, arg1, arg2, arg3, arg4, arg5)
559 @deffnx {C Function} scm_call_6 (proc, arg1, arg2, arg3, arg4, arg5, arg6)
560 @deffnx {C Function} scm_call_7 (proc, arg1, arg2, arg3, arg4, arg5, arg6, arg7)
561 @deffnx {C Function} scm_call_8 (proc, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)
562 @deffnx {C Function} scm_call_9 (proc, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9)
563 Call @var{proc} with the given arguments.
566 @deffn {C Function} scm_call (proc, ...)
567 Call @var{proc} with any number of arguments. The argument list must be
568 terminated by @code{SCM_UNDEFINED}. For example:
571 scm_call (scm_c_public_ref ("guile", "+"),
578 @deffn {C Function} scm_call_n (proc, argv, nargs)
579 Call @var{proc} with the array of arguments @var{argv}, as a
580 @code{SCM*}. The length of the arguments should be passed in
581 @var{nargs}, as a @code{size_t}.
584 @deffn {Scheme Procedure} primitive-eval exp
585 @deffnx {C Function} scm_primitive_eval (exp)
586 Evaluate @var{exp} in the top-level environment specified by
592 @subsection Compiling Scheme Code
594 The @code{eval} procedure directly interprets the S-expression
595 representation of Scheme. An alternate strategy for evaluation is to
596 determine ahead of time what computations will be necessary to
597 evaluate the expression, and then use that recipe to produce the
598 desired results. This is known as @dfn{compilation}.
600 While it is possible to compile simple Scheme expressions such as
601 @code{(+ 2 2)} or even @code{"Hello world!"}, compilation is most
602 interesting in the context of procedures. Compiling a lambda expression
603 produces a compiled procedure, which is just like a normal procedure
604 except typically much faster, because it can bypass the generic
607 Functions from system modules in a Guile installation are normally
608 compiled already, so they load and run quickly.
610 @cindex automatic compilation
611 Note that well-written Scheme programs will not typically call the
612 procedures in this section, for the same reason that it is often bad
613 taste to use @code{eval}. By default, Guile automatically compiles any
614 files it encounters that have not been compiled yet (@pxref{Invoking
615 Guile, @code{--auto-compile}}). The compiler can also be invoked
616 explicitly from the shell as @code{guild compile foo.scm}.
618 (Why are calls to @code{eval} and @code{compile} usually in bad taste?
619 Because they are limited, in that they can only really make sense for
620 top-level expressions. Also, most needs for ``compile-time''
621 computation are fulfilled by macros and closures. Of course one good
622 counterexample is the REPL itself, or any code that reads expressions
625 Automatic compilation generally works transparently, without any need
626 for user intervention. However Guile does not yet do proper dependency
627 tracking, so that if file @file{@var{a}.scm} uses macros from
628 @file{@var{b}.scm}, and @var{@var{b}.scm} changes, @code{@var{a}.scm}
629 would not be automatically recompiled. To forcibly invalidate the
630 auto-compilation cache, pass the @code{--fresh-auto-compile} option to
631 Guile, or set the @code{GUILE_AUTO_COMPILE} environment variable to
632 @code{fresh} (instead of to @code{0} or @code{1}).
634 For more information on the compiler itself, see @ref{Compiling to the
635 Virtual Machine}. For information on the virtual machine, see @ref{A
636 Virtual Machine for Guile}.
638 The command-line interface to Guile's compiler is the @command{guild
641 @deffn {Command} {guild compile} [@option{option}...] @var{file}...
642 Compile @var{file}, a source file, and store bytecode in the compilation cache
643 or in the file specified by the @option{-o} option. The following options are
649 @itemx --load-path=@var{dir}
650 Add @var{dir} to the front of the module load path.
653 @itemx --output=@var{ofile}
654 Write output bytecode to @var{ofile}. By convention, bytecode file
655 names end in @code{.go}. When @option{-o} is omitted, the output file
656 name is as for @code{compile-file} (see below).
658 @item -W @var{warning}
659 @itemx --warn=@var{warning}
660 @cindex warnings, compiler
661 Emit warnings of type @var{warning}; use @code{--warn=help} for a list
662 of available warnings and their description. Currently recognized
663 warnings include @code{unused-variable}, @code{unused-toplevel},
664 @code{unbound-variable}, @code{arity-mismatch}, @code{format},
665 @code{duplicate-case-datum}, and @code{bad-case-datum}.
668 @itemx --from=@var{lang}
669 Use @var{lang} as the source language of @var{file}. If this option is omitted,
670 @code{scheme} is assumed.
673 @itemx --to=@var{lang}
674 Use @var{lang} as the target language of @var{file}. If this option is omitted,
675 @code{rtl} is assumed.
677 @item -T @var{target}
678 @itemx --target=@var{target}
679 Produce code for @var{target} instead of @var{%host-type} (@pxref{Build
680 Config, %host-type}). Target must be a valid GNU triplet, such as
681 @code{armv5tel-unknown-linux-gnueabi} (@pxref{Specifying Target
682 Triplets,,, autoconf, GNU Autoconf Manual}).
686 Each @var{file} is assumed to be UTF-8-encoded, unless it contains a
687 coding declaration as recognized by @code{file-encoding}
688 (@pxref{Character Encoding of Source Files}).
691 The compiler can also be invoked directly by Scheme code using the procedures
694 @deffn {Scheme Procedure} compile exp [#:env=#f] @
695 [#:from=(current-language)] @
696 [#:to=value] [#:opts=()]
697 Compile the expression @var{exp} in the environment @var{env}. If
698 @var{exp} is a procedure, the result will be a compiled procedure;
699 otherwise @code{compile} is mostly equivalent to @code{eval}.
701 For a discussion of languages and compiler options, @xref{Compiling to
702 the Virtual Machine}.
705 @deffn {Scheme Procedure} compile-file file [#:output-file=#f] @
706 [#:from=(current-language)] [#:to='rtl] @
707 [#:env=(default-environment from)] @
709 [#:canonicalization='relative]
710 Compile the file named @var{file}.
712 Output will be written to a @var{output-file}. If you do not supply an
713 output file name, output is written to a file in the cache directory, as
714 computed by @code{(compiled-file-name @var{file})}.
716 @var{from} and @var{to} specify the source and target languages.
717 @xref{Compiling to the Virtual Machine}, for more information on these
718 options, and on @var{env} and @var{opts}.
720 As with @command{guild compile}, @var{file} is assumed to be
721 UTF-8-encoded unless it contains a coding declaration.
724 @deffn {Scheme Procedure} compiled-file-name file
725 Compute a cached location for a compiled version of a Scheme file named
728 This file will usually be below the @file{$HOME/.cache/guile/ccache}
729 directory, depending on the value of the @env{XDG_CACHE_HOME}
730 environment variable. The intention is that @code{compiled-file-name}
731 provides a fallback location for caching auto-compiled files. If you
732 want to place a compile file in the @code{%load-compiled-path}, you
733 should pass the @var{output-file} option to @code{compile-file},
737 @defvr {Scheme Variable} %auto-compilation-options
738 This variable contains the options passed to the @code{compile-file}
739 procedure when auto-compiling source files. By default, it enables
740 useful compilation warnings. It can be customized from @file{~/.guile}.
744 @subsection Loading Scheme Code from File
747 @deffn {Scheme Procedure} load filename [reader]
748 Load @var{filename} and evaluate its contents in the top-level
751 @var{reader} if provided should be either @code{#f}, or a procedure with
752 the signature @code{(lambda (port) @dots{})} which reads the next
753 expression from @var{port}. If @var{reader} is @code{#f} or absent,
754 Guile's built-in @code{read} procedure is used (@pxref{Scheme Read}).
756 The @var{reader} argument takes effect by setting the value of the
757 @code{current-reader} fluid (see below) before loading the file, and
758 restoring its previous value when loading is complete. The Scheme code
759 inside @var{filename} can itself change the current reader procedure on
760 the fly by setting @code{current-reader} fluid.
762 If the variable @code{%load-hook} is defined, it should be bound to a
763 procedure that will be called before any code is loaded. See
764 documentation for @code{%load-hook} later in this section.
767 @deffn {Scheme Procedure} load-compiled filename
768 Load the compiled file named @var{filename}.
770 Compiling a source file (@pxref{Read/Load/Eval/Compile}) and then
771 calling @code{load-compiled} on the resulting file is equivalent to
772 calling @code{load} on the source file.
775 @deffn {Scheme Procedure} primitive-load filename
776 @deffnx {C Function} scm_primitive_load (filename)
777 Load the file named @var{filename} and evaluate its contents in the
778 top-level environment. @var{filename} must either be a full pathname or
779 be a pathname relative to the current directory. If the variable
780 @code{%load-hook} is defined, it should be bound to a procedure that
781 will be called before any code is loaded. See the documentation for
782 @code{%load-hook} later in this section.
785 @deftypefn {C Function} SCM scm_c_primitive_load (const char *filename)
786 @code{scm_primitive_load}, but taking a C string instead of an
790 @defvar current-reader
791 @code{current-reader} holds the read procedure that is currently being
792 used by the above loading procedures to read expressions (from the file
793 that they are loading). @code{current-reader} is a fluid, so it has an
794 independent value in each dynamic root and should be read and set using
795 @code{fluid-ref} and @code{fluid-set!} (@pxref{Fluids and Dynamic
798 Changing @code{current-reader} is typically useful to introduce local
799 syntactic changes, such that code following the @code{fluid-set!} call
800 is read using the newly installed reader. The @code{current-reader}
801 change should take place at evaluation time when the code is evaluated,
802 or at compilation time when the code is compiled:
806 (eval-when (compile eval)
807 (fluid-set! current-reader my-own-reader))
810 The @code{eval-when} form above ensures that the @code{current-reader}
811 change occurs at the right time.
815 A procedure to be called @code{(%load-hook @var{filename})} whenever a
816 file is loaded, or @code{#f} for no such call. @code{%load-hook} is
817 used by all of the loading functions (@code{load} and
818 @code{primitive-load}, and @code{load-from-path} and
819 @code{primitive-load-path} documented in the next section).
821 For example an application can set this to show what's loaded,
824 (set! %load-hook (lambda (filename)
825 (format #t "Loading ~a ...\n" filename)))
826 (load-from-path "foo.scm")
827 @print{} Loading /usr/local/share/guile/site/foo.scm ...
831 @deffn {Scheme Procedure} current-load-port
832 @deffnx {C Function} scm_current_load_port ()
833 Return the current-load-port.
834 The load port is used internally by @code{primitive-load}.
838 @subsection Load Paths
840 The procedure in the previous section look for Scheme code in the file
841 system at specific location. Guile also has some procedures to search
842 the load path for code.
845 List of directories which should be searched for Scheme modules and
846 libraries. When Guile starts up, @code{%load-path} is initialized to
847 the default load path @code{(list (%library-dir) (%site-dir)
848 (%global-site-dir) (%package-data-dir))}. The @env{GUILE_LOAD_PATH}
849 environment variable can be used to prepend or append additional
850 directories (@pxref{Environment Variables}).
852 @xref{Build Config}, for more on @code{%site-dir} and related
856 @deffn {Scheme Procedure} load-from-path filename
857 Similar to @code{load}, but searches for @var{filename} in the load
858 paths. Preferentially loads a compiled version of the file, if it is
859 available and up-to-date.
862 A user can extend the load path by calling @code{add-to-load-path}.
864 @deffn {Scheme Syntax} add-to-load-path dir
865 Add @var{dir} to the load path.
868 For example, a script might include this form to add the directory that
869 it is in to the load path:
872 (add-to-load-path (dirname (current-filename)))
875 It's better to use @code{add-to-load-path} than to modify
876 @code{%load-path} directly, because @code{add-to-load-path} takes care
877 of modifying the path both at compile-time and at run-time.
879 @deffn {Scheme Procedure} primitive-load-path filename [exception-on-not-found]
880 @deffnx {C Function} scm_primitive_load_path (filename)
881 Search @code{%load-path} for the file named @var{filename} and
882 load it into the top-level environment. If @var{filename} is a
883 relative pathname and is not found in the list of search paths,
884 an error is signalled. Preferentially loads a compiled version of the
885 file, if it is available and up-to-date.
887 If @var{filename} is a relative pathname and is not found in the list of
888 search paths, one of three things may happen, depending on the optional
889 second argument, @var{exception-on-not-found}. If it is @code{#f},
890 @code{#f} will be returned. If it is a procedure, it will be called
891 with no arguments. (This allows a distinction to be made between
892 exceptions raised by loading a file, and exceptions related to the
893 loader itself.) Otherwise an error is signalled.
895 For compatibility with Guile 1.8 and earlier, the C function takes only
896 one argument, which can be either a string (the file name) or an
900 @deffn {Scheme Procedure} %search-load-path filename
901 @deffnx {C Function} scm_sys_search_load_path (filename)
902 Search @code{%load-path} for the file named @var{filename}, which must
903 be readable by the current user. If @var{filename} is found in the list
904 of paths to search or is an absolute pathname, return its full pathname.
905 Otherwise, return @code{#f}. Filenames may have any of the optional
906 extensions in the @code{%load-extensions} list; @code{%search-load-path}
907 will try each extension automatically.
910 @defvar %load-extensions
911 A list of default file extensions for files containing Scheme code.
912 @code{%search-load-path} tries each of these extensions when looking for
913 a file to load. By default, @code{%load-extensions} is bound to the
914 list @code{("" ".scm")}.
917 As mentioned above, when Guile searches the @code{%load-path} for a
918 source file, it will also search the @code{%load-compiled-path} for a
919 corresponding compiled file. If the compiled file is as new or newer
920 than the source file, it will be loaded instead of the source file,
921 using @code{load-compiled}.
923 @defvar %load-compiled-path
924 Like @code{%load-path}, but for compiled files. By default, this path
925 has two entries: one for compiled files from Guile itself, and one for
926 site packages. The @env{GUILE_LOAD_COMPILED_PATH} environment variable
927 can be used to prepend or append additional directories
928 (@pxref{Environment Variables}).
931 When @code{primitive-load-path} searches the @code{%load-compiled-path}
932 for a corresponding compiled file for a relative path it does so by
933 appending @code{.go} to the relative path. For example, searching for
934 @code{ice-9/popen} could find
935 @code{/usr/lib/guile/2.2/ccache/ice-9/popen.go}, and use it instead of
936 @code{/usr/share/guile/2.2/ice-9/popen.scm}.
938 If @code{primitive-load-path} does not find a corresponding @code{.go}
939 file in the @code{%load-compiled-path}, or the @code{.go} file is out of
940 date, it will search for a corresponding auto-compiled file in the
941 fallback path, possibly creating one if one does not exist.
943 @xref{Installing Site Packages}, for more on how to correctly install
944 site packages. @xref{Modules and the File System}, for more on the
945 relationship between load paths and modules. @xref{Compilation}, for
946 more on the fallback path and auto-compilation.
948 Finally, there are a couple of helper procedures for general path
951 @deffn {Scheme Procedure} parse-path path [tail]
952 @deffnx {C Function} scm_parse_path (path, tail)
953 Parse @var{path}, which is expected to be a colon-separated string, into
954 a list and return the resulting list with @var{tail} appended. If
955 @var{path} is @code{#f}, @var{tail} is returned.
958 @deffn {Scheme Procedure} parse-path-with-ellipsis path base
959 @deffnx {C Function} scm_parse_path_with_ellipsis (path, base)
960 Parse @var{path}, which is expected to be a colon-separated string, into
961 a list and return the resulting list with @var{base} (a list) spliced in
962 place of the @code{...} path component, if present, or else @var{base}
963 is added to the end. If @var{path} is @code{#f}, @var{base} is
967 @deffn {Scheme Procedure} search-path path filename [extensions [require-exts?]]
968 @deffnx {C Function} scm_search_path (path, filename, rest)
969 Search @var{path} for a directory containing a file named
970 @var{filename}. The file must be readable, and not a directory. If we
971 find one, return its full filename; otherwise, return @code{#f}. If
972 @var{filename} is absolute, return it unchanged. If given,
973 @var{extensions} is a list of strings; for each directory in @var{path},
974 we search for @var{filename} concatenated with each @var{extension}. If
975 @var{require-exts?} is true, require that the returned file name have
976 one of the given extensions; if @var{require-exts?} is not given, it
977 defaults to @code{#f}.
979 For compatibility with Guile 1.8 and earlier, the C function takes only
984 @node Character Encoding of Source Files
985 @subsection Character Encoding of Source Files
987 @cindex source file encoding
988 @cindex primitive-load
990 Scheme source code files are usually encoded in ASCII or UTF-8, but the
991 built-in reader can interpret other character encodings as well. When
992 Guile loads Scheme source code, it uses the @code{file-encoding}
993 procedure (described below) to try to guess the encoding of the file.
994 In the absence of any hints, UTF-8 is assumed. One way to provide a
995 hint about the encoding of a source file is to place a coding
996 declaration in the top 500 characters of the file.
998 A coding declaration has the form @code{coding: XXXXXX}, where
999 @code{XXXXXX} is the name of a character encoding in which the source
1000 code file has been encoded. The coding declaration must appear in a
1001 scheme comment. It can either be a semicolon-initiated comment, or the
1002 first block @code{#!} comment in the file.
1004 The name of the character encoding in the coding declaration is
1005 typically lower case and containing only letters, numbers, and hyphens,
1006 as recognized by @code{set-port-encoding!} (@pxref{Ports,
1007 @code{set-port-encoding!}}). Common examples of character encoding
1008 names are @code{utf-8} and @code{iso-8859-1},
1009 @url{http://www.iana.org/assignments/character-sets, as defined by
1010 IANA}. Thus, the coding declaration is mostly compatible with Emacs.
1012 However, there are some differences in encoding names recognized by
1013 Emacs and encoding names defined by IANA, the latter being essentially a
1014 subset of the former. For instance, @code{latin-1} is a valid encoding
1015 name for Emacs, but it's not according to the IANA standard, which Guile
1016 follows; instead, you should use @code{iso-8859-1}, which is both
1017 understood by Emacs and dubbed by IANA (IANA writes it uppercase but
1018 Emacs wants it lowercase and Guile is case insensitive.)
1020 For source code, only a subset of all possible character encodings can
1021 be interpreted by the built-in source code reader. Only those
1022 character encodings in which ASCII text appears unmodified can be
1023 used. This includes @code{UTF-8} and @code{ISO-8859-1} through
1024 @code{ISO-8859-15}. The multi-byte character encodings @code{UTF-16}
1025 and @code{UTF-32} may not be used because they are not compatible with
1030 @cindex port encoding
1031 @findex set-port-encoding!
1032 There might be a scenario in which one would want to read non-ASCII
1033 code from a port, such as with the function @code{read}, instead of
1034 with @code{load}. If the port's character encoding is the same as the
1035 encoding of the code to be read by the port, not other special
1036 handling is necessary. The port will automatically do the character
1037 encoding conversion. The functions @code{setlocale} or by
1038 @code{set-port-encoding!} are used to set port encodings
1041 If a port is used to read code of unknown character encoding, it can
1042 accomplish this in three steps. First, the character encoding of the
1043 port should be set to ISO-8859-1 using @code{set-port-encoding!}.
1044 Then, the procedure @code{file-encoding}, described below, is used to
1045 scan for a coding declaration when reading from the port. As a side
1046 effect, it rewinds the port after its scan is complete. After that,
1047 the port's character encoding should be set to the encoding returned
1048 by @code{file-encoding}, if any, again by using
1049 @code{set-port-encoding!}. Then the code can be read as normal.
1051 Alternatively, one can use the @code{#:guess-encoding} keyword argument
1052 of @code{open-file} and related procedures. @xref{File Ports}.
1054 @deffn {Scheme Procedure} file-encoding port
1055 @deffnx {C Function} scm_file_encoding (port)
1056 Attempt to scan the first few hundred bytes from the @var{port} for
1057 hints about its character encoding. Return a string containing the
1058 encoding name or @code{#f} if the encoding cannot be determined. The
1061 Currently, the only supported method is to look for an Emacs-like
1062 character coding declaration (@pxref{Recognize Coding, how Emacs
1063 recognizes file encoding,, emacs, The GNU Emacs Reference Manual}). The
1064 coding declaration is of the form @code{coding: XXXXX} and must appear
1065 in a Scheme comment. Additional heuristics may be added in the future.
1069 @node Delayed Evaluation
1070 @subsection Delayed Evaluation
1071 @cindex delayed evaluation
1074 Promises are a convenient way to defer a calculation until its result
1075 is actually needed, and to run such a calculation only once. Also
1078 @deffn syntax delay expr
1080 Return a promise object which holds the given @var{expr} expression,
1081 ready to be evaluated by a later @code{force}.
1084 @deffn {Scheme Procedure} promise? obj
1085 @deffnx {C Function} scm_promise_p (obj)
1086 Return true if @var{obj} is a promise.
1090 @deffn {Scheme Procedure} force p
1091 @deffnx {C Function} scm_force (p)
1092 Return the value obtained from evaluating the @var{expr} in the given
1093 promise @var{p}. If @var{p} has previously been forced then its
1094 @var{expr} is not evaluated again, instead the value obtained at that
1095 time is simply returned.
1097 During a @code{force}, an @var{expr} can call @code{force} again on
1098 its own promise, resulting in a recursive evaluation of that
1099 @var{expr}. The first evaluation to return gives the value for the
1100 promise. Higher evaluations run to completion in the normal way, but
1101 their results are ignored, @code{force} always returns the first
1106 @node Local Evaluation
1107 @subsection Local Evaluation
1109 Guile includes a facility to capture a lexical environment, and later
1110 evaluate a new expression within that environment. This code is
1111 implemented in a module.
1114 (use-modules (ice-9 local-eval))
1117 @deffn syntax the-environment
1118 Captures and returns a lexical environment for use with
1119 @code{local-eval} or @code{local-compile}.
1122 @deffn {Scheme Procedure} local-eval exp env
1123 @deffnx {C Function} scm_local_eval (exp, env)
1124 @deffnx {Scheme Procedure} local-compile exp env [opts=()]
1125 Evaluate or compile the expression @var{exp} in the lexical environment
1129 Here is a simple example, illustrating that it is the variable
1130 that gets captured, not just its value at one point in time.
1133 (define e (let ((x 100)) (the-environment)))
1134 (define fetch-x (local-eval '(lambda () x) e))
1137 (local-eval '(set! x 42) e)
1142 While @var{exp} is evaluated within the lexical environment of
1143 @code{(the-environment)}, it has the dynamic environment of the call to
1146 @code{local-eval} and @code{local-compile} can only evaluate
1147 expressions, not definitions.
1150 (local-eval '(define foo 42)
1151 (let ((x 100)) (the-environment)))
1152 @result{} syntax error: definition in expression context
1155 Note that the current implementation of @code{(the-environment)} only
1156 captures ``normal'' lexical bindings, and pattern variables bound by
1157 @code{syntax-case}. It does not currently capture local syntax
1158 transformers bound by @code{let-syntax}, @code{letrec-syntax} or
1159 non-top-level @code{define-syntax} forms. Any attempt to reference such
1160 captured syntactic keywords via @code{local-eval} or
1161 @code{local-compile} produces an error.
1164 @node Local Inclusion
1165 @subsection Local Inclusion
1167 This section has discussed various means of linking Scheme code
1168 together: fundamentally, loading up files at run-time using @code{load}
1169 and @code{load-compiled}. Guile provides another option to compose
1170 parts of programs together at expansion-time instead of at run-time.
1172 @deffn {Scheme Syntax} include file-name
1173 Open @var{file-name}, at expansion-time, and read the Scheme forms that
1174 it contains, splicing them into the location of the @code{include},
1175 within a @code{begin}.
1177 If @var{file-name} is a relative path, it is searched for relative to
1178 the path that contains the file that the @code{include} form appears in.
1181 If you are a C programmer, if @code{load} in Scheme is like
1182 @code{dlopen} in C, consider @code{include} to be like the C
1183 preprocessor's @code{#include}. When you use @code{include}, it is as
1184 if the contents of the included file were typed in instead of the
1185 @code{include} form.
1187 Because the code is included at compile-time, it is available to the
1188 macroexpander. Syntax definitions in the included file are available to
1189 later code in the form in which the @code{include} appears, without the
1190 need for @code{eval-when}. (@xref{Eval When}.)
1192 For the same reason, compiling a form that uses @code{include} results
1193 in one compilation unit, composed of multiple files. Loading the
1194 compiled file is one @code{stat} operation for the compilation unit,
1195 instead of @code{2*@var{n}} in the case of @code{load} (once for each
1196 loaded source file, and once each corresponding compiled file, in the
1199 Unlike @code{load}, @code{include} also works within nested lexical
1200 contexts. It so happens that the optimizer works best within a lexical
1201 context, because all of the uses of bindings in a lexical context are
1202 visible, so composing files by including them within a @code{(let ()
1203 ...)} can sometimes lead to important speed improvements.
1205 On the other hand, @code{include} does have all the disadvantages of
1206 early binding: once the code with the @code{include} is compiled, no
1207 change to the included file is reflected in the future behavior of the
1210 Also, the particular form of @code{include}, which requires an absolute
1211 path, or a path relative to the current directory at compile-time, is
1212 not very amenable to compiling the source in one place, but then
1213 installing the source to another place. For this reason, Guile provides
1214 another form, @code{include-from-path}, which looks for the source file
1215 to include within a load path.
1217 @deffn {Scheme Syntax} include-from-path file-name
1218 Like @code{include}, but instead of expecting @code{file-name} to be an
1219 absolute file name, it is expected to be a relative path to search in
1220 the @code{%load-path}.
1223 @code{include-from-path} is more useful when you want to install all of
1224 the source files for a package (as you should!). It makes it possible
1225 to evaluate an installed file from source, instead of relying on the
1226 @code{.go} file being up to date.
1229 @subsection REPL Servers
1233 The procedures in this section are provided by
1235 (use-modules (system repl server))
1238 When an application is written in Guile, it is often convenient to
1239 allow the user to be able to interact with it by evaluating Scheme
1240 expressions in a REPL.
1242 The procedures of this module allow you to spawn a @dfn{REPL server},
1243 which permits interaction over a local or TCP connection. Guile itself
1244 uses them internally to implement the @option{--listen} switch,
1245 @ref{Command-line Options}.
1247 @deffn {Scheme Procedure} make-tcp-server-socket [#:host=#f] @
1248 [#:addr] [#:port=37146]
1249 Return a stream socket bound to a given address @var{addr} and port
1250 number @var{port}. If the @var{host} is given, and @var{addr} is not,
1251 then the @var{host} string is converted to an address. If neither is
1252 given, we use the loopback address.
1255 @deffn {Scheme Procedure} make-unix-domain-server-socket [#:path="/tmp/guile-socket"]
1256 Return a UNIX domain socket, bound to a given @var{path}.
1259 @deffn {Scheme Procedure} run-server [server-socket]
1260 @deffnx {Scheme Procedure} spawn-server [server-socket]
1261 Create and run a REPL, making it available over the given
1262 @var{server-socket}. If @var{server-socket} is not provided, it
1263 defaults to the socket created by calling @code{make-tcp-server-socket}
1266 @code{run-server} runs the server in the current thread, whereas
1267 @code{spawn-server} runs the server in a new thread.
1270 @deffn {Scheme Procedure} stop-server-and-clients!
1271 Closes the connection on all running server sockets.
1273 Please note that in the current implementation, the REPL threads are
1274 cancelled without unwinding their stacks. If any of them are holding
1275 mutexes or are within a critical section, the results are unspecified.
1278 @node Cooperative REPL Servers
1279 @subsection Cooperative REPL Servers
1281 @cindex Cooperative REPL server
1283 The procedures in this section are provided by
1285 (use-modules (system repl coop-server))
1288 Whereas ordinary REPL servers run in their own threads (@pxref{REPL
1289 Servers}), sometimes it is more convenient to provide REPLs that run at
1290 specified times within an existing thread, for example in programs
1291 utilizing an event loop or in single-threaded programs. This allows for
1292 safe access and mutation of a program's data structures from the REPL,
1293 without concern for thread synchronization.
1295 Although the REPLs are run in the thread that calls
1296 @code{spawn-coop-repl-server} and @code{poll-coop-repl-server},
1297 dedicated threads are spawned so that the calling thread is not blocked.
1298 The spawned threads read input for the REPLs and to listen for new
1301 Cooperative REPL servers must be polled periodically to evaluate any
1302 pending expressions by calling @code{poll-coop-repl-server} with the
1303 object returned from @code{spawn-coop-repl-server}. The thread that
1304 calls @code{poll-coop-repl-server} will be blocked for as long as the
1305 expression takes to be evaluated or if the debugger is entered.
1307 @deffn {Scheme Procedure} spawn-coop-repl-server [server-socket]
1308 Create and return a new cooperative REPL server object, and spawn a new
1309 thread to listen for connections on @var{server-socket}. Proper
1310 functioning of the REPL server requires that
1311 @code{poll-coop-repl-server} be called periodically on the returned
1315 @deffn {Scheme Procedure} poll-coop-repl-server coop-server
1316 Poll the cooperative REPL server @var{coop-server} and apply a pending
1317 operation if there is one, such as evaluating an expression typed at the
1318 REPL prompt. This procedure must be called from the same thread that
1319 called @code{spawn-coop-repl-server}.
1323 @c TeX-master: "guile.texi"