elisp @@ macro
[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.
dc59631d
MW
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.
07d83abe
MV
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.
10d278fd 25* REPL Servers:: Serving a REPL over a socket.
b0a31499 26* Cooperative REPL Servers:: REPL server for single-threaded applications.
07d83abe
MV
27@end menu
28
29
30@node Scheme Syntax
31@subsection Scheme Syntax: Standard and Guile Extensions
32
33@menu
34* Expression Syntax::
35* Comments::
36* Block Comments::
37* Case Sensitivity::
38* Keyword Syntax::
39* Reader Extensions::
40@end menu
41
42
43@node Expression Syntax
44@subsubsection Expression Syntax
45
46An expression to be evaluated takes one of the following forms.
47
48@table @nicode
49
50@item @var{symbol}
51A symbol is evaluated by dereferencing. A binding of that symbol is
52sought and the value there used. For example,
53
54@example
55(define x 123)
56x @result{} 123
57@end example
58
59@item (@var{proc} @var{args}@dots{})
60A parenthesised expression is a function call. @var{proc} and each
61argument are evaluated, then the function (which @var{proc} evaluated
62to) is called with those arguments.
63
64The order in which @var{proc} and the arguments are evaluated is
65unspecified, so be careful when using expressions with side effects.
66
67@example
68(max 1 2 3) @result{} 3
69
70(define (get-some-proc) min)
71((get-some-proc) 1 2 3) @result{} 1
72@end example
73
74The same sort of parenthesised form is used for a macro invocation,
75but in that case the arguments are not evaluated. See the
76descriptions of macros for more on this (@pxref{Macros}, and
77@pxref{Syntax Rules}).
78
79@item @var{constant}
80Number, string, character and boolean constants evaluate ``to
81themselves'', so can appear as literals.
82
83@example
84123 @result{} 123
8599.9 @result{} 99.9
86"hello" @result{} "hello"
87#\z @result{} #\z
88#t @result{} #t
89@end example
90
91Note that an application must not attempt to modify literal strings,
92since they may be in read-only memory.
93
94@item (quote @var{data})
95@itemx '@var{data}
96@findex quote
97@findex '
98Quoting is used to obtain a literal symbol (instead of a variable
99reference), a literal list (instead of a function call), or a literal
100vector. @nicode{'} is simply a shorthand for a @code{quote} form.
101For example,
102
103@example
104'x @result{} x
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)
110@end example
111
112Note that an application must not attempt to modify literal lists or
113vectors obtained from a @code{quote} form, since they may be in
114read-only memory.
115
116@item (quasiquote @var{data})
117@itemx `@var{data}
118@findex quasiquote
119@findex `
120Backquote quasi-quotation is like @code{quote}, but selected
121sub-expressions are evaluated. This is a convenient way to construct
122a list or vector structure most of which is constant, but at certain
123points should have expressions substituted.
124
125The same effect can always be had with suitable @code{list},
126@code{cons} or @code{vector} calls, but quasi-quoting is often easier.
127
128@table @nicode
129
130@item (unquote @var{expr})
131@itemx ,@var{expr}
132@findex unquote
133@findex ,
134Within the quasiquote @var{data}, @code{unquote} or @code{,} indicates
135an expression to be evaluated and inserted. The comma syntax @code{,}
136is simply a shorthand for an @code{unquote} form. For example,
137
138@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)
142@end example
143
144@item (unquote-splicing @var{expr})
145@itemx ,@@@var{expr}
146@findex unquote-splicing
147@findex ,@@
148Within the quasiquote @var{data}, @code{unquote-splicing} or
149@code{,@@} indicates an expression to be evaluated and the elements of
150the 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.
153
154@example
155(define x '(2 3))
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)
159@end example
160
161Notice @code{,@@} differs from plain @code{,} in the way one level of
162nesting is stripped. For @code{,@@} the elements of a returned list
163are inserted, whereas with @code{,} it would be the list itself
164inserted.
165@end table
166
167@c
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.
173@c
174
175@end table
176
177
178@node Comments
179@subsubsection Comments
180
181@c FIXME::martin: Review me!
182
183Comments in Scheme source files are written by starting them with a
184semicolon character (@code{;}). The comment then reaches up to the end
185of the line. Comments can begin at any column, and the may be inserted
186on the same line as Scheme code.
187
188@lisp
189; Comment
190;; Comment too
191(define x 1) ; Comment after expression
192(let ((y 1))
193 ;; Display something.
194 (display y)
195;;; Comment at left margin.
196 (display (+ y 1)))
197@end lisp
198
199It is common to use a single semicolon for comments following
200expressions on a line, to use two semicolons for comments which are
201indented like code, and three semicolons for comments which start at
202column 0, even if they are inside an indented code block. This
203convention is used when indenting code in Emacs' Scheme mode.
204
205
206@node Block Comments
207@subsubsection Block Comments
456f797b
KR
208@cindex multiline comments
209@cindex block comments
210@cindex #!
211@cindex !#
07d83abe
MV
212
213@c FIXME::martin: Review me!
214
07d83abe
MV
215In addition to the standard line comments defined by R5RS, Guile has
216another comment type for multiline comments, called @dfn{block
217comments}. This type of comment begins with the character sequence
1e9249e0
LC
218@code{#!} and ends with the characters @code{!#}.
219
220These comments are compatible with the block
07d83abe
MV
221comments in the Scheme Shell @file{scsh} (@pxref{The Scheme shell
222(scsh)}). The characters @code{#!} were chosen because they are the
223magic characters used in shell scripts for indicating that the name of
224the program for executing the script follows on the same line.
225
226Thus a Guile script often starts like this.
227
228@lisp
229#! /usr/local/bin/guile -s
230!#
231@end lisp
232
233More details on Guile scripting can be found in the scripting section
234(@pxref{Guile Scripting}).
235
620c8965
LC
236@cindex R6RS block comments
237@cindex SRFI-30 block comments
238Similarly, Guile (starting from version 2.0) supports nested block
239comments as specified by R6RS and
240@url{http://srfi.schemers.org/srfi-30/srfi-30.html, SRFI-30}:
241
242@lisp
a5cbbaa6 243(+ 1 #| this is a #| nested |# block comment |# 2)
620c8965
LC
244@result{} 3
245@end lisp
246
247For backward compatibility, this syntax can be overridden with
248@code{read-hash-extend} (@pxref{Reader Extensions,
249@code{read-hash-extend}}).
250
8748ffea
MG
251There is one special case where the contents of a comment can actually
252affect the interpretation of code. When a character encoding
253declaration, such as @code{coding: utf-8} appears in one of the first
254few lines of a source file, it indicates to Guile's default reader
255that this source code file is not ASCII. For details see @ref{Character
256Encoding of Source Files}.
07d83abe
MV
257
258@node Case Sensitivity
259@subsubsection Case Sensitivity
9331ffd8
MW
260@cindex fold-case
261@cindex no-fold-case
07d83abe
MV
262
263@c FIXME::martin: Review me!
264
265Scheme as defined in R5RS is not case sensitive when reading symbols.
266Guile, on the contrary is case sensitive by default, so the identifiers
267
268@lisp
269guile-whuzzy
270Guile-Whuzzy
271@end lisp
272
273are the same in R5RS Scheme, but are different in Guile.
274
275It is possible to turn off case sensitivity in Guile by setting the
1518f649
AW
276reader option @code{case-insensitive}. For more information on reader
277options, @xref{Scheme Read}.
07d83abe
MV
278
279@lisp
280(read-enable 'case-insensitive)
281@end lisp
282
9331ffd8
MW
283It is also possible to disable (or enable) case sensitivity within a
284single file by placing the reader directives @code{#!fold-case} (or
285@code{#!no-fold-case}) within the file itself.
07d83abe
MV
286
287@node Keyword Syntax
288@subsubsection Keyword Syntax
289
290
291@node Reader Extensions
292@subsubsection Reader Extensions
293
294@deffn {Scheme Procedure} read-hash-extend chr proc
295@deffnx {C Function} scm_read_hash_extend (chr, proc)
296Install the procedure @var{proc} for reading expressions
297starting 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
3323ec06
NJ
300returned will be the return value of @code{read}.
301Passing @code{#f} for @var{proc} will remove a previous setting.
302
07d83abe
MV
303@end deffn
304
305
306@node Scheme Read
307@subsection Reading Scheme Code
308
309@rnindex read
310@deffn {Scheme Procedure} read [port]
311@deffnx {C Function} scm_read (port)
312Read an s-expression from the input port @var{port}, or from
313the current input port if @var{port} is not specified.
314Any whitespace before the next token is discarded.
315@end deffn
316
317The behaviour of Guile's Scheme reader can be modified by manipulating
1518f649 318its read options.
07d83abe 319
1518f649
AW
320@cindex options - read
321@cindex read options
07d83abe 322@deffn {Scheme Procedure} read-options [setting]
9331ffd8
MW
323Display the current settings of the global read options. If
324@var{setting} is omitted, only a short form of the current read options
325is printed. Otherwise if @var{setting} is the symbol @code{help}, a
326complete options description is displayed.
07d83abe
MV
327@end deffn
328
1518f649
AW
329The set of available options, and their default values, may be had by
330invoking @code{read-options} at the prompt.
331
332@smalllisp
333scheme@@(guile-user)> (read-options)
334(square-brackets keywords #f positions)
335scheme@@(guile-user)> (read-options 'help)
336copy no Copy source code expressions.
337positions yes Record positions of source code expressions.
338case-insensitive no Convert symbols to lower case.
339keywords #f Style of keyword recognition: #f, 'prefix or 'postfix.
340r6rs-hex-escapes no Use R6RS variable-length character and string hex escapes.
341square-brackets yes Treat `[' and `]' as parentheses, for R6RS compatibility.
c869f0c1
AW
342hungry-eol-escapes no In strings, consume leading whitespace after an
343 escaped end-of-line.
bf9eb54a 344curly-infix no Support SRFI-105 curly infix expressions.
dc59631d 345r7rs-symbols no Support R7RS |...| symbol notation.
1518f649
AW
346@end smalllisp
347
9331ffd8
MW
348Note that Guile also includes a preliminary mechanism for setting read
349options on a per-port basis. For instance, the @code{case-insensitive}
350read option is set (or unset) on the port when the reader encounters the
bf9eb54a
MW
351@code{#!fold-case} or @code{#!no-fold-case} reader directives.
352Similarly, 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
355unsets @code{square-brackets} on the port (@pxref{SRFI-105}). There is
9331ffd8
MW
356currently no other way to access or set the per-port read options.
357
1518f649
AW
358The boolean options may be toggled with @code{read-enable} and
359@code{read-disable}. The non-boolean @code{keywords} option must be set
360using @code{read-set!}.
361
07d83abe
MV
362@deffn {Scheme Procedure} read-enable option-name
363@deffnx {Scheme Procedure} read-disable option-name
1233b383 364@deffnx {Scheme Syntax} read-set! option-name value
07d83abe
MV
365Modify the read options. @code{read-enable} should be used with boolean
366options and switches them on, @code{read-disable} switches them off.
1233b383
AW
367
368@code{read-set!} can be used to set an option to a specific value. Due
369to historical oddities, it is a macro that expects an unquoted option
370name.
07d83abe
MV
371@end deffn
372
1518f649
AW
373For example, to make @code{read} fold all symbols to their lower case
374(perhaps for compatibility with older Scheme code), you can enter:
375
376@lisp
377(read-enable 'case-insensitive)
378@end lisp
379
c869f0c1
AW
380For more information on the effect of the @code{r6rs-hex-escapes} and
381@code{hungry-eol-escapes} options, see (@pxref{String Syntax}).
1518f649 382
dc59631d
MW
383For more information on the @code{r7rs-symbols} option, see
384(@pxref{Symbol Read Syntax}).
385
1518f649
AW
386
387@node Scheme Write
388@subsection Writing Scheme Values
389
390Any scheme value may be written to a port. Not all values may be read
391back in (@pxref{Scheme Read}), however.
392
393@rnindex write
394@rnindex print
395@deffn {Scheme Procedure} write obj [port]
396Send a representation of @var{obj} to @var{port} or to the current
397output port if not given.
398
399The output is designed to be machine readable, and can be read back
400with @code{read} (@pxref{Scheme Read}). Strings are printed in
401double quotes, with escapes if necessary, and characters are printed in
402@samp{#\} notation.
403@end deffn
404
405@rnindex display
406@deffn {Scheme Procedure} display obj [port]
407Send a representation of @var{obj} to @var{port} or to the current
408output port if not given.
409
410The output is designed for human readability, it differs from
411@code{write} in that strings are printed without double quotes and
412escapes, and characters are printed as per @code{write-char}, not in
413@samp{#\} form.
414@end deffn
415
416As was the case with the Scheme reader, there are a few options that
417affect the behavior of the Scheme printer.
418
419@cindex options - print
420@cindex print options
421@deffn {Scheme Procedure} print-options [setting]
422Display the current settings of the read options. If @var{setting} is
423omitted, only a short form of the current read options is
424printed. Otherwise if @var{setting} is the symbol @code{help}, a
425complete options description is displayed.
426@end deffn
427
428The set of available options, and their default values, may be had by
429invoking @code{print-options} at the prompt.
430
431@smalllisp
432scheme@@(guile-user)> (print-options)
433(quote-keywordish-symbols reader highlight-suffix "@}" highlight-prefix "@{")
434scheme@@(guile-user)> (print-options 'help)
435highlight-prefix @{ The string to print before highlighted values.
436highlight-suffix @} The string to print after highlighted values.
437quote-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
442 not '#f'.
e2e8ca42
AW
443escape-newlines yes Render newlines as \n when printing
444 using `write'.
6e504a7b
MW
445r7rs-symbols no Escape symbols using R7RS |...| symbol
446 notation.
1518f649
AW
447@end smalllisp
448
1233b383 449These options may be modified with the print-set! syntax.
1518f649 450
1233b383
AW
451@deffn {Scheme Syntax} print-set! option-name value
452Modify the print options. Due to historical oddities, @code{print-set!}
453is a macro that expects an unquoted option name.
07d83abe
MV
454@end deffn
455
456
457@node Fly Evaluation
458@subsection Procedures for On the Fly Evaluation
459
c2e56d9b
AW
460Scheme has the lovely property that its expressions may be represented
461as data. The @code{eval} procedure takes a Scheme datum and evaluates
462it as code.
07d83abe
MV
463
464@rnindex eval
465@c ARGFIXME environment/environment specifier
b4fddbbe
MV
466@deffn {Scheme Procedure} eval exp module_or_state
467@deffnx {C Function} scm_eval (exp, module_or_state)
07d83abe 468Evaluate @var{exp}, a list representing a Scheme expression,
64de6db5 469in the top-level environment specified by @var{module_or_state}.
07d83abe 470While @var{exp} is evaluated (using @code{primitive-eval}),
64de6db5
BT
471@var{module_or_state} is made the current module. The current module
472is reset to its previous value when @code{eval} returns.
b4fddbbe
MV
473XXX - dynamic states.
474Example: (eval '(+ 1 2) (interaction-environment))
07d83abe
MV
475@end deffn
476
477@rnindex interaction-environment
478@deffn {Scheme Procedure} interaction-environment
479@deffnx {C Function} scm_interaction_environment ()
480Return a specifier for the environment that contains
481implementation--defined bindings, typically a superset of those
482listed in the report. The intent is that this procedure will
483return the environment in which the implementation would
484evaluate expressions dynamically typed by the user.
485@end deffn
486
c2e56d9b
AW
487@xref{Environments}, for other environments.
488
489One does not always receive code as Scheme data, of course, and this is
490especially the case for Guile's other language implementations
491(@pxref{Other Languages}). For the case in which all you have is a
492string, we have @code{eval-string}. There is a legacy version of this
493procedure in the default environment, but you really want the one from
494@code{(ice-9 eval-string)}, so load it up:
495
496@example
497(use-modules (ice-9 eval-string))
498@end example
499
994d87be
BT
500@deffn {Scheme Procedure} eval-string string [#:module=#f] [#:file=#f] @
501 [#:line=#f] [#:column=#f] @
502 [#:lang=(current-language)] @
503 [#:compile?=#f]
c2e56d9b
AW
504Parse @var{string} according to the current language, normally Scheme.
505Evaluate or compile the expressions it contains, in order, returning the
506last expression.
507
508If 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.
511
512The @var{file}, @var{line}, and @var{column} keyword arguments can be
513used to indicate that the source string begins at a particular source
514location.
515
516Finally, @var{lang} is a language, defaulting to the current language,
517and the expression is compiled if @var{compile?} is true or there is no
518evaluator for the given language.
519@end deffn
520
521@deffn {C Function} scm_eval_string (string)
07d83abe 522@deffnx {C Function} scm_eval_string_in_module (string, module)
c2e56d9b
AW
523These C bindings call @code{eval-string} from @code{(ice-9
524eval-string)}, evaluating within @var{module} or the current module.
07d83abe
MV
525@end deffn
526
40296bab 527@deftypefn {C Function} SCM scm_c_eval_string (const char *string)
c2e56d9b
AW
528@code{scm_eval_string}, but taking a C string in locale encoding instead
529of an @code{SCM}.
40296bab
KR
530@end deftypefn
531
df0a1002 532@deffn {Scheme Procedure} apply proc arg @dots{} arglst
07d83abe
MV
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)
538@rnindex apply
df0a1002 539Call @var{proc} with arguments @var{arg} @dots{} and the
07d83abe
MV
540elements of the @var{arglst} list.
541
542@code{scm_apply} takes parameters corresponding to a Scheme level
df0a1002
BT
543@code{(lambda (proc arg1 . rest) ...)}. So @var{arg1} and all but the
544last element of the @var{rest} list make up @var{arg} @dots{}, and the
545last element of @var{rest} is the @var{arglst} list. Or if @var{rest}
546is the empty list @code{SCM_EOL} then there's no @var{arg} @dots{}, and
547(@var{arg1}) is the @var{arglst}.
07d83abe
MV
548
549@var{arglst} is not modified, but the @var{rest} list passed to
550@code{scm_apply} is modified.
551@end deffn
552
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)
8d596b11 557@deffnx {C Function} scm_call_4 (proc, arg1, arg2, arg3, arg4)
13459a96
AW
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)
741b8a23
MW
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)
07d83abe
MV
563Call @var{proc} with the given arguments.
564@end deffn
565
07c2ca0f 566@deffn {C Function} scm_call (proc, ...)
741b8a23
MW
567Call @var{proc} with any number of arguments. The argument list must be
568terminated by @code{SCM_UNDEFINED}. For example:
569
570@example
07c2ca0f
MW
571scm_call (scm_c_public_ref ("guile", "+"),
572 scm_from_int (1),
573 scm_from_int (2),
574 SCM_UNDEFINED);
741b8a23
MW
575@end example
576@end deffn
577
13459a96
AW
578@deffn {C Function} scm_call_n (proc, argv, nargs)
579Call @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}.
582@end deffn
583
07d83abe
MV
584@deffn {Scheme Procedure} primitive-eval exp
585@deffnx {C Function} scm_primitive_eval (exp)
586Evaluate @var{exp} in the top-level environment specified by
587the current module.
588@end deffn
589
590
00ce5125
AW
591@node Compilation
592@subsection Compiling Scheme Code
593
594The @code{eval} procedure directly interprets the S-expression
595representation of Scheme. An alternate strategy for evaluation is to
596determine ahead of time what computations will be necessary to
597evaluate the expression, and then use that recipe to produce the
598desired results. This is known as @dfn{compilation}.
599
600While it is possible to compile simple Scheme expressions such as
601@code{(+ 2 2)} or even @code{"Hello world!"}, compilation is most
ca445ba5 602interesting in the context of procedures. Compiling a lambda expression
00ce5125
AW
603produces a compiled procedure, which is just like a normal procedure
604except typically much faster, because it can bypass the generic
605interpreter.
606
607Functions from system modules in a Guile installation are normally
608compiled already, so they load and run quickly.
609
14d2ee31 610@cindex automatic compilation
00ce5125
AW
611Note that well-written Scheme programs will not typically call the
612procedures in this section, for the same reason that it is often bad
14d2ee31
LC
613taste to use @code{eval}. By default, Guile automatically compiles any
614files it encounters that have not been compiled yet (@pxref{Invoking
615Guile, @code{--auto-compile}}). The compiler can also be invoked
b8b06598 616explicitly from the shell as @code{guild compile foo.scm}.
00ce5125
AW
617
618(Why are calls to @code{eval} and @code{compile} usually in bad taste?
619Because they are limited, in that they can only really make sense for
620top-level expressions. Also, most needs for ``compile-time''
621computation are fulfilled by macros and closures. Of course one good
622counterexample is the REPL itself, or any code that reads expressions
623from a port.)
624
1e56cff2
AW
625Automatic compilation generally works transparently, without any need
626for user intervention. However Guile does not yet do proper dependency
627tracking, 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}
629would not be automatically recompiled. To forcibly invalidate the
630auto-compilation cache, pass the @code{--fresh-auto-compile} option to
631Guile, or set the @code{GUILE_AUTO_COMPILE} environment variable to
632@code{fresh} (instead of to @code{0} or @code{1}).
633
ca445ba5
AW
634For more information on the compiler itself, see @ref{Compiling to the
635Virtual Machine}. For information on the virtual machine, see @ref{A
00ce5125
AW
636Virtual Machine for Guile}.
637
b8b06598 638The command-line interface to Guile's compiler is the @command{guild
788cf402
LC
639compile} command:
640
b8b06598 641@deffn {Command} {guild compile} [@option{option}...] @var{file}...
788cf402
LC
642Compile @var{file}, a source file, and store bytecode in the compilation cache
643or in the file specified by the @option{-o} option. The following options are
644available:
645
646@table @option
647
648@item -L @var{dir}
649@itemx --load-path=@var{dir}
650Add @var{dir} to the front of the module load path.
651
652@item -o @var{ofile}
653@itemx --output=@var{ofile}
eda06220
LC
654Write output bytecode to @var{ofile}. By convention, bytecode file
655names end in @code{.go}. When @option{-o} is omitted, the output file
656name is as for @code{compile-file} (see below).
788cf402
LC
657
658@item -W @var{warning}
659@itemx --warn=@var{warning}
ffd901eb 660@cindex warnings, compiler
75365375
LC
661Emit warnings of type @var{warning}; use @code{--warn=help} for a list
662of available warnings and their description. Currently recognized
663warnings include @code{unused-variable}, @code{unused-toplevel},
679a3556
LC
664@code{unbound-variable}, @code{arity-mismatch}, @code{format},
665@code{duplicate-case-datum}, and @code{bad-case-datum}.
788cf402
LC
666
667@item -f @var{lang}
668@itemx --from=@var{lang}
669Use @var{lang} as the source language of @var{file}. If this option is omitted,
670@code{scheme} is assumed.
671
672@item -t @var{lang}
673@itemx --to=@var{lang}
674Use @var{lang} as the target language of @var{file}. If this option is omitted,
c0d928dc 675@code{rtl} is assumed.
788cf402 676
d4b88945
LC
677@item -T @var{target}
678@itemx --target=@var{target}
c0d928dc
AW
679Produce code for @var{target} instead of @var{%host-type} (@pxref{Build
680Config, %host-type}). Target must be a valid GNU triplet, such as
681@code{armv5tel-unknown-linux-gnueabi} (@pxref{Specifying Target
d4b88945
LC
682Triplets,,, autoconf, GNU Autoconf Manual}).
683
788cf402
LC
684@end table
685
eda06220
LC
686Each @var{file} is assumed to be UTF-8-encoded, unless it contains a
687coding declaration as recognized by @code{file-encoding}
688(@pxref{Character Encoding of Source Files}).
788cf402
LC
689@end deffn
690
691The compiler can also be invoked directly by Scheme code using the procedures
692below:
693
994d87be
BT
694@deffn {Scheme Procedure} compile exp [#:env=#f] @
695 [#:from=(current-language)] @
696 [#:to=value] [#:opts=()]
00ce5125
AW
697Compile the expression @var{exp} in the environment @var{env}. If
698@var{exp} is a procedure, the result will be a compiled procedure;
699otherwise @code{compile} is mostly equivalent to @code{eval}.
700
701For a discussion of languages and compiler options, @xref{Compiling to
702the Virtual Machine}.
703@end deffn
704
994d87be 705@deffn {Scheme Procedure} compile-file file [#:output-file=#f] @
c0d928dc 706 [#:from=(current-language)] [#:to='rtl] @
994d87be
BT
707 [#:env=(default-environment from)] @
708 [#:opts='()] @
709 [#:canonicalization='relative]
00ce5125
AW
710Compile the file named @var{file}.
711
043bca03
AW
712Output will be written to a @var{output-file}. If you do not supply an
713output file name, output is written to a file in the cache directory, as
714computed by @code{(compiled-file-name @var{file})}.
715
716@var{from} and @var{to} specify the source and target languages.
717@xref{Compiling to the Virtual Machine}, for more information on these
718options, and on @var{env} and @var{opts}.
eda06220 719
b8b06598 720As with @command{guild compile}, @var{file} is assumed to be
eda06220 721UTF-8-encoded unless it contains a coding declaration.
00ce5125
AW
722@end deffn
723
724@deffn {Scheme Procedure} compiled-file-name file
043bca03
AW
725Compute a cached location for a compiled version of a Scheme file named
726@var{file}.
727
728This file will usually be below the @file{$HOME/.cache/guile/ccache}
729directory, depending on the value of the @env{XDG_CACHE_HOME}
730environment variable. The intention is that @code{compiled-file-name}
731provides a fallback location for caching auto-compiled files. If you
732want to place a compile file in the @code{%load-compiled-path}, you
733should pass the @var{output-file} option to @code{compile-file},
734explicitly.
00ce5125
AW
735@end deffn
736
14d2ee31
LC
737@defvr {Scheme Variable} %auto-compilation-options
738This variable contains the options passed to the @code{compile-file}
739procedure when auto-compiling source files. By default, it enables
740useful compilation warnings. It can be customized from @file{~/.guile}.
741@end defvr
742
07d83abe
MV
743@node Loading
744@subsection Loading Scheme Code from File
745
746@rnindex load
ec3a8ace 747@deffn {Scheme Procedure} load filename [reader]
07d83abe 748Load @var{filename} and evaluate its contents in the top-level
925172cf 749environment.
ec3a8ace
NJ
750
751@var{reader} if provided should be either @code{#f}, or a procedure with
752the signature @code{(lambda (port) @dots{})} which reads the next
753expression from @var{port}. If @var{reader} is @code{#f} or absent,
754Guile's built-in @code{read} procedure is used (@pxref{Scheme Read}).
755
756The @var{reader} argument takes effect by setting the value of the
757@code{current-reader} fluid (see below) before loading the file, and
758restoring its previous value when loading is complete. The Scheme code
759inside @var{filename} can itself change the current reader procedure on
760the fly by setting @code{current-reader} fluid.
761
762If the variable @code{%load-hook} is defined, it should be bound to a
763procedure that will be called before any code is loaded. See
764documentation for @code{%load-hook} later in this section.
07d83abe
MV
765@end deffn
766
00ce5125 767@deffn {Scheme Procedure} load-compiled filename
925172cf 768Load the compiled file named @var{filename}.
00ce5125
AW
769
770Compiling a source file (@pxref{Read/Load/Eval/Compile}) and then
771calling @code{load-compiled} on the resulting file is equivalent to
772calling @code{load} on the source file.
773@end deffn
774
07d83abe
MV
775@deffn {Scheme Procedure} primitive-load filename
776@deffnx {C Function} scm_primitive_load (filename)
925172cf
AW
777Load the file named @var{filename} and evaluate its contents in the
778top-level environment. @var{filename} must either be a full pathname or
779be a pathname relative to the current directory. If the variable
780@code{%load-hook} is defined, it should be bound to a procedure that
781will be called before any code is loaded. See the documentation for
782@code{%load-hook} later in this section.
07d83abe
MV
783@end deffn
784
40296bab
KR
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
787@code{SCM}.
788@end deftypefn
789
ec3a8ace
NJ
790@defvar current-reader
791@code{current-reader} holds the read procedure that is currently being
792used by the above loading procedures to read expressions (from the file
793that they are loading). @code{current-reader} is a fluid, so it has an
794independent value in each dynamic root and should be read and set using
795@code{fluid-ref} and @code{fluid-set!} (@pxref{Fluids and Dynamic
796States}).
1ebe6a63
LC
797
798Changing @code{current-reader} is typically useful to introduce local
799syntactic changes, such that code following the @code{fluid-set!} call
800is read using the newly installed reader. The @code{current-reader}
801change should take place at evaluation time when the code is evaluated,
802or at compilation time when the code is compiled:
803
804@findex eval-when
805@example
806(eval-when (compile eval)
807 (fluid-set! current-reader my-own-reader))
808@end example
809
810The @code{eval-when} form above ensures that the @code{current-reader}
811change occurs at the right time.
ec3a8ace
NJ
812@end defvar
813
07d83abe 814@defvar %load-hook
42ad91f7
KR
815A procedure to be called @code{(%load-hook @var{filename})} whenever a
816file is loaded, or @code{#f} for no such call. @code{%load-hook} is
925172cf 817used by all of the loading functions (@code{load} and
21ad60a1 818@code{primitive-load}, and @code{load-from-path} and
925172cf 819@code{primitive-load-path} documented in the next section).
42ad91f7
KR
820
821For example an application can set this to show what's loaded,
07d83abe
MV
822
823@example
42ad91f7
KR
824(set! %load-hook (lambda (filename)
825 (format #t "Loading ~a ...\n" filename)))
07d83abe 826(load-from-path "foo.scm")
42ad91f7 827@print{} Loading /usr/local/share/guile/site/foo.scm ...
07d83abe 828@end example
07d83abe
MV
829@end defvar
830
831@deffn {Scheme Procedure} current-load-port
832@deffnx {C Function} scm_current_load_port ()
833Return the current-load-port.
834The load port is used internally by @code{primitive-load}.
835@end deffn
836
925172cf
AW
837@node Load Paths
838@subsection Load Paths
839
840The procedure in the previous section look for Scheme code in the file
841system at specific location. Guile also has some procedures to search
842the load path for code.
843
0740cb49
AW
844@defvar %load-path
845List of directories which should be searched for Scheme modules and
bd31bce6
MW
846libraries. When Guile starts up, @code{%load-path} is initialized to
847the default load path @code{(list (%library-dir) (%site-dir)
848(%global-site-dir) (%package-data-dir))}. The @env{GUILE_LOAD_PATH}
849environment variable can be used to prepend or append additional
850directories (@pxref{Environment Variables}).
851
852@xref{Build Config}, for more on @code{%site-dir} and related
853procedures.
0740cb49 854@end defvar
925172cf
AW
855
856@deffn {Scheme Procedure} load-from-path filename
857Similar to @code{load}, but searches for @var{filename} in the load
858paths. Preferentially loads a compiled version of the file, if it is
859available and up-to-date.
860@end deffn
861
862A user can extend the load path by calling @code{add-to-load-path}.
863
864@deffn {Scheme Syntax} add-to-load-path dir
865Add @var{dir} to the load path.
0740cb49 866@end deffn
925172cf
AW
867
868For example, a script might include this form to add the directory that
869it is in to the load path:
870
871@example
872(add-to-load-path (dirname (current-filename)))
873@end example
925172cf
AW
874
875It'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
877of modifying the path both at compile-time and at run-time.
878
925172cf
AW
879@deffn {Scheme Procedure} primitive-load-path filename [exception-on-not-found]
880@deffnx {C Function} scm_primitive_load_path (filename)
881Search @code{%load-path} for the file named @var{filename} and
882load it into the top-level environment. If @var{filename} is a
883relative pathname and is not found in the list of search paths,
f6fd2c03 884an error is signalled. Preferentially loads a compiled version of the
925172cf
AW
885file, if it is available and up-to-date.
886
f6fd2c03
AW
887If @var{filename} is a relative pathname and is not found in the list of
888search paths, one of three things may happen, depending on the optional
889second 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
891with no arguments. (This allows a distinction to be made between
892exceptions raised by loading a file, and exceptions related to the
893loader itself.) Otherwise an error is signalled.
894
895For compatibility with Guile 1.8 and earlier, the C function takes only
896one argument, which can be either a string (the file name) or an
897argument list.
925172cf
AW
898@end deffn
899
900@deffn {Scheme Procedure} %search-load-path filename
901@deffnx {C Function} scm_sys_search_load_path (filename)
0740cb49
AW
902Search @code{%load-path} for the file named @var{filename}, which must
903be readable by the current user. If @var{filename} is found in the list
904of paths to search or is an absolute pathname, return its full pathname.
905Otherwise, return @code{#f}. Filenames may have any of the optional
906extensions in the @code{%load-extensions} list; @code{%search-load-path}
925172cf
AW
907will try each extension automatically.
908@end deffn
909
07d83abe
MV
910@defvar %load-extensions
911A list of default file extensions for files containing Scheme code.
912@code{%search-load-path} tries each of these extensions when looking for
913a file to load. By default, @code{%load-extensions} is bound to the
914list @code{("" ".scm")}.
915@end defvar
916
0740cb49
AW
917As mentioned above, when Guile searches the @code{%load-path} for a
918source file, it will also search the @code{%load-compiled-path} for a
919corresponding compiled file. If the compiled file is as new or newer
920than the source file, it will be loaded instead of the source file,
921using @code{load-compiled}.
922
923@defvar %load-compiled-path
924Like @code{%load-path}, but for compiled files. By default, this path
925has two entries: one for compiled files from Guile itself, and one for
bd31bce6
MW
926site packages. The @env{GUILE_LOAD_COMPILED_PATH} environment variable
927can be used to prepend or append additional directories
928(@pxref{Environment Variables}).
0740cb49
AW
929@end defvar
930
931When @code{primitive-load-path} searches the @code{%load-compiled-path}
932for a corresponding compiled file for a relative path it does so by
933appending @code{.go} to the relative path. For example, searching for
934@code{ice-9/popen} could find
f88e9510
AW
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}.
0740cb49
AW
937
938If @code{primitive-load-path} does not find a corresponding @code{.go}
939file in the @code{%load-compiled-path}, or the @code{.go} file is out of
940date, it will search for a corresponding auto-compiled file in the
941fallback path, possibly creating one if one does not exist.
942
943@xref{Installing Site Packages}, for more on how to correctly install
944site packages. @xref{Modules and the File System}, for more on the
945relationship between load paths and modules. @xref{Compilation}, for
946more on the fallback path and auto-compilation.
947
948Finally, there are a couple of helper procedures for general path
949manipulation.
950
951@deffn {Scheme Procedure} parse-path path [tail]
952@deffnx {C Function} scm_parse_path (path, tail)
953Parse @var{path}, which is expected to be a colon-separated string, into
954a list and return the resulting list with @var{tail} appended. If
955@var{path} is @code{#f}, @var{tail} is returned.
956@end deffn
957
bd31bce6
MW
958@deffn {Scheme Procedure} parse-path-with-ellipsis path base
959@deffnx {C Function} scm_parse_path_with_ellipsis (path, base)
960Parse @var{path}, which is expected to be a colon-separated string, into
961a list and return the resulting list with @var{base} (a list) spliced in
962place of the @code{...} path component, if present, or else @var{base}
963is added to the end. If @var{path} is @code{#f}, @var{base} is
964returned.
965@end deffn
966
0740cb49
AW
967@deffn {Scheme Procedure} search-path path filename [extensions [require-exts?]]
968@deffnx {C Function} scm_search_path (path, filename, rest)
969Search @var{path} for a directory containing a file named
970@var{filename}. The file must be readable, and not a directory. If we
971find 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},
974we search for @var{filename} concatenated with each @var{extension}. If
975@var{require-exts?} is true, require that the returned file name have
976one of the given extensions; if @var{require-exts?} is not given, it
977defaults to @code{#f}.
978
979For compatibility with Guile 1.8 and earlier, the C function takes only
980three arguments.
981@end deffn
982
925172cf 983
8748ffea
MG
984@node Character Encoding of Source Files
985@subsection Character Encoding of Source Files
986
4c7b9975 987@cindex source file encoding
8748ffea
MG
988@cindex primitive-load
989@cindex load
7099eec4
MW
990Scheme source code files are usually encoded in ASCII or UTF-8, but the
991built-in reader can interpret other character encodings as well. When
992Guile loads Scheme source code, it uses the @code{file-encoding}
993procedure (described below) to try to guess the encoding of the file.
994In the absence of any hints, UTF-8 is assumed. One way to provide a
995hint about the encoding of a source file is to place a coding
996declaration in the top 500 characters of the file.
8748ffea
MG
997
998A coding declaration has the form @code{coding: XXXXXX}, where
999@code{XXXXXX} is the name of a character encoding in which the source
1000code file has been encoded. The coding declaration must appear in a
7099eec4
MW
1001scheme comment. It can either be a semicolon-initiated comment, or the
1002first block @code{#!} comment in the file.
8748ffea
MG
1003
1004The name of the character encoding in the coding declaration is
4c7b9975
LC
1005typically lower case and containing only letters, numbers, and hyphens,
1006as recognized by @code{set-port-encoding!} (@pxref{Ports,
1007@code{set-port-encoding!}}). Common examples of character encoding
1008names are @code{utf-8} and @code{iso-8859-1},
1009@url{http://www.iana.org/assignments/character-sets, as defined by
1010IANA}. Thus, the coding declaration is mostly compatible with Emacs.
1011
1012However, there are some differences in encoding names recognized by
1013Emacs and encoding names defined by IANA, the latter being essentially a
1014subset of the former. For instance, @code{latin-1} is a valid encoding
1015name for Emacs, but it's not according to the IANA standard, which Guile
a270e133
LC
1016follows; instead, you should use @code{iso-8859-1}, which is both
1017understood by Emacs and dubbed by IANA (IANA writes it uppercase but
1018Emacs wants it lowercase and Guile is case insensitive.)
8748ffea
MG
1019
1020For source code, only a subset of all possible character encodings can
1021be interpreted by the built-in source code reader. Only those
1022character encodings in which ASCII text appears unmodified can be
1023used. This includes @code{UTF-8} and @code{ISO-8859-1} through
1024@code{ISO-8859-15}. The multi-byte character encodings @code{UTF-16}
1025and @code{UTF-32} may not be used because they are not compatible with
1026ASCII.
1027
1028@cindex read
d6a6989e
LC
1029@cindex encoding
1030@cindex port encoding
1031@findex set-port-encoding!
8748ffea
MG
1032There might be a scenario in which one would want to read non-ASCII
1033code from a port, such as with the function @code{read}, instead of
1034with @code{load}. If the port's character encoding is the same as the
1035encoding of the code to be read by the port, not other special
1036handling is necessary. The port will automatically do the character
1037encoding conversion. The functions @code{setlocale} or by
d6a6989e
LC
1038@code{set-port-encoding!} are used to set port encodings
1039(@pxref{Ports}).
8748ffea
MG
1040
1041If a port is used to read code of unknown character encoding, it can
1042accomplish this in three steps. First, the character encoding of the
1043port should be set to ISO-8859-1 using @code{set-port-encoding!}.
1044Then, the procedure @code{file-encoding}, described below, is used to
1045scan for a coding declaration when reading from the port. As a side
1046effect, it rewinds the port after its scan is complete. After that,
1047the port's character encoding should be set to the encoding returned
1048by @code{file-encoding}, if any, again by using
1049@code{set-port-encoding!}. Then the code can be read as normal.
1050
7099eec4
MW
1051Alternatively, one can use the @code{#:guess-encoding} keyword argument
1052of @code{open-file} and related procedures. @xref{File Ports}.
1053
8748ffea 1054@deffn {Scheme Procedure} file-encoding port
5f6ffd66 1055@deffnx {C Function} scm_file_encoding (port)
7099eec4
MW
1056Attempt to scan the first few hundred bytes from the @var{port} for
1057hints about its character encoding. Return a string containing the
1058encoding name or @code{#f} if the encoding cannot be determined. The
1059port is rewound.
1060
1061Currently, the only supported method is to look for an Emacs-like
1062character coding declaration (@pxref{Recognize Coding, how Emacs
1063recognizes file encoding,, emacs, The GNU Emacs Reference Manual}). The
1064coding declaration is of the form @code{coding: XXXXX} and must appear
1065in a Scheme comment. Additional heuristics may be added in the future.
8748ffea
MG
1066@end deffn
1067
07d83abe
MV
1068
1069@node Delayed Evaluation
1070@subsection Delayed Evaluation
1071@cindex delayed evaluation
1072@cindex promises
1073
1074Promises are a convenient way to defer a calculation until its result
41502bd0
MW
1075is actually needed, and to run such a calculation only once. Also
1076@pxref{SRFI-45}.
07d83abe
MV
1077
1078@deffn syntax delay expr
1079@rnindex delay
1080Return a promise object which holds the given @var{expr} expression,
1081ready to be evaluated by a later @code{force}.
1082@end deffn
1083
1084@deffn {Scheme Procedure} promise? obj
1085@deffnx {C Function} scm_promise_p (obj)
1086Return true if @var{obj} is a promise.
1087@end deffn
1088
1089@rnindex force
1090@deffn {Scheme Procedure} force p
1091@deffnx {C Function} scm_force (p)
1092Return the value obtained from evaluating the @var{expr} in the given
1093promise @var{p}. If @var{p} has previously been forced then its
1094@var{expr} is not evaluated again, instead the value obtained at that
1095time is simply returned.
1096
1097During a @code{force}, an @var{expr} can call @code{force} again on
1098its own promise, resulting in a recursive evaluation of that
1099@var{expr}. The first evaluation to return gives the value for the
1100promise. Higher evaluations run to completion in the normal way, but
1101their results are ignored, @code{force} always returns the first
1102value.
1103@end deffn
1104
1105
d062a8c1
AW
1106@node Local Evaluation
1107@subsection Local Evaluation
1108
68c31a42
AW
1109Guile includes a facility to capture a lexical environment, and later
1110evaluate a new expression within that environment. This code is
1111implemented in a module.
1112
1113@example
1114(use-modules (ice-9 local-eval))
1115@end example
1116
d062a8c1
AW
1117@deffn syntax the-environment
1118Captures and returns a lexical environment for use with
1119@code{local-eval} or @code{local-compile}.
1120@end deffn
1121
1122@deffn {Scheme Procedure} local-eval exp env
1123@deffnx {C Function} scm_local_eval (exp, env)
68c31a42
AW
1124@deffnx {Scheme Procedure} local-compile exp env [opts=()]
1125Evaluate or compile the expression @var{exp} in the lexical environment
1126@var{env}.
1127@end deffn
1128
1129Here is a simple example, illustrating that it is the variable
1130that gets captured, not just its value at one point in time.
1131
1132@example
1133(define e (let ((x 100)) (the-environment)))
1134(define fetch-x (local-eval '(lambda () x) e))
1135(fetch-x)
1136@result{} 100
1137(local-eval '(set! x 42) e)
1138(fetch-x)
1139@result{} 42
1140@end example
1141
1142While @var{exp} is evaluated within the lexical environment of
1143@code{(the-environment)}, it has the dynamic environment of the call to
1144@code{local-eval}.
1145
1146@code{local-eval} and @code{local-compile} can only evaluate
1147expressions, not definitions.
1148
1149@example
1150(local-eval '(define foo 42)
1151 (let ((x 100)) (the-environment)))
1152@result{} syntax error: definition in expression context
1153@end example
1154
1155Note that the current implementation of @code{(the-environment)} only
1156captures ``normal'' lexical bindings, and pattern variables bound by
1157@code{syntax-case}. It does not currently capture local syntax
1158transformers bound by @code{let-syntax}, @code{letrec-syntax} or
1159non-top-level @code{define-syntax} forms. Any attempt to reference such
1160captured syntactic keywords via @code{local-eval} or
1161@code{local-compile} produces an error.
d062a8c1
AW
1162
1163
eb7da3d8
AW
1164@node Local Inclusion
1165@subsection Local Inclusion
1166
1167This section has discussed various means of linking Scheme code
1168together: fundamentally, loading up files at run-time using @code{load}
1169and @code{load-compiled}. Guile provides another option to compose
1170parts of programs together at expansion-time instead of at run-time.
1171
1172@deffn {Scheme Syntax} include file-name
1173Open @var{file-name}, at expansion-time, and read the Scheme forms that
1174it contains, splicing them into the location of the @code{include},
1175within a @code{begin}.
84f5a825
AW
1176
1177If @var{file-name} is a relative path, it is searched for relative to
3cff108d 1178the path that contains the file that the @code{include} form appears in.
eb7da3d8
AW
1179@end deffn
1180
1181If 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
1183preprocessor's @code{#include}. When you use @code{include}, it is as
1184if the contents of the included file were typed in instead of the
1185@code{include} form.
1186
1187Because the code is included at compile-time, it is available to the
1188macroexpander. Syntax definitions in the included file are available to
1189later code in the form in which the @code{include} appears, without the
1190need for @code{eval-when}. (@xref{Eval When}.)
1191
1192For the same reason, compiling a form that uses @code{include} results
1193in one compilation unit, composed of multiple files. Loading the
1194compiled file is one @code{stat} operation for the compilation unit,
1195instead of @code{2*@var{n}} in the case of @code{load} (once for each
1196loaded source file, and once each corresponding compiled file, in the
1197best case).
1198
1199Unlike @code{load}, @code{include} also works within nested lexical
1200contexts. It so happens that the optimizer works best within a lexical
1201context, because all of the uses of bindings in a lexical context are
1202visible, so composing files by including them within a @code{(let ()
1203...)} can sometimes lead to important speed improvements.
1204
1205On the other hand, @code{include} does have all the disadvantages of
1206early binding: once the code with the @code{include} is compiled, no
1207change to the included file is reflected in the future behavior of the
1208including form.
1209
1210Also, the particular form of @code{include}, which requires an absolute
1211path, or a path relative to the current directory at compile-time, is
1212not very amenable to compiling the source in one place, but then
1213installing the source to another place. For this reason, Guile provides
1214another form, @code{include-from-path}, which looks for the source file
1215to include within a load path.
1216
1217@deffn {Scheme Syntax} include-from-path file-name
1218Like @code{include}, but instead of expecting @code{file-name} to be an
1219absolute file name, it is expected to be a relative path to search in
1220the @code{%load-path}.
1221@end deffn
1222
1223@code{include-from-path} is more useful when you want to install all of
1224the source files for a package (as you should!). It makes it possible
1225to evaluate an installed file from source, instead of relying on the
1226@code{.go} file being up to date.
1227
10d278fd
IP
1228@node REPL Servers
1229@subsection REPL Servers
1230
1231@cindex REPL server
1232
1233The procedures in this section are provided by
1234@lisp
1235(use-modules (system repl server))
1236@end lisp
1237
1238When an application is written in Guile, it is often convenient to
1239allow the user to be able to interact with it by evaluating Scheme
1240expressions in a REPL.
1241
1242The procedures of this module allow you to spawn a @dfn{REPL server},
1243which permits interaction over a local or TCP connection. Guile itself
1244uses them internally to implement the @option{--listen} switch,
1245@ref{Command-line Options}.
1246
1247@deffn {Scheme Procedure} make-tcp-server-socket [#:host=#f] @
1248 [#:addr] [#:port=37146]
1249Return a stream socket bound to a given address @var{addr} and port
1250number @var{port}. If the @var{host} is given, and @var{addr} is not,
1251then the @var{host} string is converted to an address. If neither is
1252given, we use the loopback address.
1253@end deffn
1254
1255@deffn {Scheme Procedure} make-unix-domain-server-socket [#:path="/tmp/guile-socket"]
1256Return a UNIX domain socket, bound to a given @var{path}.
1257@end deffn
1258
1259@deffn {Scheme Procedure} run-server [server-socket]
1260@deffnx {Scheme Procedure} spawn-server [server-socket]
1261Create and run a REPL, making it available over the given
1262@var{server-socket}. If @var{server-socket} is not provided, it
1263defaults to the socket created by calling @code{make-tcp-server-socket}
1264with no arguments.
1265
1266@code{run-server} runs the server in the current thread, whereas
1267@code{spawn-server} runs the server in a new thread.
1268@end deffn
1269
1270@deffn {Scheme Procedure} stop-server-and-clients!
1271Closes the connection on all running server sockets.
5ecc5811
MW
1272
1273Please note that in the current implementation, the REPL threads are
1274cancelled without unwinding their stacks. If any of them are holding
1275mutexes or are within a critical section, the results are unspecified.
10d278fd
IP
1276@end deffn
1277
b0a31499
DT
1278@node Cooperative REPL Servers
1279@subsection Cooperative REPL Servers
1280
1281@cindex Cooperative REPL server
1282
1283The procedures in this section are provided by
1284@lisp
1285(use-modules (system repl coop-server))
1286@end lisp
1287
1288Whereas ordinary REPL servers run in their own threads (@pxref{REPL
1289Servers}), sometimes it is more convenient to provide REPLs that run at
1290specified times within an existing thread, for example in programs
1291utilizing an event loop or in single-threaded programs. This allows for
1292safe access and mutation of a program's data structures from the REPL,
1293without concern for thread synchronization.
1294
1295Although the REPLs are run in the thread that calls
1296@code{spawn-coop-repl-server} and @code{poll-coop-repl-server},
1297dedicated threads are spawned so that the calling thread is not blocked.
1298The spawned threads read input for the REPLs and to listen for new
1299connections.
1300
1301Cooperative REPL servers must be polled periodically to evaluate any
1302pending expressions by calling @code{poll-coop-repl-server} with the
1303object returned from @code{spawn-coop-repl-server}. The thread that
1304calls @code{poll-coop-repl-server} will be blocked for as long as the
1305expression takes to be evaluated or if the debugger is entered.
1306
1307@deffn {Scheme Procedure} spawn-coop-repl-server [server-socket]
1308Create and return a new cooperative REPL server object, and spawn a new
1309thread to listen for connections on @var{server-socket}. Proper
1310functioning of the REPL server requires that
1311@code{poll-coop-repl-server} be called periodically on the returned
1312server object.
1313@end deffn
1314
1315@deffn {Scheme Procedure} poll-coop-repl-server coop-server
1316Poll the cooperative REPL server @var{coop-server} and apply a pending
1317operation if there is one, such as evaluating an expression typed at the
1318REPL prompt. This procedure must be called from the same thread that
1319called @code{spawn-coop-repl-server}.
10d278fd
IP
1320@end deffn
1321
07d83abe
MV
1322@c Local Variables:
1323@c TeX-master: "guile.texi"
1324@c End: