2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2009, 2010, 2011, 2012
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
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.
27 @subsection Scheme Syntax: Standard and Guile Extensions
39 @node Expression Syntax
40 @subsubsection Expression Syntax
42 An expression to be evaluated takes one of the following forms.
47 A symbol is evaluated by dereferencing. A binding of that symbol is
48 sought and the value there used. For example,
55 @item (@var{proc} @var{args}@dots{})
56 A parenthesised expression is a function call. @var{proc} and each
57 argument are evaluated, then the function (which @var{proc} evaluated
58 to) is called with those arguments.
60 The order in which @var{proc} and the arguments are evaluated is
61 unspecified, so be careful when using expressions with side effects.
64 (max 1 2 3) @result{} 3
66 (define (get-some-proc) min)
67 ((get-some-proc) 1 2 3) @result{} 1
70 The same sort of parenthesised form is used for a macro invocation,
71 but in that case the arguments are not evaluated. See the
72 descriptions of macros for more on this (@pxref{Macros}, and
73 @pxref{Syntax Rules}).
76 Number, string, character and boolean constants evaluate ``to
77 themselves'', so can appear as literals.
82 "hello" @result{} "hello"
87 Note that an application must not attempt to modify literal strings,
88 since they may be in read-only memory.
90 @item (quote @var{data})
94 Quoting is used to obtain a literal symbol (instead of a variable
95 reference), a literal list (instead of a function call), or a literal
96 vector. @nicode{'} is simply a shorthand for a @code{quote} form.
101 '(1 2 3) @result{} (1 2 3)
102 '#(1 (2 3) 4) @result{} #(1 (2 3) 4)
103 (quote x) @result{} x
104 (quote (1 2 3)) @result{} (1 2 3)
105 (quote #(1 (2 3) 4)) @result{} #(1 (2 3) 4)
108 Note that an application must not attempt to modify literal lists or
109 vectors obtained from a @code{quote} form, since they may be in
112 @item (quasiquote @var{data})
116 Backquote quasi-quotation is like @code{quote}, but selected
117 sub-expressions are evaluated. This is a convenient way to construct
118 a list or vector structure most of which is constant, but at certain
119 points should have expressions substituted.
121 The same effect can always be had with suitable @code{list},
122 @code{cons} or @code{vector} calls, but quasi-quoting is often easier.
126 @item (unquote @var{expr})
130 Within the quasiquote @var{data}, @code{unquote} or @code{,} indicates
131 an expression to be evaluated and inserted. The comma syntax @code{,}
132 is simply a shorthand for an @code{unquote} form. For example,
135 `(1 2 ,(* 9 9) 3 4) @result{} (1 2 81 3 4)
136 `(1 (unquote (+ 1 1)) 3) @result{} (1 2 3)
137 `#(1 ,(/ 12 2)) @result{} #(1 6)
140 @item (unquote-splicing @var{expr})
142 @findex unquote-splicing
144 Within the quasiquote @var{data}, @code{unquote-splicing} or
145 @code{,@@} indicates an expression to be evaluated and the elements of
146 the returned list inserted. @var{expr} must evaluate to a list. The
147 ``comma-at'' syntax @code{,@@} is simply a shorthand for an
148 @code{unquote-splicing} form.
152 `(1 ,@@x 4) @result{} (1 2 3 4)
153 `(1 (unquote-splicing (map 1+ x))) @result{} (1 3 4)
154 `#(9 ,@@x 9) @result{} #(9 2 3 9)
157 Notice @code{,@@} differs from plain @code{,} in the way one level of
158 nesting is stripped. For @code{,@@} the elements of a returned list
159 are inserted, whereas with @code{,} it would be the list itself
164 @c FIXME: What can we say about the mutability of a quasiquote
165 @c result? R5RS doesn't seem to specify anything, though where it
166 @c says backquote without commas is the same as plain quote then
167 @c presumably the "fixed" portions of a quasiquote expression must be
168 @c treated as immutable.
175 @subsubsection Comments
177 @c FIXME::martin: Review me!
179 Comments in Scheme source files are written by starting them with a
180 semicolon character (@code{;}). The comment then reaches up to the end
181 of the line. Comments can begin at any column, and the may be inserted
182 on the same line as Scheme code.
187 (define x 1) ; Comment after expression
189 ;; Display something.
191 ;;; Comment at left margin.
195 It is common to use a single semicolon for comments following
196 expressions on a line, to use two semicolons for comments which are
197 indented like code, and three semicolons for comments which start at
198 column 0, even if they are inside an indented code block. This
199 convention is used when indenting code in Emacs' Scheme mode.
203 @subsubsection Block Comments
204 @cindex multiline comments
205 @cindex block comments
209 @c FIXME::martin: Review me!
211 In addition to the standard line comments defined by R5RS, Guile has
212 another comment type for multiline comments, called @dfn{block
213 comments}. This type of comment begins with the character sequence
214 @code{#!} and ends with the characters @code{!#}, which must appear on a
215 line of their own. These comments are compatible with the block
216 comments in the Scheme Shell @file{scsh} (@pxref{The Scheme shell
217 (scsh)}). The characters @code{#!} were chosen because they are the
218 magic characters used in shell scripts for indicating that the name of
219 the program for executing the script follows on the same line.
221 Thus a Guile script often starts like this.
224 #! /usr/local/bin/guile -s
228 More details on Guile scripting can be found in the scripting section
229 (@pxref{Guile Scripting}).
231 @cindex R6RS block comments
232 @cindex SRFI-30 block comments
233 Similarly, Guile (starting from version 2.0) supports nested block
234 comments as specified by R6RS and
235 @url{http://srfi.schemers.org/srfi-30/srfi-30.html, SRFI-30}:
238 (+ #| this is a #| nested |# block comment |# 2)
242 For backward compatibility, this syntax can be overridden with
243 @code{read-hash-extend} (@pxref{Reader Extensions,
244 @code{read-hash-extend}}).
246 There is one special case where the contents of a comment can actually
247 affect the interpretation of code. When a character encoding
248 declaration, such as @code{coding: utf-8} appears in one of the first
249 few lines of a source file, it indicates to Guile's default reader
250 that this source code file is not ASCII. For details see @ref{Character
251 Encoding of Source Files}.
253 @node Case Sensitivity
254 @subsubsection Case Sensitivity
256 @c FIXME::martin: Review me!
258 Scheme as defined in R5RS is not case sensitive when reading symbols.
259 Guile, on the contrary is case sensitive by default, so the identifiers
266 are the same in R5RS Scheme, but are different in Guile.
268 It is possible to turn off case sensitivity in Guile by setting the
269 reader option @code{case-insensitive}. For more information on reader
270 options, @xref{Scheme Read}.
273 (read-enable 'case-insensitive)
276 Note that this is seldom a problem, because Scheme programmers tend not
277 to use uppercase letters in their identifiers anyway.
281 @subsubsection Keyword Syntax
284 @node Reader Extensions
285 @subsubsection Reader Extensions
287 @deffn {Scheme Procedure} read-hash-extend chr proc
288 @deffnx {C Function} scm_read_hash_extend (chr, proc)
289 Install the procedure @var{proc} for reading expressions
290 starting with the character sequence @code{#} and @var{chr}.
291 @var{proc} will be called with two arguments: the character
292 @var{chr} and the port to read further data from. The object
293 returned will be the return value of @code{read}.
294 Passing @code{#f} for @var{proc} will remove a previous setting.
300 @subsection Reading Scheme Code
303 @deffn {Scheme Procedure} read [port]
304 @deffnx {C Function} scm_read (port)
305 Read an s-expression from the input port @var{port}, or from
306 the current input port if @var{port} is not specified.
307 Any whitespace before the next token is discarded.
310 The behaviour of Guile's Scheme reader can be modified by manipulating
313 @cindex options - read
315 @deffn {Scheme Procedure} read-options [setting]
316 Display the current settings of the read options. If @var{setting} is
317 omitted, only a short form of the current read options is printed.
318 Otherwise if @var{setting} is the symbol @code{help}, a complete options
319 description is displayed.
322 The set of available options, and their default values, may be had by
323 invoking @code{read-options} at the prompt.
326 scheme@@(guile-user)> (read-options)
327 (square-brackets keywords #f positions)
328 scheme@@(guile-user)> (read-options 'help)
329 copy no Copy source code expressions.
330 positions yes Record positions of source code expressions.
331 case-insensitive no Convert symbols to lower case.
332 keywords #f Style of keyword recognition: #f, 'prefix or 'postfix.
333 r6rs-hex-escapes no Use R6RS variable-length character and string hex escapes.
334 square-brackets yes Treat `[' and `]' as parentheses, for R6RS compatibility.
335 hungry-eol-escapes no In strings, consume leading whitespace after an
339 The boolean options may be toggled with @code{read-enable} and
340 @code{read-disable}. The non-boolean @code{keywords} option must be set
341 using @code{read-set!}.
343 @deffn {Scheme Procedure} read-enable option-name
344 @deffnx {Scheme Procedure} read-disable option-name
345 @deffnx {Scheme Syntax} read-set! option-name value
346 Modify the read options. @code{read-enable} should be used with boolean
347 options and switches them on, @code{read-disable} switches them off.
349 @code{read-set!} can be used to set an option to a specific value. Due
350 to historical oddities, it is a macro that expects an unquoted option
354 For example, to make @code{read} fold all symbols to their lower case
355 (perhaps for compatibility with older Scheme code), you can enter:
358 (read-enable 'case-insensitive)
361 For more information on the effect of the @code{r6rs-hex-escapes} and
362 @code{hungry-eol-escapes} options, see (@pxref{String Syntax}).
366 @subsection Writing Scheme Values
368 Any scheme value may be written to a port. Not all values may be read
369 back in (@pxref{Scheme Read}), however.
373 @deffn {Scheme Procedure} write obj [port]
374 Send a representation of @var{obj} to @var{port} or to the current
375 output port if not given.
377 The output is designed to be machine readable, and can be read back
378 with @code{read} (@pxref{Scheme Read}). Strings are printed in
379 double quotes, with escapes if necessary, and characters are printed in
384 @deffn {Scheme Procedure} display obj [port]
385 Send a representation of @var{obj} to @var{port} or to the current
386 output port if not given.
388 The output is designed for human readability, it differs from
389 @code{write} in that strings are printed without double quotes and
390 escapes, and characters are printed as per @code{write-char}, not in
394 As was the case with the Scheme reader, there are a few options that
395 affect the behavior of the Scheme printer.
397 @cindex options - print
398 @cindex print options
399 @deffn {Scheme Procedure} print-options [setting]
400 Display the current settings of the read options. If @var{setting} is
401 omitted, only a short form of the current read options is
402 printed. Otherwise if @var{setting} is the symbol @code{help}, a
403 complete options description is displayed.
406 The set of available options, and their default values, may be had by
407 invoking @code{print-options} at the prompt.
410 scheme@@(guile-user)> (print-options)
411 (quote-keywordish-symbols reader highlight-suffix "@}" highlight-prefix "@{")
412 scheme@@(guile-user)> (print-options 'help)
413 highlight-prefix @{ The string to print before highlighted values.
414 highlight-suffix @} The string to print after highlighted values.
415 quote-keywordish-symbols reader How to print symbols that have a colon
416 as their first or last character. The
417 value '#f' does not quote the colons;
418 '#t' quotes them; 'reader' quotes them
419 when the reader option 'keywords' is
421 escape-newlines yes Render newlines as \n when printing
425 These options may be modified with the print-set! syntax.
427 @deffn {Scheme Syntax} print-set! option-name value
428 Modify the print options. Due to historical oddities, @code{print-set!}
429 is a macro that expects an unquoted option name.
434 @subsection Procedures for On the Fly Evaluation
436 Scheme has the lovely property that its expressions may be represented
437 as data. The @code{eval} procedure takes a Scheme datum and evaluates
441 @c ARGFIXME environment/environment specifier
442 @deffn {Scheme Procedure} eval exp module_or_state
443 @deffnx {C Function} scm_eval (exp, module_or_state)
444 Evaluate @var{exp}, a list representing a Scheme expression,
445 in the top-level environment specified by @var{module}.
446 While @var{exp} is evaluated (using @code{primitive-eval}),
447 @var{module} is made the current module. The current module
448 is reset to its previous value when @var{eval} returns.
449 XXX - dynamic states.
450 Example: (eval '(+ 1 2) (interaction-environment))
453 @rnindex interaction-environment
454 @deffn {Scheme Procedure} interaction-environment
455 @deffnx {C Function} scm_interaction_environment ()
456 Return a specifier for the environment that contains
457 implementation--defined bindings, typically a superset of those
458 listed in the report. The intent is that this procedure will
459 return the environment in which the implementation would
460 evaluate expressions dynamically typed by the user.
463 @xref{Environments}, for other environments.
465 One does not always receive code as Scheme data, of course, and this is
466 especially the case for Guile's other language implementations
467 (@pxref{Other Languages}). For the case in which all you have is a
468 string, we have @code{eval-string}. There is a legacy version of this
469 procedure in the default environment, but you really want the one from
470 @code{(ice-9 eval-string)}, so load it up:
473 (use-modules (ice-9 eval-string))
476 @deffn {Scheme Procedure} eval-string string [module=#f] [file=#f] [line=#f] [column=#f] [lang=(current-language)] [compile?=#f]
477 Parse @var{string} according to the current language, normally Scheme.
478 Evaluate or compile the expressions it contains, in order, returning the
481 If the @var{module} keyword argument is set, save a module excursion
482 (@pxref{Module System Reflection}) and set the current module to
483 @var{module} before evaluation.
485 The @var{file}, @var{line}, and @var{column} keyword arguments can be
486 used to indicate that the source string begins at a particular source
489 Finally, @var{lang} is a language, defaulting to the current language,
490 and the expression is compiled if @var{compile?} is true or there is no
491 evaluator for the given language.
494 @deffn {C Function} scm_eval_string (string)
495 @deffnx {C Function} scm_eval_string_in_module (string, module)
496 These C bindings call @code{eval-string} from @code{(ice-9
497 eval-string)}, evaluating within @var{module} or the current module.
500 @deftypefn {C Function} SCM scm_c_eval_string (const char *string)
501 @code{scm_eval_string}, but taking a C string in locale encoding instead
505 @deffn {Scheme Procedure} apply proc arg1 @dots{} argN arglst
506 @deffnx {C Function} scm_apply_0 (proc, arglst)
507 @deffnx {C Function} scm_apply_1 (proc, arg1, arglst)
508 @deffnx {C Function} scm_apply_2 (proc, arg1, arg2, arglst)
509 @deffnx {C Function} scm_apply_3 (proc, arg1, arg2, arg3, arglst)
510 @deffnx {C Function} scm_apply (proc, arg, rest)
512 Call @var{proc} with arguments @var{arg1} @dots{} @var{argN} plus the
513 elements of the @var{arglst} list.
515 @code{scm_apply} takes parameters corresponding to a Scheme level
516 @code{(lambda (proc arg . rest) ...)}. So @var{arg} and all but the
517 last element of the @var{rest} list make up
518 @var{arg1}@dots{}@var{argN} and the last element of @var{rest} is the
519 @var{arglst} list. Or if @var{rest} is the empty list @code{SCM_EOL}
520 then there's no @var{arg1}@dots{}@var{argN} and @var{arg} is the
523 @var{arglst} is not modified, but the @var{rest} list passed to
524 @code{scm_apply} is modified.
527 @deffn {C Function} scm_call_0 (proc)
528 @deffnx {C Function} scm_call_1 (proc, arg1)
529 @deffnx {C Function} scm_call_2 (proc, arg1, arg2)
530 @deffnx {C Function} scm_call_3 (proc, arg1, arg2, arg3)
531 @deffnx {C Function} scm_call_4 (proc, arg1, arg2, arg3, arg4)
532 @deffnx {C Function} scm_call_5 (proc, arg1, arg2, arg3, arg4, arg5)
533 @deffnx {C Function} scm_call_6 (proc, arg1, arg2, arg3, arg4, arg5, arg6)
534 Call @var{proc} with the given arguments.
537 @deffn {C Function} scm_call_n (proc, argv, nargs)
538 Call @var{proc} with the array of arguments @var{argv}, as a
539 @code{SCM*}. The length of the arguments should be passed in
540 @var{nargs}, as a @code{size_t}.
543 @deffn {Scheme Procedure} apply:nconc2last lst
544 @deffnx {C Function} scm_nconc2last (lst)
545 @var{lst} should be a list (@var{arg1} @dots{} @var{argN}
546 @var{arglst}), with @var{arglst} being a list. This function returns
547 a list comprising @var{arg1} to @var{argN} plus the elements of
548 @var{arglst}. @var{lst} is modified to form the return. @var{arglst}
549 is not modified, though the return does share structure with it.
551 This operation collects up the arguments from a list which is
552 @code{apply} style parameters.
555 @deffn {Scheme Procedure} primitive-eval exp
556 @deffnx {C Function} scm_primitive_eval (exp)
557 Evaluate @var{exp} in the top-level environment specified by
563 @subsection Compiling Scheme Code
565 The @code{eval} procedure directly interprets the S-expression
566 representation of Scheme. An alternate strategy for evaluation is to
567 determine ahead of time what computations will be necessary to
568 evaluate the expression, and then use that recipe to produce the
569 desired results. This is known as @dfn{compilation}.
571 While it is possible to compile simple Scheme expressions such as
572 @code{(+ 2 2)} or even @code{"Hello world!"}, compilation is most
573 interesting in the context of procedures. Compiling a lambda expression
574 produces a compiled procedure, which is just like a normal procedure
575 except typically much faster, because it can bypass the generic
578 Functions from system modules in a Guile installation are normally
579 compiled already, so they load and run quickly.
581 @cindex automatic compilation
582 Note that well-written Scheme programs will not typically call the
583 procedures in this section, for the same reason that it is often bad
584 taste to use @code{eval}. By default, Guile automatically compiles any
585 files it encounters that have not been compiled yet (@pxref{Invoking
586 Guile, @code{--auto-compile}}). The compiler can also be invoked
587 explicitly from the shell as @code{guild compile foo.scm}.
589 (Why are calls to @code{eval} and @code{compile} usually in bad taste?
590 Because they are limited, in that they can only really make sense for
591 top-level expressions. Also, most needs for ``compile-time''
592 computation are fulfilled by macros and closures. Of course one good
593 counterexample is the REPL itself, or any code that reads expressions
596 Automatic compilation generally works transparently, without any need
597 for user intervention. However Guile does not yet do proper dependency
598 tracking, so that if file @file{@var{a}.scm} uses macros from
599 @file{@var{b}.scm}, and @var{@var{b}.scm} changes, @code{@var{a}.scm}
600 would not be automatically recompiled. To forcibly invalidate the
601 auto-compilation cache, pass the @code{--fresh-auto-compile} option to
602 Guile, or set the @code{GUILE_AUTO_COMPILE} environment variable to
603 @code{fresh} (instead of to @code{0} or @code{1}).
605 For more information on the compiler itself, see @ref{Compiling to the
606 Virtual Machine}. For information on the virtual machine, see @ref{A
607 Virtual Machine for Guile}.
609 The command-line interface to Guile's compiler is the @command{guild
612 @deffn {Command} {guild compile} [@option{option}...] @var{file}...
613 Compile @var{file}, a source file, and store bytecode in the compilation cache
614 or in the file specified by the @option{-o} option. The following options are
620 @itemx --load-path=@var{dir}
621 Add @var{dir} to the front of the module load path.
624 @itemx --output=@var{ofile}
625 Write output bytecode to @var{ofile}. By convention, bytecode file
626 names end in @code{.go}. When @option{-o} is omitted, the output file
627 name is as for @code{compile-file} (see below).
629 @item -W @var{warning}
630 @itemx --warn=@var{warning}
631 Emit warnings of type @var{warning}; use @code{--warn=help} for a list
632 of available warnings and their description. Currently recognized
633 warnings include @code{unused-variable}, @code{unused-toplevel},
634 @code{unbound-variable}, @code{arity-mismatch}, and @code{format}.
637 @itemx --from=@var{lang}
638 Use @var{lang} as the source language of @var{file}. If this option is omitted,
639 @code{scheme} is assumed.
642 @itemx --to=@var{lang}
643 Use @var{lang} as the target language of @var{file}. If this option is omitted,
644 @code{objcode} is assumed.
646 @item -T @var{target}
647 @itemx --target=@var{target}
648 Produce bytecode for @var{target} instead of @var{%host-type}
649 (@pxref{Build Config, %host-type}). Target must be a valid GNU triplet,
650 such as @code{armv5tel-unknown-linux-gnueabi} (@pxref{Specifying Target
651 Triplets,,, autoconf, GNU Autoconf Manual}).
655 Each @var{file} is assumed to be UTF-8-encoded, unless it contains a
656 coding declaration as recognized by @code{file-encoding}
657 (@pxref{Character Encoding of Source Files}).
660 The compiler can also be invoked directly by Scheme code using the procedures
663 @deffn {Scheme Procedure} compile exp [env=#f] [from=(current-language)] [to=value] [opts=()]
664 Compile the expression @var{exp} in the environment @var{env}. If
665 @var{exp} is a procedure, the result will be a compiled procedure;
666 otherwise @code{compile} is mostly equivalent to @code{eval}.
668 For a discussion of languages and compiler options, @xref{Compiling to
669 the Virtual Machine}.
672 @deffn {Scheme Procedure} compile-file file [output-file=#f] @
673 [from=(current-language)] [to='objcode] @
674 [env=(default-environment from)] [opts='()] @
675 [canonicalization 'relative]
676 Compile the file named @var{file}.
678 Output will be written to a @var{output-file}. If you do not supply an
679 output file name, output is written to a file in the cache directory, as
680 computed by @code{(compiled-file-name @var{file})}.
682 @var{from} and @var{to} specify the source and target languages.
683 @xref{Compiling to the Virtual Machine}, for more information on these
684 options, and on @var{env} and @var{opts}.
686 As with @command{guild compile}, @var{file} is assumed to be
687 UTF-8-encoded unless it contains a coding declaration.
690 @deffn {Scheme Procedure} compiled-file-name file
691 Compute a cached location for a compiled version of a Scheme file named
694 This file will usually be below the @file{$HOME/.cache/guile/ccache}
695 directory, depending on the value of the @env{XDG_CACHE_HOME}
696 environment variable. The intention is that @code{compiled-file-name}
697 provides a fallback location for caching auto-compiled files. If you
698 want to place a compile file in the @code{%load-compiled-path}, you
699 should pass the @var{output-file} option to @code{compile-file},
703 @defvr {Scheme Variable} %auto-compilation-options
704 This variable contains the options passed to the @code{compile-file}
705 procedure when auto-compiling source files. By default, it enables
706 useful compilation warnings. It can be customized from @file{~/.guile}.
710 @subsection Loading Scheme Code from File
713 @deffn {Scheme Procedure} load filename [reader]
714 Load @var{filename} and evaluate its contents in the top-level
717 @var{reader} if provided should be either @code{#f}, or a procedure with
718 the signature @code{(lambda (port) @dots{})} which reads the next
719 expression from @var{port}. If @var{reader} is @code{#f} or absent,
720 Guile's built-in @code{read} procedure is used (@pxref{Scheme Read}).
722 The @var{reader} argument takes effect by setting the value of the
723 @code{current-reader} fluid (see below) before loading the file, and
724 restoring its previous value when loading is complete. The Scheme code
725 inside @var{filename} can itself change the current reader procedure on
726 the fly by setting @code{current-reader} fluid.
728 If the variable @code{%load-hook} is defined, it should be bound to a
729 procedure that will be called before any code is loaded. See
730 documentation for @code{%load-hook} later in this section.
733 @deffn {Scheme Procedure} load-compiled filename
734 Load the compiled file named @var{filename}.
736 Compiling a source file (@pxref{Read/Load/Eval/Compile}) and then
737 calling @code{load-compiled} on the resulting file is equivalent to
738 calling @code{load} on the source file.
741 @deffn {Scheme Procedure} primitive-load filename
742 @deffnx {C Function} scm_primitive_load (filename)
743 Load the file named @var{filename} and evaluate its contents in the
744 top-level environment. @var{filename} must either be a full pathname or
745 be a pathname relative to the current directory. If the variable
746 @code{%load-hook} is defined, it should be bound to a procedure that
747 will be called before any code is loaded. See the documentation for
748 @code{%load-hook} later in this section.
751 @deftypefn {C Function} SCM scm_c_primitive_load (const char *filename)
752 @code{scm_primitive_load}, but taking a C string instead of an
756 @defvar current-reader
757 @code{current-reader} holds the read procedure that is currently being
758 used by the above loading procedures to read expressions (from the file
759 that they are loading). @code{current-reader} is a fluid, so it has an
760 independent value in each dynamic root and should be read and set using
761 @code{fluid-ref} and @code{fluid-set!} (@pxref{Fluids and Dynamic
764 Changing @code{current-reader} is typically useful to introduce local
765 syntactic changes, such that code following the @code{fluid-set!} call
766 is read using the newly installed reader. The @code{current-reader}
767 change should take place at evaluation time when the code is evaluated,
768 or at compilation time when the code is compiled:
772 (eval-when (compile eval)
773 (fluid-set! current-reader my-own-reader))
776 The @code{eval-when} form above ensures that the @code{current-reader}
777 change occurs at the right time.
781 A procedure to be called @code{(%load-hook @var{filename})} whenever a
782 file is loaded, or @code{#f} for no such call. @code{%load-hook} is
783 used by all of the loading functions (@code{load} and
784 @code{primitive-load}, and @code{load-from-path} and
785 @code{primitive-load-path} documented in the next section).
787 For example an application can set this to show what's loaded,
790 (set! %load-hook (lambda (filename)
791 (format #t "Loading ~a ...\n" filename)))
792 (load-from-path "foo.scm")
793 @print{} Loading /usr/local/share/guile/site/foo.scm ...
797 @deffn {Scheme Procedure} current-load-port
798 @deffnx {C Function} scm_current_load_port ()
799 Return the current-load-port.
800 The load port is used internally by @code{primitive-load}.
804 @subsection Load Paths
806 The procedure in the previous section look for Scheme code in the file
807 system at specific location. Guile also has some procedures to search
808 the load path for code.
810 For more on the @code{%load-path} variable, @xref{Build Config}.
812 @deffn {Scheme Procedure} load-from-path filename
813 Similar to @code{load}, but searches for @var{filename} in the load
814 paths. Preferentially loads a compiled version of the file, if it is
815 available and up-to-date.
818 A user can extend the load path by calling @code{add-to-load-path}.
820 @deffn {Scheme Syntax} add-to-load-path dir
821 Add @var{dir} to the load path.
823 For example, a script might include this form to add the directory that
824 it is in to the load path:
827 (add-to-load-path (dirname (current-filename)))
831 It's better to use @code{add-to-load-path} than to modify
832 @code{%load-path} directly, because @code{add-to-load-path} takes care
833 of modifying the path both at compile-time and at run-time.
835 @deffn {Scheme Procedure} primitive-load-path filename [exception-on-not-found]
836 @deffnx {C Function} scm_primitive_load_path (filename)
837 Search @code{%load-path} for the file named @var{filename} and
838 load it into the top-level environment. If @var{filename} is a
839 relative pathname and is not found in the list of search paths,
840 an error is signalled. Preferentially loads a compiled version of the
841 file, if it is available and up-to-date.
843 By default or if @var{exception-on-not-found} is true, an exception is
844 raised if @var{filename} is not found. If @var{exception-on-not-found}
845 is @code{#f} and @var{filename} is not found, no exception is raised and
846 @code{#f} is returned. For compatibility with Guile 1.8 and earlier,
847 the C function takes only one argument, which can be either a string
848 (the file name) or an argument list.
851 @deffn {Scheme Procedure} %search-load-path filename
852 @deffnx {C Function} scm_sys_search_load_path (filename)
853 Search @code{%load-path} for the file named @var{filename},
854 which must be readable by the current user. If @var{filename}
855 is found in the list of paths to search or is an absolute
856 pathname, return its full pathname. Otherwise, return
857 @code{#f}. Filenames may have any of the optional extensions
858 in the @code{%load-extensions} list; @code{%search-load-path}
859 will try each extension automatically.
862 @defvar %load-extensions
863 A list of default file extensions for files containing Scheme code.
864 @code{%search-load-path} tries each of these extensions when looking for
865 a file to load. By default, @code{%load-extensions} is bound to the
866 list @code{("" ".scm")}.
870 @node Character Encoding of Source Files
871 @subsection Character Encoding of Source Files
873 @cindex source file encoding
874 @cindex primitive-load
876 Scheme source code files are usually encoded in ASCII, but, the
877 built-in reader can interpret other character encodings. The
878 procedure @code{primitive-load}, and by extension the functions that
879 call it, such as @code{load}, first scan the top 500 characters of the
880 file for a coding declaration.
882 A coding declaration has the form @code{coding: XXXXXX}, where
883 @code{XXXXXX} is the name of a character encoding in which the source
884 code file has been encoded. The coding declaration must appear in a
885 scheme comment. It can either be a semicolon-initiated comment or a block
888 The name of the character encoding in the coding declaration is
889 typically lower case and containing only letters, numbers, and hyphens,
890 as recognized by @code{set-port-encoding!} (@pxref{Ports,
891 @code{set-port-encoding!}}). Common examples of character encoding
892 names are @code{utf-8} and @code{iso-8859-1},
893 @url{http://www.iana.org/assignments/character-sets, as defined by
894 IANA}. Thus, the coding declaration is mostly compatible with Emacs.
896 However, there are some differences in encoding names recognized by
897 Emacs and encoding names defined by IANA, the latter being essentially a
898 subset of the former. For instance, @code{latin-1} is a valid encoding
899 name for Emacs, but it's not according to the IANA standard, which Guile
900 follows; instead, you should use @code{iso-8859-1}, which is both
901 understood by Emacs and dubbed by IANA (IANA writes it uppercase but
902 Emacs wants it lowercase and Guile is case insensitive.)
904 For source code, only a subset of all possible character encodings can
905 be interpreted by the built-in source code reader. Only those
906 character encodings in which ASCII text appears unmodified can be
907 used. This includes @code{UTF-8} and @code{ISO-8859-1} through
908 @code{ISO-8859-15}. The multi-byte character encodings @code{UTF-16}
909 and @code{UTF-32} may not be used because they are not compatible with
914 @cindex port encoding
915 @findex set-port-encoding!
916 There might be a scenario in which one would want to read non-ASCII
917 code from a port, such as with the function @code{read}, instead of
918 with @code{load}. If the port's character encoding is the same as the
919 encoding of the code to be read by the port, not other special
920 handling is necessary. The port will automatically do the character
921 encoding conversion. The functions @code{setlocale} or by
922 @code{set-port-encoding!} are used to set port encodings
925 If a port is used to read code of unknown character encoding, it can
926 accomplish this in three steps. First, the character encoding of the
927 port should be set to ISO-8859-1 using @code{set-port-encoding!}.
928 Then, the procedure @code{file-encoding}, described below, is used to
929 scan for a coding declaration when reading from the port. As a side
930 effect, it rewinds the port after its scan is complete. After that,
931 the port's character encoding should be set to the encoding returned
932 by @code{file-encoding}, if any, again by using
933 @code{set-port-encoding!}. Then the code can be read as normal.
935 @deffn {Scheme Procedure} file-encoding port
936 @deffnx {C Function} scm_file_encoding port
937 Scan the port for an Emacs-like character coding declaration near the
938 top of the contents of a port with random-accessible contents
939 (@pxref{Recognize Coding, how Emacs recognizes file encoding,, emacs,
940 The GNU Emacs Reference Manual}). The coding declaration is of the form
941 @code{coding: XXXXX} and must appear in a Scheme comment. Return a
942 string containing the character encoding of the file if a declaration
943 was found, or @code{#f} otherwise. The port is rewound.
947 @node Delayed Evaluation
948 @subsection Delayed Evaluation
949 @cindex delayed evaluation
952 Promises are a convenient way to defer a calculation until its result
953 is actually needed, and to run such a calculation only once.
955 @deffn syntax delay expr
957 Return a promise object which holds the given @var{expr} expression,
958 ready to be evaluated by a later @code{force}.
961 @deffn {Scheme Procedure} promise? obj
962 @deffnx {C Function} scm_promise_p (obj)
963 Return true if @var{obj} is a promise.
967 @deffn {Scheme Procedure} force p
968 @deffnx {C Function} scm_force (p)
969 Return the value obtained from evaluating the @var{expr} in the given
970 promise @var{p}. If @var{p} has previously been forced then its
971 @var{expr} is not evaluated again, instead the value obtained at that
972 time is simply returned.
974 During a @code{force}, an @var{expr} can call @code{force} again on
975 its own promise, resulting in a recursive evaluation of that
976 @var{expr}. The first evaluation to return gives the value for the
977 promise. Higher evaluations run to completion in the normal way, but
978 their results are ignored, @code{force} always returns the first
984 @c TeX-master: "guile.texi"