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