\input texinfo @c -*- texinfo -*- @setfilename chicken.info @settitle Chicken Scheme Reference Manual @setchapternewpage on @ifinfo @format INFO-DIR-SECTION Programming START-INFO-DIR-ENTRY * Chicken: (chicken.info). A compiler that translates Scheme source files into C. END-INFO-DIR-ENTRY @end format @end ifinfo @copying Copyright 2007 Felix Winkelmann @end copying @titlepage @sp 10 @title{Chicken Scheme Reference Manual} @author{Felix Winkelmann} @comment The following two commands start the copyright page. @page @vskip 0pt plus 1fill Copyright 2007 Felix Winkelmann @end titlepage @node Top, The User's Manual, (dir), (dir) @top Chicken Scheme Reference Manual This is the top node. @menu * The User's Manual:: * Basic mode of operation:: * Using the compiler:: * Using the interpreter:: * Supported language:: * Deviations from the standard:: * Extensions to the standard:: * Non-standard read syntax:: * Non-standard macros and special forms:: * Pattern matching:: * Declarations:: * Parameters:: * Unit library:: * Unit eval:: * Unit extras:: * Unit srfi-1:: * Unit srfi-4:: * Unit srfi-13:: * Unit srfi-14:: * Unit match:: * Unit regex:: * Unit srfi-18:: * Unit posix:: * Unit utils:: * Unit tcp:: * Unit lolevel:: * Interface to external functions and variables:: * Accessing external objects:: * Foreign type specifiers:: * Embedding:: * Callbacks:: * Locations:: * Other support procedures:: * C interface:: * chicken-setup:: * Data representation:: * Bugs and limitations:: * FAQ:: * Acknowledgements:: * Bibliography:: @end menu @node The User's Manual, Basic mode of operation, Top, Top @chapter The User's Manual @emph{(This document describes version 2.635)} @b{CHICKEN is a compiler that translates Scheme source files into C}, which in turn can be fed to a C-compiler to generate a standalone executable. An interpreter is also available and can be used as a scripting environment or for testing programs before compilation. This package is distributed under the @b{BSD license} and as such is free to use and modify. The method of compilation and the design of the runtime-system follow closely Henry Baker's @uref{http://home.pipeline.com/~hbaker1/CheneyMTA.html, CONS Should Not CONS Its Arguments, Part II: Cheney on the M.T.A.} paper and expose a number of interesting properties: @itemize @item Consing (creation of data on the heap) is relatively inexpensive, because a generational garbage collection scheme is used, in which short-lived data structures are reclaimed extremely quickly. @item Moreover, @code{call-with-current-continuation} is practically for free and CHICKEN does not suffer under any performance penalties if first-class continuations are used in complex ways. @end itemize The generated C code is fully tail-recursive. Some of the features supported by CHICKEN: @itemize @item SRFIs 0, 1, 2, 4, 6-19, 23, 25-31, 37-40, 42, 43, 45, 47, 55, 57, 60-63, 66, 69, 72, 78, 85 and 95. @item Lightweight threads based on first-class continuations @item Pattern matching with Andrew Wright's @code{match} package @item Record structures @item Extended comment- and string-literal syntaxes @item Libraries for regular expressions, string handling @item UNIX system calls and extended data structures @item Create interpreted or compiled shell scripts written in Scheme for UNIX or Windows @item Compiled C files can be easily distributed @item Allows the creation of fully self-contained statically linked executables @item On systems that support it, compiled code can be loaded dynamically @end itemize This manual is merely a reference for the CHICKEN system and assumes a working knowledge of Scheme. The manual is split in the following sections: @table @b @item @ref{Basic mode of operation, Basic mode of operation} Compiling Scheme files. @item @ref{Using the compiler, Using the compiler} Explains how to use CHICKEN to compile programs and execute them. @item @ref{Using the interpreter, Using the interpreter} Invocation and usage of @code{csi}, the CHICKEN interpreter @item @ref{Supported language, Supported language} The language implemented by CHICKEN (deviations from the standard and extensions). @item @ref{Interface to external functions and variables, Interface to external functions and variables} Accessing C and C++ code and data. @item @ref{chicken-setup, chicken-setup} Packaging and installing extension libraries. @item @ref{Data representation, Data representation} How Scheme data is internally represented. @item @ref{Bugs and limitations, Bugs and limitations} Yes, there are some. @item @ref{FAQ, FAQ} A list of Frequently Asked Questions about CHICKEN (and their answers!). @item @ref{Acknowledgements, Acknowledgements} A list of some of the people that have contributed to make CHICKEN what it is. @item @ref{Bibliography, Bibliography} Links to documents that may be of interest. @end table @node Basic mode of operation, Using the compiler, The User's Manual, Top @chapter Basic mode of operation The compiler translates Scheme source code into fairly portable C that can be compiled and linked with most available C compilers. CHICKEN supports the generation of executables and libraries, linked either statically or dynamically. Compiled Scheme code can be loaded dynamically, or can be embedded in applications written in other languages. Separate compilation of modules is fully supported. The most portable way of creating separately linkable entities is supported by so-called @emph{unit}s. A unit is a single compiled object module that contains a number of toplevel expressions that are executed either when the unit is the @emph{main} unit or if the unit is @emph{used}. To use a unit, the unit has to be @emph{declare}ed as used, like this: (declare (uses UNITNAME)) The toplevel expressions of used units are executed in the order in which the units appear in the @code{uses} declaration. Units may be used multiple times and @code{uses} declarations may be circular (the unit is initialized at most once). To compile a file as a unit, add a @code{unit} declaration: (declare (unit UNITNAME)) When compiling different object modules, make sure to have one main unit. This unit is called initially and initializes all used units before executing its toplevel expressions. The main-unit has no @code{unit} declaration. Another method of using definitions in separate source files is to @emph{include} them. This simply inserts the code in a given file into the current file: (include "FILENAME") Macro definitions are only available when processed by @code{include} or @code{require-for-syntax}. Macro definitions in separate units are not available, since they are defined at compile time, i.e the time when that other unit was compiled (macros can optionally be available at runtime, see @code{define-macro} in @ref{Non-standard macros and special forms, Substitution forms and macros}). On platforms that support dynamic loading of compiled code ( Windows, most ELF based systems like Linux or BSD, MacOS X, and others) code can be compiled into a shared object @code{.dll}, @code{.so}, @code{.dylib}) and loaded dynamically into a running application. Previous: @ref{The User's Manual, The User's Manual} Next: @ref{Using the compiler, Using the compiler} @node Using the compiler, Using the interpreter, Basic mode of operation, Top @chapter Using the compiler @menu * Using the compiler - Compiler command line format:: * Using the compiler - Runtime options:: * Using the compiler - Examples:: * Using the compiler - Extending the compiler:: * Using the compiler - Distributing compiled C files:: @end menu The interface to @code{chicken} is intentionally simple. System dependent makefiles, shell-scripts or batch-files should perform any necessary steps before and after invocation of @code{chicken}. A program named @code{csc} provides a much simpler interface to the Scheme- and C-compilers and linker. Enter @verbatim csc -help @end verbatim on the command line for more information. @node Using the compiler - Compiler command line format, Using the compiler - Runtime options, , Using the compiler @section Compiler command line format @verbatim chicken FILENAME @{OPTION@} @end verbatim @code{FILENAME} is the complete pathname of the source file that is to be translated into C. A filename argument of @code{-} specifies that the source text should be read from standard input. Note that the filename has to be the first argument to @code{chicken}. Possible options are: @table @b @item -analyze-only Stop compilation after first analysis pass. @item -benchmark-mode Equivalent to @code{-no-trace -no-lambda-info -optimize-level 3} @code{-fixnum-arithmetic -disable-interrupts -block -lambda-lift}. @item -block Enable block-compilation. When this option is specified, the compiler assumes that global variables are not modified outside this compilation-unit. Specifically, toplevel bindings are not seen by @code{eval} and unused toplevel bindings are removed. @item -case-insensitive Enables the reader to read symbols case insensitive. The default is to read case sensitive (in violation of R5RS). This option registers the @code{case-insensitive} feature identifier. @item -check-imports Search for references to undefined global variables. For each library unit accessed via @code{(declare (uses ...))}, the compiler will search a file named @code{UNITNAME.exports} in the current include path and load its contents into the @emph{import-table} (if found). Also, export-information for extensions (accessed through @code{(require-extension ...)}) will be searched and stored in the import-table. If a required extension does not provide explicit export-information a @code{.exports} file is searched (as with used units). After the analysis phase of the compiler, referenced toplevel variables for which no assignment was found will generate a warning. Also, re-assignments of imported variables will trigger a warning. @item -check-syntax Aborts compilation process after macro-expansion and syntax checks. @item -compress-literals THRESHOLD Compiles quoted literals that exceed the size @code{THRESHOLD} as strings and parse the strings at run-time. This reduces the size of the code and speeds up compile-times of the host C compiler, but has a small run-time performance penalty. The size of a literal is computed by counting recursively the objects in the literal, so a vector counts as 1 plus the count of the elements, a pair counts as the counts of the car and the cdr, respectively. All other objects count 1. @item -debug MODES Enables one or more compiler debugging modes. @code{MODES} is a string of characters that select debugging information about the compiler that will be printed to standard output. @end table @verbatim t show time needed for compilation b show breakdown of time needed for each compiler pass o show performed optimizations r show invocation parameters s show program-size information and other statistics a show node-matching during simplification p show execution of compiler sub-passes l show lambda-lifting information m show GC statistics during compilation n print the line-number database c print every expression before macro-expansion u lists all unassigned global variable references x display information about experimental features D when printing nodes, use node-tree output N show the real-name mapping table U show expressions after the secondary user pass 0 show database before lambda-lifting pass L show expressions after lambda-lifting M show unit-information and syntax-/runtime-requirements 1 show source expressions 2 show canonicalized expressions 3 show expressions converted into CPS 4 show database after each analysis pass 5 show expressions after each optimization pass 6 show expressions after each inlining pass 7 show expressions after complete optimization 8 show database after final analysis 9 show expressions after closure conversion @end verbatim @table @b @item -debug-level LEVEL Selects amount of debug-information. @code{LEVEL} should be an integer. @end table @verbatim -debug-level 0 is equivalent to -no-trace -no-lambda-info -debug-level 1 is equivalent to -no-trace -debug-level 2 does nothing (the default) @end verbatim @table @b @item -disable-interrupts Equivalent to the @code{(disable-interrupts)} declaration. No interrupt-checks are generated for compiled programs. @item -disable-compiler-macros disable expansion of compiler macros. @item -disable-stack-overflow-checks Disables detection of stack overflows. This is equivalent to running the compiled executable with the @code{-:o} runtime option. @item -disable-warning CLASS : Disables specific class of warnings, may be given multiple times. The following classes are defined @end table @verbatim usage warnings related to command-line arguments type warnings related to type-conversion ext warnings related to extension libraries var warnings related to variable- and syntax-definitions and use const warnings related to constant-definitions syntax syntax-related warnings redef warnings about redefinitions of standard- or extended-bindings call warnings related to known procedure calls ffi warnings related to the foreign function interface @end verbatim @table @b @item -dynamic This option should be used when compiling files intended to be loaded dynamically into a running Scheme program. @item -epilogue FILENAME Includes the file named @code{FILENAME} at the end of the compiled source file. The include-path is not searched. This option may be given multiple times. @item -emit-exports FILENAME Write exported toplevel variables to @code{FILENAME}. @item -emit-external-prototypes-first Emit prototypes for callbacks defined with @code{define-external} before any other foreign declarations. This is sometimes useful, when C/C++ code embedded into the a Scheme program has to access the callbacks. By default the prototypes are emitted after foreign declarations. @item -explicit-use Disables automatic use of the units @code{library, eval} and @code{extras}. Use this option if compiling a library unit instead of an application unit. @item -extend FILENAME Loads a Scheme source file or compiled Scheme program (on systems that support it) before compilation commences. This feature can be used to extend the compiler. This option may be given multiple times. The file is also searched in the current include path and in the extension-repository. @item -extension Mostly equivalent to @code{-prelude '(define-extension )'}, where @code{} is the basename of the currently compiled file. Note that if you want to compile a file as a normal (dynamically loadable) extension library, you should also pass the @code{-shared} option. @item -feature SYMBOL Registers @code{SYMBOL} to be a valid feature identifier for @code{cond-expand}. Multiple symbols may be given, if comma-separated. @item -fixnum-arithmetic Equivalent to @code{(fixnum-arithmetic)} declaration. Assume all mathematical operations use small integer arguments. @item -heap-size NUMBER Sets a fixed heap size of the generated executable to @code{NUMBER} bytes. The parameter may be followed by a @code{M} (@code{m}) or @code{K} (@code{k}) suffix which stand for mega- and kilobytes, respectively. The default heap size is 5 kilobytes. Note that only half of it is in use at every given time. @item -heap-initial-size NUMBER Sets the size that the heap of the compiled application should have at startup time. @item -heap-growth PERCENTAGE Sets the heap-growth rate for the compiled program at compile time (see: @code{-:hg}). @item -heap-shrinkage PERCENTAGE Sets the heap-shrinkage rate for the compiled program at compile time (see: @code{-:hs}). @item -help Print a summary of available options and the format of the command line parameters and exit the compiler. @item -import FILENAME Read exports from linked or loaded libraries from given file. See also @code{-check-imports}. This is equivalent to declaring @code{(declare (import FILENAME))}. Implies @code{-check-imports}. @item -include-path PATHNAME Specifies an additional search path for files included via the @code{include} special form. This option may be given multiple times. If the environment variable @code{CHICKEN_INCLUDE_PATH} is set, it should contain a list of alternative include pathnames separated by @code{;}. The environment variable @code{CHICKEN_HOME} is also considered as a search path. @item -inline Enable procedure inlining for known procedures of a size below the threshold (which can be set through the @code{-inline-limit} option). @item -inline-limit THRESHOLD Sets the maximum size of a potentially inlinable procedure. This option is only effective when inlining has been enabled with the @code{-inline} option. The default threshold is @code{10}. @item -keyword-style STYLE Enables alternative keyword syntax, where @code{STYLE} may be either @code{prefix} (as in Common Lisp), @code{suffix} (as in DSSSL) or @code{none}. Any other value is ignored. The default is @code{suffix}. @item -keep-shadowed-macros Do not remove macro definitions with the same name as assigned toplevel variables (the default is to remove the macro definition). @item -lambda-lift Enable the optimization known as lambda-lifting. @item -no-lambda-info Don't emit additional information for each @code{lambda} expression (currently the argument-list, after alpha-conversion/renaming). @item -no-trace Disable generation of tracing information. If a compiled executable should halt due to a runtime error, then a list of the name and the line-number (if available) of the last procedure calls is printed, unless @code{-no-trace} is specified. With this option the generated code is slightly faster. @item -no-warnings Disable generation of compiler warnings. @item -nursery NUMBER @item -stack-size NUMBER Sets the size of the first heap-generation of the generated executable to @code{NUMBER} bytes. The parameter may be followed by a @code{M} (@code{m}) or @code{K} (@code{k}) suffix. The default stack-size depends on the target platform. @item -optimize-leaf-routines Enable leaf routine optimization. @item -optimize-level LEVEL Enables certain sets of optimization options. @code{LEVEL} should be an integer. @end table @verbatim -optimize-level 0 does nothing. -optimize-level 1 is equivalent to -optimize-leaf-routines -optimize-level 2 is currently the same as -optimize-level 1 -optimize-level 3 is equivalent to -optimize-leaf-routines -unsafe @end verbatim @table @b @item -output-file FILENAME Specifies the pathname of the generated C file. Default is @code{FILENAME.c}. @item -postlude EXPRESSIONS Add @code{EXPRESSIONS} after all other toplevel expressions in the compiled file. This option may be given multiple times. Processing of this option takes place after processing of @code{-epilogue}. @item -prelude EXPRESSIONS Add @code{EXPRESSIONS} before all other toplevel expressions in the compiled file. This option may be given multiple times. Processing of this option takes place before processing of @code{-prologue}. @item -profile @item -accumulate-profile Instruments the source code to count procedure calls and execution times. After the program terminates (either via an explicit @code{exit} or implicitly), profiling statistics are written to a file named @code{PROFILE}. Each line of the generated file contains a list with the procedure name, the number of calls and the time spent executing it. Use the @code{chicken-profile} program to display the profiling information in a more user-friendly form. Enter @code{chicken-profile} with no arguments at the command line to get a list of available options. The @code{-accumulate-profile} option is similar to @code{-profile}, but the resulting profile information will be appended to any existing @code{PROFILE} file. @code{chicken-profile} will merge and sum up the accumulated timing information, if several entries for the same procedure calls exist. @item -profile-name FILENAME Specifies name of the generated profile information (which defaults to @code{PROFILE}. Implies @code{-profile}. @item -prologue FILENAME Includes the file named @code{FILENAME} at the start of the compiled source file. The include-path is not searched. This option may be given multiple times. @item -quiet Disables output of compile information. @item -raw Disables the generation of any implicit code that uses the Scheme libraries (that is all runtime system files besides @code{runtime.c} and @code{chicken.h}). @item -require-extension NAME Loads the extension @code{NAME} before the compilation process commences. This is identical to adding @code{(require-extension NAME)} at the start of the compiled program. If @code{-uses NAME} is also given on the command line, then any occurrences of @code{-require-extension NAME} are replaced with @code{(declare (uses NAME))}. Multiple names may be given and should be separated by @code{,}. @item -run-time-macros Makes macros also available at run-time. By default macros are not available at run-time. @item -to-stdout Write compiled code to standard output instead of creating a @code{.c} file. @item -unit NAME Compile this file as a library unit. Equivalent to @code{-prelude "(declare (unit NAME))"} @item -unsafe Disable runtime safety checks. @item -unsafe-libraries Marks the generated file for being linked with the unsafe runtime system. This should be used when generating shared object files that are to be loaded dynamically. If the marker is present, any attempt to load code compiled with this option will signal an error. @item -uses NAME Use definitions from the library unit @code{NAME}. This is equivalent to @code{-prelude "(declare (uses NAME))"}. Multiple arguments may be given, separated by @code{,}. @item -no-usual-integrations Specifies that standard procedures and certain internal procedures may be redefined, and can not be inlined. This is equivalent to declaring @code{(not usual-integrations)}. @item -version Prints the version and some copyright information and exit the compiler. @item -verbose Prints progress information to standard output during compilation. @end table The environment variable @code{CHICKEN_OPTIONS} can be set to a string with default command-line options for the compiler. @node Using the compiler - Runtime options, Using the compiler - Examples, Using the compiler - Compiler command line format, Using the compiler @section Runtime options After successful compilation a C source file is generated and can be compiled with a C compiler. Executables generated with CHICKEN (and the compiler itself) accept a small set of runtime options: @table @b @item @code{-:?} Shows a list of the available runtime options and exits the program. @item @code{-:aNUMBER} Specifies the length of the buffer for recording a trace of the last invoked procedures. Defaults to 16. @item @code{-:b} Enter a read-eval-print-loop when an error is encountered. @item @code{-:B} Sounds a bell (ASCII 7) on every major garbage collection. @item @code{-:c} Forces console mode. Currently this is only used in the interpreter (@code{csi}) to force output of the @code{#;N>} prompt even if stdin is not a terminal (for example if running in an @code{emacs} buffer under Windows). @item @code{-:d} Prints some debug-information at runtime. @item @code{-:D} Prints some more debug-information at runtime. @item @code{-:fNUMBER} Specifies the maximal number of currently pending finalizers before finalization is forced. @item @code{-:hNUMBER} Specifies fixed heap size @item @code{-:hgPERCENTAGE} Sets the growth rate of the heap in percent. If the heap is exhausted, then it will grow by @code{PERCENTAGE}. The default is 200. @item @code{-:hiNUMBER} Specifies the initial heap size @item @code{-:hmNUMBER} Specifies a maximal heap size. The default is (2GB - 15). @item @code{-:hsPERCENTAGE} Sets the shrink rate of the heap in percent. If no more than a quarter of @code{PERCENTAGE} of the heap is used, then it will shrink to @code{PERCENTAGE}. The default is 50. Note: If you want to make sure that the heap never shrinks, specify a value of @code{0}. (this can be useful in situations where an optimal heap-size is known in advance). @item @code{-:o} Disables detection of stack overflows at run-time. @item @code{-:r} Writes trace output to stderr. This option has no effect with in files compiled with the @code{-no-trace} options. @item @code{-:sNUMBER} Specifies stack size. @item @code{-:tNUMBER} Specifies symbol table size. @item @code{-:w} Enables garbage collection of unused symbols. By default unused and unbound symbols are not garbage collected. @item @code{-:x} Raises uncaught exceptions of separately spawned threads in primordial thread. By default uncaught exceptions in separate threads are not handled, unless the primordial one explicitly joins them. When warnings are enabled (the default) and @code{-:x} is not given, a warning will be shown, though. @end table The argument values may be given in bytes, in kilobytes (suffixed with @code{K} or @code{k}), in megabytes (suffixed with @code{M} or @code{m}), or in gigabytes (suffixed with @code{G} or @code{g}). Runtime options may be combined, like @code{-:dc}, but everything following a @code{NUMBER} argument is ignored. So @code{-:wh64m} is OK, but @code{-:h64mw} will not enable GC of unused symbols. @node Using the compiler - Examples, Using the compiler - Extending the compiler, Using the compiler - Runtime options, Using the compiler @section Examples @menu * Using the compiler - Examples - A simple example (with one source file):: * Using the compiler - Examples - An example with multiple files:: @end menu @node Using the compiler - Examples - A simple example (with one source file), Using the compiler - Examples - An example with multiple files, , Using the compiler - Examples @subsection A simple example (with one source file) @menu * Using the compiler - Examples - A simple example (with one source file) - Writing your source file:: * Using the compiler - Examples - A simple example (with one source file) - Compiling your program:: * Using the compiler - Examples - A simple example (with one source file) - Running your program:: @end menu To compile a Scheme program (assuming a UNIX-like environment) consisting of a single source file, perform the following steps. @node Using the compiler - Examples - A simple example (with one source file) - Writing your source file, Using the compiler - Examples - A simple example (with one source file) - Compiling your program, , Using the compiler - Examples - A simple example (with one source file) @subsubsection Writing your source file In this example we will assume your source file is called @code{foo.scm}: ;;; foo.scm (define (fac n) @verbatim (if (zero? n) 1 (* n (fac (- n 1))) ) ) @end verbatim (write (fac 10)) (newline) @node Using the compiler - Examples - A simple example (with one source file) - Compiling your program, Using the compiler - Examples - A simple example (with one source file) - Running your program, Using the compiler - Examples - A simple example (with one source file) - Writing your source file, Using the compiler - Examples - A simple example (with one source file) @subsubsection Compiling your program Compile the file @code{foo.scm}: @verbatim % csc foo.scm @end verbatim This will produce the @code{foo} executable: @verbatim % ls foo foo.scm @end verbatim @node Using the compiler - Examples - A simple example (with one source file) - Running your program, , Using the compiler - Examples - A simple example (with one source file) - Compiling your program, Using the compiler - Examples - A simple example (with one source file) @subsubsection Running your program To run your newly compiled executable use: @verbatim % foo 3628800 @end verbatim If you get a @code{foo: command not found} error, you might want to try with @code{./foo} instead (or, in Unix machines, modify your @code{PATH} environment variable to include your current directory). @node Using the compiler - Examples - An example with multiple files, , Using the compiler - Examples - A simple example (with one source file), Using the compiler - Examples @subsection An example with multiple files @menu * Using the compiler - Examples - An example with multiple files - Writing your source files:: * Using the compiler - Examples - An example with multiple files - Compiling and running your program:: @end menu If multiple bodies of Scheme code are to be combined into a single executable, then we have to compile each file and link the resulting object files together with the runtime system. Let's consider an example where your program consists of multiple source files. @node Using the compiler - Examples - An example with multiple files - Writing your source files, Using the compiler - Examples - An example with multiple files - Compiling and running your program, , Using the compiler - Examples - An example with multiple files @subsubsection Writing your source files The declarations in these files specify which of the compiled files is the main module, and which is the library module. An executable can only have one main module, since a program has only a single entry-point. In this case @code{foo.scm} is the main module, because it doesn't have a @code{unit} declaration: ;;; foo.scm @table @b @item The declaration marks this source file as dependant on the symbols provided @item by the bar unit @end table (declare (uses bar)) (write (fac 10)) (newline) @code{bar.scm} will be our library: ;;; bar.scm @table @b @item The declaration marks this source file as the bar unit. The names of the @item units and your files don't need to match. @end table (declare (unit bar)) (define (fac n) @verbatim (if (zero? n) 1 (* n (fac (- n 1))) ) ) @end verbatim @node Using the compiler - Examples - An example with multiple files - Compiling and running your program, , Using the compiler - Examples - An example with multiple files - Writing your source files, Using the compiler - Examples - An example with multiple files @subsubsection Compiling and running your program You should compile your two files with the following commands: @verbatim % csc -c bar.scm % csc -c foo.scm @end verbatim That should produce two files, @code{bar.o} and @code{foo.o}. They contain the code from your source files in compiled form. To link your compiled files use the following command: @verbatim % csc foo.o bar.o -o foo @end verbatim This should produce the @code{foo} executable, which you can run just as in the previous example. At this point you can also erase the @code{*.o} files. You could avoid one step and link the two files just as @code{foo.scm} is compiled: @verbatim % csc -c bar.scm % csc foo.scm bar.o -o foo @end verbatim Note that if you want to distribute your program, you might want it to follow the GNU Coding Standards. One relatively easy way to achieve this is to use Autoconf and Automake, two tools made for this specific purpose. @node Using the compiler - Extending the compiler, Using the compiler - Distributing compiled C files, Using the compiler - Examples, Using the compiler @section Extending the compiler The compiler supplies a couple of hooks to add user-level passes to the compilation process. Before compilation commences any Scheme source files or compiled code specified using the @code{-extend} option are loaded and evaluated. The parameters @code{user-options-pass, user-read-pass, user-preprocessor-pass, user-pass, user-pass-2} and @code{user-post-analysis-pass} can be set to procedures that are called to perform certain compilation passes instead of the usual processing (for more information about parameters see: @ref{Supported language, Supported language}. @table @b @item [parameter] user-options-pass Holds a procedure that will be called with a list of command-line arguments and should return two values: the source filename and the actual list of options, where compiler switches have their leading @code{-} (hyphen) removed and are converted to symbols. Note that this parameter is invoked @b{before} processing of the @code{-extend} option, and so can only be changed in compiled user passes. @item [parameter] user-read-pass Holds a procedure of three arguments. The first argument is a list of strings with the code passed to the compiler via @code{-prelude} options. The second argument is a list of source files including any files specified by @code{-prologue} and @code{-epilogue}. The third argument is a list of strings specified using @code{-postlude} options. The procedure should return a list of toplevel Scheme expressions. @item [parameter] user-preprocessor-pass Holds a procedure of one argument. This procedure is applied to each toplevel expression in the source file @b{before} macro-expansion. The result is macro-expanded and compiled in place of the original expression. @item [parameter] user-pass Holds a procedure of one argument. This procedure is applied to each toplevel expression @b{after} macro-expansion. The result of the procedure is then compiled in place of the original expression. @item [parameter] user-pass-2 Holds a procedure of three arguments, which is called with the canonicalized node-graph as its sole argument. The result is ignored, so this pass has to mutate the node-structure to cause any effect. @item [parameter] user-post-analysis-pass Holds a procedure that will be called after every performed program analysis pass. The procedure (when defined) will be called with seven arguments: a symbol indicating the analysis pass, the program database, the current node graph, a getter and a setter-procedure which can be used to access and manipulate the program database, which holds various information about the compiled program, a pass iteration count, and an analysis continuation flag. The getter procedure should be called with two arguments: a symbol representing the binding for which information should be retrieved, and a symbol that specifies the database-entry. The current value of the database entry will be returned or @code{#f}, if no such entry is available. The setter procedure is called with three arguments: the symbol and key and the new value. The pass iteration count currently is meaningful only for the 'opt pass. The analysis continuation flag will be @code{#f} for the last 'opt pass. For information about the contents of the program database contact the author. @end table Loaded code (via the @code{-extend} option) has access to the library units @code{extras, srfi-1, srfi-4, utils, regex} and the pattern matching macros. Multithreading is not available. Note that the macroexpansion/canonicalization phase of the compiler adds certain forms to the source program. These extra expressions are not seen by @code{user-preprocessor-pass} but by @code{user-pass}. @node Using the compiler - Distributing compiled C files, , Using the compiler - Extending the compiler, Using the compiler @section Distributing compiled C files It is relatively easy to create distributions of Scheme projects that have been compiled to C. The runtime system of CHICKEN consists of only two handcoded C files (@code{runtime.c} and @code{chicken.h}), plus the file @code{chicken-config.h}, which is generated by the build process. All other modules of the runtime system and the extension libraries are just compiled Scheme code. The following example shows a minimal application, which should run without changes on the most frequent operating systems, like Windows, Linux or FreeBSD: Let's take a simple "Hello, world!": ; hello.scm (print "Hello, world!") Compiled to C, we get @code{hello.c}. We need the files @code{chicken.h} and @code{runtime.c}, which contain the basic runtime system, plus the three basic library files @code{library.c}, @code{eval.c} and @code{extras.c} which contain the same functionality as the library linked into a plain CHICKEN-compiled application, or which is available by default in the interpreter, @code{csi}: @verbatim % csc hello.scm -O2 -d1 @end verbatim A simple makefile is needed as well: @enumerate @item Makefile for UNIX systems @end enumerate hello: hello.o runtime.o library.o eval.o extras.o @verbatim $(CC) -o hello hello.o runtime.o library.o eval.o extras.o -lm @end verbatim hello.o: chicken.h runtime.o: chicken.h library.o: chicken.h eval.o: chicken.h extras.o: chicken.h Now we have all files together, and can create an tarball containing all the files: @verbatim % tar cf hello.tar Makefile hello.c runtime.c library.c eval.c extras.c chicken.h % gzip hello.tar @end verbatim This is of naturally rather simplistic. Things like enabling dynamic loading, estimating the optimal stack-size and selecting supported features of the host system would need more configuration- and build-time support. All this can be addressed using more elaborate build-scripts, makefiles or by using autoconf/automake. Note also that the size of the application can still be reduced by removing @code{extras} and @code{eval} and compiling @code{hello.scm} with the @code{-explicit-use} option. For more information, study the CHICKEN source code and/or get in contact with the author. Previous: @ref{The User's Manual, The User's Manual} Next: @ref{Using the interpreter, Using the interpreter} @node Using the interpreter, Supported language, Using the compiler, Top @chapter Using the interpreter @menu * Using the interpreter - Interpreter command line format:: * Using the interpreter - Writing Scheme scripts:: * Using the interpreter - Toplevel commands:: * Using the interpreter - toplevel-command:: * Using the interpreter - History access:: * Using the interpreter - set-describer!:: * Using the interpreter - Auto-completion and edition:: * Using the interpreter - Accessing documentation:: @end menu CHICKEN provides an interpreter named @code{csi} for evaluating Scheme programs and expressions interactively. @node Using the interpreter - Interpreter command line format, Using the interpreter - Writing Scheme scripts, , Using the interpreter @section Interpreter command line format @code{csi @{FILENAME|OPTION}@} where @code{FILENAME} specifies a file with Scheme source-code. If the extension of the source file is @code{.scm}, it may be omitted. The runtime options described in @uref{http://galinha.ucpel.tche.br/Using%20the%20compiler#Compiler%20command%20line%20format, Compiler command line format} are also available for the interpreter. If the environment variable @code{CSI_OPTIONS} is set to a list of options, then these options are additionally passed to every direct or indirect invocation of @code{csi}. Please note that runtime options (like @code{-:...}) can not be passed using this method. The options recognized by the interpreter are: @table @b @item -- Ignore everything on the command-line following this marker. Runtime options (@code{-:...}) are still recognized. @item -i -case-insensitive Enables the reader to read symbols case insensitive. The default is to read case sensitive (in violation of R5RS). This option registers the @code{case-insensitive} feature identifier. @item -b -batch Quit the interpreter after processing all command line options. @item -e -eval EXPRESSIONS Evaluate @code{EXPRESSIONS}. This option implies @code{-batch} and @code{-quiet}, so no startup message will be printed and the interpreter exits after processing all @code{-eval} options and/or loading files given on the command-line. @item -D -feature SYMBOL Registers @code{SYMBOL} to be a valid feature identifier for @code{cond-expand}. @item -h -help Write a summary of the available command line options to standard output and exit. @item -I -include-path PATHNAME Specifies an alternative search-path for files included via the @code{include} special form. This option may be given multiple times. If the environment variable @code{CHICKEN_INCLUDE_PATH} is set, it should contain a list of alternative include pathnames separated by @code{;}. The environment variable @code{CHICKEN_HOME} is also considered as a search path. @item -k -keyword-style STYLE Enables alternative keyword syntax, where @code{STYLE} may be either @code{prefix} (as in Common Lisp) or @code{suffix} (as in DSSSL). Any other value is ignored. @item -n -no-init Do not load initialization-file. If this option is not given and the file @code{./.csirc} or @code{$HOME/.csirc} exists, then it is loaded before the read-eval-print loop commences. @item -w -no-warnings Disables any warnings that might be issued by the reader or evaluated code. @item -q -quiet Do not print a startup message. @item -s -script PATHNAME This is equivalent to @code{-batch -quiet -no-init PATHNAME}. Arguments following @code{PATHNAME} are available by using @code{command-line-arguments} and are not processed as interpreter options. Extra options in the environment variable @code{CSI_OPTIONS} are ignored. @item -ss PATHNAME The same as @code{-s PATHNAME} but invokes the procedure @code{main} with the value of @code{(command-line-arguments)} as its single argument. If the main procedure returns an integer result, then the interpreter is terminated, returning the integer as the status code back to the invoking process. Any other result terminates the interpreter with a zero exit status. @item -R -require-extension NAME Equivalent to evaluating @code{(require-extension NAME)}. @item -v -version Write the banner with version information to standard output and exit. @end table @node Using the interpreter - Writing Scheme scripts, Using the interpreter - Toplevel commands, Using the interpreter - Interpreter command line format, Using the interpreter @section Writing Scheme scripts Since UNIX shells use the @code{#!} notation for starting scripts, anything following the characters @code{#!} is ignored, with the exception of the special symbols @code{#!optional, #!key, #!rest} and @code{#!eof}. The easiest way is to use the @code{-script} option like this: @verbatim % cat foo #! /usr/local/bin/csi -script (print (eval (with-input-from-string (car (command-line-arguments)) read))) @end verbatim @verbatim % chmod +x foo % foo "(+ 3 4)" 7 @end verbatim The parameter @code{command-line-arguments} is set to a list of the parameters that were passed to the Scheme script. Scripts can be compiled to standalone executables (don't forget to declare used library units). CHICKEN supports writing shell scripts in Scheme for these platforms as well, using a slightly different approach. The first example would look like this on Windows: @verbatim C:>type foo.bat @@;csibatch %0 %1 %2 %3 %4 %5 %6 %7 %8 %9 (print (eval (with-input-from-string (car (command-line-arguments)) read))) @end verbatim @verbatim C:>foo "(+ 3 4)" 7 @end verbatim Like UNIX scripts, batch files can be compiled. Windows batch scripts do not accept more than 8 arguments. Since it is sometimes useful to run a script into the interpreter without actually running it (for example to test specific parts of it), the option @code{-ss} can be used as an alternative to @code{-script}. @code{-ss PATHNAME} is equivalent to @code{-script PATHNAME} but invokes @code{(main (command-line-arguments))} after loading all top-level forms of the script file. The result of @code{main} is returned as the exit status to the shell. Any non-numeric result exits with status zero: @verbatim % cat hi.scm (define (main args) (print "Hi, " (car args)) 0) % csi -ss hi.scm you Hi, you % csi -q #;1> ,l hi.scm #;2> (main (list "ye all")) Hi, ye all 0 #;3> @end verbatim @node Using the interpreter - Toplevel commands, Using the interpreter - toplevel-command, Using the interpreter - Writing Scheme scripts, Using the interpreter @section Toplevel commands The toplevel loop understands a number of special commands: @table @b @item ,? Show summary of available toplevel commands. @item ,l FILENAME ... Load files with given @code{FILENAME}s @item ,ln FILENAME ... Load files and print result(s) of each top-level expression. @item ,p EXP Pretty-print evaluated expression @code{EXP}. @item ,d EXP Describe result of evaluated expression @code{EXP}. @item ,du EXP Dump contents of the result of evaluated expression @code{EXP}. @item ,dur EXP N Dump @code{N} bytes of the result of evaluated expression @code{EXP}. @item ,exn Describes the last exception that occurred and adds it to the result history (it can be accessed using the @code{#} notation). @item ,q Quit the interpreter. @item ,r Show system information. @item ,s TEXT ... Execute shell-command. @item ,t EXP Evaluate form and print elapsed time. @item ,x EXP Pretty-print macroexpanded expression @code{EXP} (the expression is not evaluated). @item ,tr SYMBOL ... Enables tracing of the toplevel procedures with the given names. @end table @enumerate @item ;1> (fac 10) ==> 3628800 @item ;2> ,tr fac @item ;3> (fac 3) |(fac 3) | (fac 2) | (fac 1) | (fac 0) | fac -> 1 | fac -> 1 | fac -> 2 |fac -> 6 ==> 6 @item ;4> ,utr fac @item ;5> (fac 3) ==> 6 @end enumerate @table @b @item ,utr SYMBOL ... Disables tracing of the given toplevel procedures. @item ,br SYMBOL ... Sets a breakpoint at the procedures named @code{SYMBOL ...}. Breakpoint can also be trigged using the @code{breakpoint} procedure. @item ,ubr SYMBOL ... Removes breakpoints. @item ,c Continues execution from the last invoked breakpoint. @item ,breakall Enable breakpoints for all threads (this is the default). @item ,breakonly THREAD Enable breakpoints only for the thread returned by the expression @code{THREAD}. @item ,info Lists traced procedures and breakpoints. @item ,step EXPR Evaluates @code{EXPR} in single-stepping mode. On each procedure call you will be presented with a menu that allows stepping to the next call, leaving single-stepping mode or triggering a breakpoint. Note that you will see some internal calls, and unsafe or heavily optimized compiled code might not be stepped at all. Single-stepping mode is also possible by invoking the @code{singlestep} procedure. @end table You can define your own toplevel commands using the @code{toplevel-command} procedure: @node Using the interpreter - toplevel-command, Using the interpreter - History access, Using the interpreter - Toplevel commands, Using the interpreter @section toplevel-command @verbatim [procedure] (toplevel-command SYMBOL PROC [HELPSTRING]) @end verbatim Defines or redefines a toplevel interpreter command which can be invoked by entering @code{,SYMBOL}. @code{PROC} will be invoked when the command is entered and may read any required argument via @code{read} (or @code{read-line}). If the optional argument @code{HELPSTRING} is given, it will be listed by the @code{,?} command. @node Using the interpreter - History access, Using the interpreter - set-describer!, Using the interpreter - toplevel-command, Using the interpreter @section History access The interpreter toplevel accepts the special object @code{#[INDEX]} which returns the result of entry number @code{INDEX} in the history list. If the expression for that entry resulted in multiple values, the first result (or an unspecified value for no values) is returned. If no @code{INDEX} is given (and if a whitespace or closing paranthesis character follows the @code{#}, then the result of the last expression is returned. Note that the value returned is implicitly quoted. @node Using the interpreter - set-describer!, Using the interpreter - Auto-completion and edition, Using the interpreter - History access, Using the interpreter @section set-describer! @verbatim [procedure] (set-describer! TAG PROC) @end verbatim Sets a custom description handler that invokes @code{PROC} when the @code{,d} command is invoked with a record-type object that has the type @code{TAG} (a symbol). @code{PROC} is called with two arguments: the object to be described and an output-port. It should write a possibly useful textual description of the object to the passed output-port. For example: @verbatim #;1> (define-record point x y) #;2> (set-describer! 'point (lambda (pt o) (print "a point with x=" (point-x pt) " and y=" (point-y pt)))) #;3> ,d (make-point 1 2) a point with x=1 and y=2 @end verbatim @node Using the interpreter - Auto-completion and edition, Using the interpreter - Accessing documentation, Using the interpreter - set-describer!, Using the interpreter @section Auto-completion and edition On platforms that support it, it is possible to get auto-completion of symbols, history (over different @code{csi} sessions) and a more feature-full editor for the expressions you type using the @uref{http://www.call-with-current-continuation.org/eggs/readline.html, http://www.call-with-current-continuation.org/eggs/readline.html} egg by Tony Garnock Jones. It is very useful for interactive use of csi. To enable it install the egg and put this in your @code{~/.csirc} file: @verbatim (use readline regex) (current-input-port (make-gnu-readline-port)) (gnu-history-install-file-manager (string-append (or (getenv "HOME") ".") "/.csi.history")) @end verbatim More details are available in @uref{http://www.call-with-current-continuation.org/eggs/readline.html, the egg's documentation}. @node Using the interpreter - Accessing documentation, , Using the interpreter - Auto-completion and edition, Using the interpreter @section Accessing documentation You can access the manual directly from @code{csi} using the @uref{http://www.call-with-current-continuation.org/eggs/man.html, man} extension by Mario Domenech Goulart. To enable it install the egg and put this in your @code{~/.csirc} file: @verbatim (use man) (man:load) @end verbatim Then, in @code{csi}, you can search for definitions using @code{man:search} as in: @verbatim (man:search "case") @end verbatim Note that the search uses regular expressions. To view the documentation for one entry from the manual, use @code{man:help} as in: @verbatim (man:help "case-lambda") @end verbatim Note: Currently the documentation provided by the @code{man} extension corresponds to Chicken's 2.429, one of the last releases whose documentation was in the texinfo format (the format the @code{man} extension parses). Previous: @ref{Using the compiler, Using the compiler} Next: @ref{Supported language, Supported language} @node Supported language, Deviations from the standard, Using the interpreter, Top @chapter Supported language @itemize @item @ref{Deviations from the standard, Deviations from the standard} @item @ref{Extensions to the standard, Extensions to the standard} @item @ref{Non-standard read syntax, Non-standard read syntax} @item @ref{Non-standard macros and special forms, Non-standard macros and special forms} @item @ref{Pattern matching, Pattern matching} @item @ref{Declarations, Declarations} @item @ref{Parameters, Parameters} @item @ref{Unit library, Unit library} basic Scheme definitions @item @ref{Unit eval, Unit eval} evaluation and macro-handling @item @ref{Unit extras, Unit extras} useful utility definitions @item @ref{Unit srfi-1, Unit srfi-1} List Library @item @ref{Unit srfi-4, Unit srfi-4} Homogeneous numeric vectors @item @ref{Unit srfi-13, Unit srfi-13} String library @item @ref{Unit srfi-14, Unit srfi-14} character set library @item @ref{Unit match, Unit match} pattern matching runtime-support @item @ref{Unit regex, Unit regex} regular expressions @item @ref{Unit srfi-18, Unit srfi-18} multithreading @item @ref{Unit posix, Unit posix} Unix-like services @item @ref{Unit utils, Unit utils} Shell scripting and file operations @item @ref{Unit tcp, Unit tcp} basic TCP-sockets @item @ref{Unit lolevel, Unit lolevel} low-level operations @end itemize Previous: @ref{Using the interpreter, Using the interpreter} Next: @ref{Interface to external functions and variables, Interface to external functions and variables} @node Deviations from the standard, Extensions to the standard, Supported language, Top @chapter Deviations from the standard @itemize @item Identifiers are by default case-sensitive (see @uref{http://galinha.ucpel.tche.br:8080/Using%20the%20compiler#Compiler%20command%20line%20format, Compiler command line format}). @item [4.1.3] The maximal number of arguments that may be passed to a compiled procedure or macro is 120. A macro-definition that has a single rest-parameter can have any number of arguments. If the @code{libffi} library is available on this platform, and if it is installed, then CHICKEN can take advantage of this. See the @uref{http://chicken.wiki.br/chicken/README, README} file for more details. @item [4.2.2] @code{letrec} does evaluate the initial values for the bound variables sequentially and not in parallel, that is: @end itemize @verbatim (letrec ((x 1) (y 2)) (cons x y)) @end verbatim is equivalent to @verbatim (let ((x (void)) (y (void))) (set! x 1) (set! y 2) (cons x y) ) @end verbatim where R5RS requires @verbatim (let ((x (void)) (y (void))) (let ((tmp1 1) (tmp2 2)) (set! x tmp1) (set! y tmp2) (cons x y) ) ) @end verbatim @itemize @item [4.3] @code{syntax-rules} macros are not provided but available separately. @item [6.1] @code{equal?} compares all structured data recursively, while R5RS specifies that @code{eqv?} is used for data other than pairs, strings and vectors. @item [6.2.4] The runtime system uses the numerical string-conversion routines of the underlying C library and so does only understand standard (C-library) syntax for floating-point constants. @item [6.2.5] There is no built-in support for rationals, complex numbers or extended-precision integers (bignums). The routines @code{complex?}, @code{real?} and @code{rational?} are identical to the standard procedure @code{number?}. The procedures @code{numerator}, @code{denominator}, @code{rationalize}, @code{make-rectangular} and @code{make-polar} are not implemented. Fixnums are limited to ±230 (or ±262 on 64-bit hardware). Support for extended numbers is available as a separate package, provided the GNU multiprecision library is installed. @item [6.2.6] The procedure @code{string->number} does not obey read/write invariance on inexact numbers. @item [6.4] The maximum number of values that can be passed to continuations captured using @code{call-with-current-continuation} is 120. @item [6.5] Code evaluated in @code{scheme-report-environment} or @code{null-environment} still sees non-standard syntax. @item [6.6.2] The procedure @code{char-ready?} always returns @code{#t} for terminal ports. The procedure @code{read} does not obey read/write invariance on inexact numbers. @item [6.6.3] The procedures @code{write} and @code{display} do not obey read/write invariance to inexact numbers. @item [6.6.4] The @code{transcript-on} and @code{transcript-off} procedures are not implemented. @end itemize Previous: @ref{Supported language, Supported language} Next: @ref{Extensions to the standard, Extensions to the standard} @node Extensions to the standard, Non-standard read syntax, Deviations from the standard, Top @chapter Extensions to the standard [2.1] Identifiers may contain special characters if delimited with @code{| ... |}. [2.3] The brackets @code{[ ... ]} are provided as an alternative syntax for @code{( ... )}. A number of reader extensions is provided. See @ref{Non-standard read syntax, Non-standard read syntax}. [4] Numerous non-standard macros are provided. See @ref{Non-standard macros and special forms, Non-standard macros and special forms} for more information. [4.1.4] Extended DSSSL style lambda lists are supported. DSSSL formal argument lists are defined by the following grammar: @verbatim ==> * [(#!optional *)] [(#!rest )] [(#!key *)] ==> ==> | ( ) ==> ==> | ( ) ==> @end verbatim When a procedure is applied to a list of actual arguments, the formal and actual arguments are processed from left to right as follows: @itemize @item Variables in required-formal-arguments are bound to successive actual arguments starting with the first actual argument. It shall be an error if there are fewer actual arguments than required-formal-arguments. @item Next, variables in optional-formal-arguments are bound to any remaining actual arguments. If there are fewer remaining actual arguments than optional-formal-arguments, then variables are bound to the result of the evaluation of initializer if one was specified or otherwise to @code{#f}. The initializer is evaluated in an environment in which all previous formal arguments have been bound. @item If there is a rest-formal-argument, then it is bound to a list of all remaining actual arguments. The remaining actual arguments are also eligible to be bound to keyword-formal-arguments. If there is no rest-formal-argument and there are no keywords, the it shall be an error if there are any remaining actual arguments. @item If @code{#!key} was specified in the formal-argument-list, there shall be an even number of remaining actual arguments. These are interpreted as a series of pairs, where the first member of each pair is a keyword specifying the argument name, and th corresponding value. It shall be an error if the first member of a pair is not a keyword. It shall be an error if the argument name is not the same as a variable in a keyword-formal-argument, unless there is a rest-formal-argument. If the same argument name occurs more than once in the list of actual arguments, then the first value is used. If there is no actual argument for a particular keyword-formal-argument, then the variable is bound to the result of evaluating initializer if one was specified or @code{#f}. The initializer is evaluated in an environment in which all previous formal arguments have been bound. @end itemize It shall be an error for an @code{} to appear more than once in a formal-argument-list. Example: @verbatim ((lambda x x) 3 4 5 6) => (3 4 5 6) ((lambda (x y #!rest z) z) 3 4 5 6) => (5 6) ((lambda (x y #!optional z #!rest r #!key i (j 1)) (list x y z i: i j: j)) 3 4 5 i: 6 i: 7) => (3 4 5 i: 6 j: 1) @end verbatim [4.1.6] @code{set!} for unbound toplevel variables is allowed. @code{set! (PROCEDURE ...) ...)} is supported, as CHICKEN implements @uref{http://srfi.schemers.org/srfi-17/srfi-17.html, SRFI-17}. [4.2.1] The @code{cond} form supports @uref{http://srfi.schemers.org/srfi-61, SRFI-61}. [4.2.2] It is allowed for initialization values of bindings in a @code{letrec} construct to refer to previous variables in the same set of bindings, so @verbatim (letrec ((foo 123) (bar foo) ) bar) @end verbatim is allowed and returns @code{123}. [4.2.3] @code{(begin)} is allowed in non-toplevel contexts and evaluates to an unspecified value. [4.2.5] Delayed expressions may return multiple values. [5.2.2] CHICKEN extends standard semantics by allowing internal definitions everywhere, and not only at the beginning of a body. A set of internal definitions is equivalent to a @code{letrec} form enclosing all following expressions in the body: @verbatim (let ((foo 123)) (bar) (define foo 456) (baz foo) ) @end verbatim expands into @verbatim (let ((foo 123)) (bar) (letrec ((foo 456)) (baz foo) ) ) @end verbatim [5.2] @code{define} with a single argument is allowed and initializes the toplevel or local binding to an unspecified value. CHICKEN supports @emph{curried} definitions, where the variable name may also be a list specifying a name and a nested lambda list. So @verbatim (define ((make-adder x) y) (+ x y)) @end verbatim is equivalent to @verbatim (define (make-adder x) (lambda (y) (+ x y))) @end verbatim [6] CHICKEN provides numerous non-standard procedures. See the manual sections on library units for more information. [6.2.4] The special IEEE floating-point numbers @emph{+nan}, @emph{+inf} and @emph{-inf} are supported, as is negative zero. [6.3.4] User defined character names are supported. See @code{char-name}. Characters can be given in hexadecimal notation using the @emph{#\xXX} syntax where @emph{XX} specifies the character code. Character codes above 255 are supported and can be read (and are written) using the @emph{#\uXXXX} and @emph{#\UXXXXXXXX} notations. Non-standard characters names supported are @code{#\tab}, @code{#\linefeed}, @code{#\return}, @code{#\alarm}, @code{#\vtab}, @code{#\nul}, @code{#\page}, @code{#\esc}, @code{#\delete} and @code{#\backspace}. [6.3.5] CHICKEN supports special characters preceded with a backslash @emph{\} in quoted string constants. @emph{\n} denotes the newline-character, @emph{\r} carriage return, @emph{\b} backspace, @emph{\t} TAB, @emph{\v} vertical TAB, @emph{\a} alarm, @emph{\f} formfeed, @emph{\xXX} a character with the code @code{XX} in hex and @emph{\uXXXX} (and @emph{\UXXXXXXXX}) a unicode character with the code @code{XXXX}. The latter is encoded in UTF-8 format. The third argument to @code{substring} is optional and defaults to the length of the string. [6.4] @code{force} called with an argument that is not a promise returns that object unchanged. Captured continuations can be safely invoked inside before- and after-thunks of a @code{dynamic-wind} form and execute in the outer dynamic context of the @code{dynamic-wind} form. @b{Implicit} non-multival continuations accept multiple values by discarding all but the first result. Zero values result in the continuation receiving an unspecified value. Note that this slight relaxation of the behaviour of returning mulitple values to non-multival continuations does not apply to explicit continuations (created with @code{call-with-current-continuation}). [6.5] The second argument to @code{eval} is optional and defaults to the value of @code{(interaction-environment)}. @code{scheme-report-environment} and @code{null-environment} accept an optional 2nd parameter: if not @code{#f} (which is the default), toplevel bindings to standard procedures are mutable and new toplevel bindings may be introduced. [6.6] The @emph{tilde} character (@code{~}) is automatically expanded in pathnames. Additionally, if a pathname starts with @code{$VARIABLE...}, then the prefix is replaced by the value of the given environment variable. [6.6.1] if the procedures @code{current-input-port} and @code{current-output-port} are called with an argument (which should be a port), then that argument is selected as the new current input- and output-port, respectively. The procedures @code{open-input-file}, @code{open-output-file}, @code{with-input-from-file}, @code{with-output-to-file}, @code{call-with-input-file} and @code{call-with-output-file} accept an optional second (or third) argument which should be one or more keywords, if supplied. These arguments specify the mode in which the file is opened. Possible values are the keywords @code{#:text}, @code{#:binary} or @code{#:append}. Previous: @ref{Deviations from the standard, Deviations from the standard} Next: @ref{Non-standard read syntax, Non-standard read syntax} @node Non-standard read syntax, Non-standard macros and special forms, Extensions to the standard, Top @chapter Non-standard read syntax @menu * Non-standard read syntax - Multiline Block Comment:: * Non-standard read syntax - Expression Comment:: * Non-standard read syntax - External Representation:: * Non-standard read syntax - Syntax Expression:: * Non-standard read syntax - Location Expression:: * Non-standard read syntax - Keyword:: * Non-standard read syntax - Multiline String Constant:: * Non-standard read syntax - Multiline String Constant with Embedded Expressions:: * Non-standard read syntax - Foreign Declare:: * Non-standard read syntax - Sharp Prefixed Symbol:: * Non-standard read syntax - Bang:: * Non-standard read syntax - Case Sensitive Expression:: * Non-standard read syntax - Case Insensitive Expression:: * Non-standard read syntax - Conditional Expansion:: @end menu @node Non-standard read syntax - Multiline Block Comment, Non-standard read syntax - Expression Comment, , Non-standard read syntax @section Multiline Block Comment @verbatim #| ... |# @end verbatim A multiline @emph{block} comment. May be nested. Implements @uref{http://srfi.schemers.org/srfi-30/srfi-30.html, SRFI-30} @node Non-standard read syntax - Expression Comment, Non-standard read syntax - External Representation, Non-standard read syntax - Multiline Block Comment, Non-standard read syntax @section Expression Comment @verbatim #;EXPRESSION @end verbatim Treats @code{EXPRESSION} as a comment. @node Non-standard read syntax - External Representation, Non-standard read syntax - Syntax Expression, Non-standard read syntax - Expression Comment, Non-standard read syntax @section External Representation @verbatim #,(CONSTRUCTORNAME DATUM ...) @end verbatim Allows user-defined extension of external representations. (For more information see the documentation for @uref{http://srfi.schemers.org/srfi-10/srfi-10.html, SRFI-10}) @node Non-standard read syntax - Syntax Expression, Non-standard read syntax - Location Expression, Non-standard read syntax - External Representation, Non-standard read syntax @section Syntax Expression @verbatim #'EXPRESSION @end verbatim An abbreviation for @code{(syntax EXPRESSION)}. @node Non-standard read syntax - Location Expression, Non-standard read syntax - Keyword, Non-standard read syntax - Syntax Expression, Non-standard read syntax @section Location Expression @verbatim #$EXPRESSION @end verbatim An abbreviation for @code{(location EXPRESSION)}. @node Non-standard read syntax - Keyword, Non-standard read syntax - Multiline String Constant, Non-standard read syntax - Location Expression, Non-standard read syntax @section Keyword @verbatim #:SYMBOL @end verbatim Syntax for keywords. Keywords are symbols that evaluate to themselves, and as such don't have to be quoted. @node Non-standard read syntax - Multiline String Constant, Non-standard read syntax - Multiline String Constant with Embedded Expressions, Non-standard read syntax - Keyword, Non-standard read syntax @section Multiline String Constant @verbatim #< #(+ three 99) (three is "#@{three@}") EOF ) @end verbatim prints @verbatim This is a simple string with an embedded `#' character and substituted expressions: (+ three 99) ==> 102 (three is "3") @end verbatim @node Non-standard read syntax - Foreign Declare, Non-standard read syntax - Sharp Prefixed Symbol, Non-standard read syntax - Multiline String Constant with Embedded Expressions, Non-standard read syntax @section Foreign Declare @verbatim #> ... <# @end verbatim Abbreviation for @code{foreign-declare " ... ")}. @node Non-standard read syntax - Sharp Prefixed Symbol, Non-standard read syntax - Bang, Non-standard read syntax - Foreign Declare, Non-standard read syntax @section Sharp Prefixed Symbol @verbatim #%... @end verbatim Reads like a normal symbol. @node Non-standard read syntax - Bang, Non-standard read syntax - Case Sensitive Expression, Non-standard read syntax - Sharp Prefixed Symbol, Non-standard read syntax @section Bang @menu * Non-standard read syntax - Bang - Line Comment:: * Non-standard read syntax - Bang - Eof Object:: * Non-standard read syntax - Bang - DSSSL Formal Parameter List Annotation:: * Non-standard read syntax - Bang - Read Mark Invocation:: @end menu @verbatim #!... @end verbatim Interpretation depends on the directly following characters. Only the following are recognized. Any other case results in a read error. @node Non-standard read syntax - Bang - Line Comment, Non-standard read syntax - Bang - Eof Object, , Non-standard read syntax - Bang @subsection Line Comment @itemize @item If followed by whitespace or a slash, then everything up the end of the current line is ignored @end itemize @node Non-standard read syntax - Bang - Eof Object, Non-standard read syntax - Bang - DSSSL Formal Parameter List Annotation, Non-standard read syntax - Bang - Line Comment, Non-standard read syntax - Bang @subsection Eof Object @itemize @item If followed by the character sequence @code{eof}, then the (self-evaluating) end-of-file object is returned @end itemize @node Non-standard read syntax - Bang - DSSSL Formal Parameter List Annotation, Non-standard read syntax - Bang - Read Mark Invocation, Non-standard read syntax - Bang - Eof Object, Non-standard read syntax - Bang @subsection DSSSL Formal Parameter List Annotation @itemize @item If followed by any of the character sequences @code{optional}, @code{rest} or @code{key}, then a symbol with the same name (and prefixed with @code{#!}) is returned @end itemize @node Non-standard read syntax - Bang - Read Mark Invocation, , Non-standard read syntax - Bang - DSSSL Formal Parameter List Annotation, Non-standard read syntax - Bang @subsection Read Mark Invocation @itemize @item If a @emph{read mark} with the same name as the token is registered, then its procedure is called and the result of the read-mark procedure will be returned @end itemize @node Non-standard read syntax - Case Sensitive Expression, Non-standard read syntax - Case Insensitive Expression, Non-standard read syntax - Bang, Non-standard read syntax @section Case Sensitive Expression @verbatim #cs... @end verbatim Read the next expression in case-sensitive mode (regardless of the current global setting). @node Non-standard read syntax - Case Insensitive Expression, Non-standard read syntax - Conditional Expansion, Non-standard read syntax - Case Sensitive Expression, Non-standard read syntax @section Case Insensitive Expression @verbatim #ci... @end verbatim Read the next expression in case-insensitive mode (regardless of the current global setting). @node Non-standard read syntax - Conditional Expansion, , Non-standard read syntax - Case Insensitive Expression, Non-standard read syntax @section Conditional Expansion @verbatim #+FEATURE EXPR @end verbatim Equivalent to @verbatim (cond-expand (FEATURE EXPR) (else)) @end verbatim Previous: @ref{Extensions to the standard, Extensions to the standard} Next: @ref{Non-standard macros and special forms, Non-standard macros and special forms} @node Non-standard macros and special forms, Pattern matching, Non-standard read syntax, Top @chapter Non-standard macros and special forms @menu * Non-standard macros and special forms - Making extra libraries and extensions availablee:: * Non-standard macros and special forms - Binding forms for optional arguments:: * Non-standard macros and special forms - Other binding forms:: * Non-standard macros and special forms - Substitution forms and macros:: * Non-standard macros and special forms - Conditional forms:: * Non-standard macros and special forms - Record structures:: * Non-standard macros and special forms - Other forms:: @end menu @node Non-standard macros and special forms - Making extra libraries and extensions availablee, Non-standard macros and special forms - Binding forms for optional arguments, , Non-standard macros and special forms @section Making extra libraries and extensions availablee @menu * Non-standard macros and special forms - Making extra libraries and extensions availablee - require-extension:: * Non-standard macros and special forms - Making extra libraries and extensions availablee - define-extension:: @end menu @node Non-standard macros and special forms - Making extra libraries and extensions availablee - require-extension, Non-standard macros and special forms - Making extra libraries and extensions availablee - define-extension, , Non-standard macros and special forms - Making extra libraries and extensions availablee @subsection require-extension @verbatim [syntax] (require-extension ID ...) [syntax] (use ID ...) @end verbatim This form does all necessary steps to make the libraries or extensions given in @code{ID ...} available. It loads syntactic extension, if needed and generates code for loading/linking with core library modules or separately installed extensions. @code{use} is just a shorter alias for @code{require-extension}. This implementation of @code{require-extension} is compliant to @uref{http://srfi.schemers.org/srfi-55/srfi-55.html, SRFI-55} (see the @uref{http://srfi.schemers.org/srfi-55/srfi-55.html, SRFI-55} document for more information). During interpretation/evaluation @code{require-extension} performs one of the following: @itemize @item If @code{ID} names a built-in feature @code{chicken srfi-0 srfi-2 srfi-6 srfi-8 srfi-9 srfi-10 srfi-17 srfi-23 srfi-30 srfi-39 srfi-55}, then nothing is done. @item If @code{ID} names one of the syntactic extensions @code{chicken-more-macros chicken-ffi-macros}, then this extension will be loaded. @item @code{ID} names one of the core library units shipped with CHICKEN, then a @code{(load-library 'ID)} will be performed. @item @code{ID} names an installed extension with the @code{syntax} or @code{require-at-runtime} attribute, then the equivalent of @code{(require-for-syntax 'ID)} is performed, probably followed by @code{(require ...)} for any run-time requirements. @item Otherwise @code{(require-extension ID)} is equivalent to @code{(require 'ID)}. @end itemize During compilation one of the following happens instead: @itemize @item If @code{ID} names a built-in feature @code{chicken srfi-0 srfi-2 srfi-6 srfi-8 srfi-9 srfi-10 srfi-17 srfi-23 srfi-30 srfi-39 srfi-55}, then nothing is done. @item If @code{ID} names one of the syntactic extensions @code{chicken-more-macros chicken-ffi-macros}, then this extension will be loaded at compile-time, making the syntactic extensions available in compiled code. @item If @code{ID} names one of the core library units shipped with CHICKEN, or if the option @code{-uses ID} has been passed to the compiler then a @code{(declare (uses ID))} is generated. @item If @code{ID} names an installed extension with the @code{syntax} or @code{require-at-runtime} attribute, then the equivalent of @code{(require-for-syntax 'ID)} is performed, and code is emitted to @code{(require ...)} any needed run-time requirements. @item Otherwise @code{(require-extension ID)} is equivalent to @code{(require 'ID)}. @end itemize To make long matters short - just use @code{require-extension} and it will normally figure everything out for dynamically loadable extensions and core library units. @code{ID} should be a pure extension name and should not contain any path prefixes (for example @code{dir/lib...}) is illegal). @code{ID} may also be a list that designates an extension-specifier. Currently the following extension specifiers are defined: @itemize @item @code{(srfi NUMBER ...)} is required for SRFI-55 compatibility and is fully implemented @item @code{(version ID NUMBER)} is equivalent to @code{ID}, but checks at compile-time whether the extension named @code{ID} is installed and whether its version is equal or higher than @code{NUMBER}. @code{NUMBER} may be a string or a number, the comparison is done lexicographically (using @code{string>=?}). @end itemize See also: @code{set-extension-specifier!} When syntax extensions are loaded that redefine the global toplevel macro-expander (for example the @uref{http://www.call-with-current-continuation.org/eggs/syntax-case.html, syntax-case} extension), then all remaining expression @emph{in the same toplevel form} are still expanded with the old toplevel macro-expander. @node Non-standard macros and special forms - Making extra libraries and extensions availablee - define-extension, , Non-standard macros and special forms - Making extra libraries and extensions availablee - require-extension, Non-standard macros and special forms - Making extra libraries and extensions availablee @subsection define-extension @verbatim [syntax] (define-extension NAME CLAUSE ...) @end verbatim This macro simplifies the task of writing extensions that can be linked both statically and dynamically. If encountered in interpreted code or code that is compiled into a shared object (specifically if compiled with the feature @code{chicken-compile-shared}, done automatically by @code{csc} when compiling with the @code{-shared} or @code{-dynamic} option) then the code given by clauses of the form (dynamic EXPRESSION ...) are inserted into the output as a @code{begin} form. If compiled statically (specifically if the feature @code{chicken-compile-shared} has not been given), then this form expands into the following: (declare (unit NAME)) (provide 'NAME) and all clauses of the form (static EXPRESSION ...) all additionally inserted into the expansion. As a convenience, the clause (export IDENTIFIER ...) is also allowed and is identical to @code{(declare (export IDENTIFIER ...))} (unless the @code{define-extension} form occurs in interpreted code, in with it is simply ignored). Note that the compiler option @code{-extension NAME} is equivalent to prefixing the compiled file with (define-extension NAME) @node Non-standard macros and special forms - Binding forms for optional arguments, Non-standard macros and special forms - Other binding forms, Non-standard macros and special forms - Making extra libraries and extensions availablee, Non-standard macros and special forms @section Binding forms for optional arguments @menu * Non-standard macros and special forms - Binding forms for optional arguments - optional:: * Non-standard macros and special forms - Binding forms for optional arguments - case-lambda:: * Non-standard macros and special forms - Binding forms for optional arguments - let-optionals:: * Non-standard macros and special forms - Binding forms for optional arguments - let-optionals*:: @end menu @node Non-standard macros and special forms - Binding forms for optional arguments - optional, Non-standard macros and special forms - Binding forms for optional arguments - case-lambda, , Non-standard macros and special forms - Binding forms for optional arguments @subsection optional @verbatim [syntax] (optional ARGS DEFAULT) @end verbatim Use this form for procedures that take a single optional argument. If @code{ARGS} is the empty list @code{DEFAULT} is evaluated and returned, otherwise the first element of the list @code{ARGS}. It is an error if @code{ARGS} contains more than one value. (define (incr x . i) (+ x (optional i 1))) (incr 10) ==> 11 (incr 12 5) ==> 17 @node Non-standard macros and special forms - Binding forms for optional arguments - case-lambda, Non-standard macros and special forms - Binding forms for optional arguments - let-optionals, Non-standard macros and special forms - Binding forms for optional arguments - optional, Non-standard macros and special forms - Binding forms for optional arguments @subsection case-lambda @verbatim [syntax] (case-lambda (LAMBDA-LIST1 EXP1 ...) ...) @end verbatim Expands into a lambda that invokes the body following the first matching lambda-list. (define plus @verbatim (case-lambda (() 0) ((x) x) ((x y) (+ x y)) ((x y z) (+ (+ x y) z)) (args (apply + args)))) @end verbatim (plus) ==> 9 (plus 1) ==> 1 (plus 1 2 3) ==> 6 For more information see the documentation for @uref{http://srfi.schemers.org/srfi-16/srfi-16.html, SRFI-16} @node Non-standard macros and special forms - Binding forms for optional arguments - let-optionals, Non-standard macros and special forms - Binding forms for optional arguments - let-optionals*, Non-standard macros and special forms - Binding forms for optional arguments - case-lambda, Non-standard macros and special forms - Binding forms for optional arguments @subsection let-optionals @verbatim [syntax] (let-optionals ARGS ((VAR1 DEFAULT1) ...) BODY ...) @end verbatim Binding constructs for optional procedure arguments. @code{ARGS} should be a rest-parameter taken from a lambda-list. @code{let-optionals} binds @code{VAR1 ...} to available arguments in parallel, or to @code{DEFAULT1 ...} if not enough arguments were provided. @code{let-optionals*} binds @code{VAR1 ...} sequentially, so every variable sees the previous ones. it is an error if any excess arguments are provided. (let-optionals '(one two) ((a 1) (b 2) (c 3)) @verbatim (list a b c) ) ==> (one two 3) @end verbatim @node Non-standard macros and special forms - Binding forms for optional arguments - let-optionals*, , Non-standard macros and special forms - Binding forms for optional arguments - let-optionals, Non-standard macros and special forms - Binding forms for optional arguments @subsection let-optionals* @verbatim [syntax] (let-optionals* ARGS ((VAR1 DEFAULT1) ... [RESTVAR]) BODY ...) @end verbatim Binding constructs for optional procedure arguments. @code{ARGS} should be a rest-parameter taken from a lambda-list. @code{let-optionals} binds @code{VAR1 ...} to available arguments in parallel, or to @code{DEFAULT1 ...} if not enough arguments were provided. @code{let-optionals*} binds @code{VAR1 ...} sequentially, so every variable sees the previous ones. If a single variable @code{RESTVAR} is given, then it is bound to any remaining arguments, otherwise it is an error if any excess arguments are provided. (let-optionals* '(one two) ((a 1) (b 2) (c a)) @verbatim (list a b c) ) ==> (one two one) @end verbatim @node Non-standard macros and special forms - Other binding forms, Non-standard macros and special forms - Substitution forms and macros, Non-standard macros and special forms - Binding forms for optional arguments, Non-standard macros and special forms @section Other binding forms @menu * Non-standard macros and special forms - Other binding forms - and-let*:: * Non-standard macros and special forms - Other binding forms - rec:: * Non-standard macros and special forms - Other binding forms - cut:: * Non-standard macros and special forms - Other binding forms - define-values:: * Non-standard macros and special forms - Other binding forms - fluid-let:: * Non-standard macros and special forms - Other binding forms - let-values:: * Non-standard macros and special forms - Other binding forms - let*-values:: * Non-standard macros and special forms - Other binding forms - letrec-values:: * Non-standard macros and special forms - Other binding forms - parameterize:: * Non-standard macros and special forms - Other binding forms - receive:: * Non-standard macros and special forms - Other binding forms - set!-values:: @end menu @node Non-standard macros and special forms - Other binding forms - and-let*, Non-standard macros and special forms - Other binding forms - rec, , Non-standard macros and special forms - Other binding forms @subsection and-let* @verbatim [syntax] (and-let* (BINDING ...) EXP1 EXP2 ...) @end verbatim SRFI-2. Bind sequentially and execute body. @code{BINDING} can be a list of a variable and an expression, a list with a single expression, or a single variable. If the value of an expression bound to a variable is @code{#f}, the @code{and-let*} form evaluates to @code{#f} (and the subsequent bindings and the body are not executed). Otherwise the next binding is performed. If all bindings/expressions evaluate to a true result, the body is executed normally and the result of the last expression is the result of the @code{and-let*} form. See also the documentation for @uref{http://srfi.schemers.org/srfi-2/srfi-2.html, SRFI-2}. @node Non-standard macros and special forms - Other binding forms - rec, Non-standard macros and special forms - Other binding forms - cut, Non-standard macros and special forms - Other binding forms - and-let*, Non-standard macros and special forms - Other binding forms @subsection rec @verbatim [syntax] (rec NAME EXPRESSION) [syntax] (rec (NAME VARIABLE ...) BODY ...) @end verbatim Allows simple definition of recursive definitions. @code{(rec NAME EXPRESSION)} is equivalent to @code{(letrec ((NAME EXPRESSION)) NAME)} and @code{(rec (NAME VARIABLE ...) BODY ...)} is the same as @code{(letrec ((NAME (lambda (VARIABLE ...) BODY ...))) NAME)}. @node Non-standard macros and special forms - Other binding forms - cut, Non-standard macros and special forms - Other binding forms - define-values, Non-standard macros and special forms - Other binding forms - rec, Non-standard macros and special forms - Other binding forms @subsection cut @verbatim [syntax] (cut SLOT ...) [syntax] (cute SLOT ...) @end verbatim @uref{http://srfi.schemers.org/srfi-26/srfi-26.html, Syntactic sugar for specializing parameters}. @node Non-standard macros and special forms - Other binding forms - define-values, Non-standard macros and special forms - Other binding forms - fluid-let, Non-standard macros and special forms - Other binding forms - cut, Non-standard macros and special forms - Other binding forms @subsection define-values @verbatim [syntax] (define-values (NAME ...) EXP) @end verbatim Defines several variables at once, with the result values of expression @code{EXP}. @node Non-standard macros and special forms - Other binding forms - fluid-let, Non-standard macros and special forms - Other binding forms - let-values, Non-standard macros and special forms - Other binding forms - define-values, Non-standard macros and special forms - Other binding forms @subsection fluid-let @verbatim [syntax] (fluid-let ((VAR1 X1) ...) BODY ...) @end verbatim Binds the variables @code{VAR1 ...} dynamically to the values @code{X1 ...} during execution of @code{BODY ...}. @node Non-standard macros and special forms - Other binding forms - let-values, Non-standard macros and special forms - Other binding forms - let*-values, Non-standard macros and special forms - Other binding forms - fluid-let, Non-standard macros and special forms - Other binding forms @subsection let-values @verbatim [syntax] (let-values (((NAME ...) EXP) ...) BODY ...) @end verbatim Binds multiple variables to the result values of @code{EXP ...}. All variables are bound simultaneously. @node Non-standard macros and special forms - Other binding forms - let*-values, Non-standard macros and special forms - Other binding forms - letrec-values, Non-standard macros and special forms - Other binding forms - let-values, Non-standard macros and special forms - Other binding forms @subsection let*-values @verbatim [syntax] (let*-values (((NAME ...) EXP) ...) BODY ...) @end verbatim Binds multiple variables to the result values of @code{EXP ...}. The variables are bound sequentially. (let*-values (((a b) (values 2 3)) @verbatim ((p) (+ a b)) ) p) ==> 5 @end verbatim @node Non-standard macros and special forms - Other binding forms - letrec-values, Non-standard macros and special forms - Other binding forms - parameterize, Non-standard macros and special forms - Other binding forms - let*-values, Non-standard macros and special forms - Other binding forms @subsection letrec-values @verbatim [syntax] (letrec-values (((NAME ...) EXP) ...) BODY ...) @end verbatim Binds the result values of @code{EXP ...} to multiple variables at once. All variables are mutually recursive. (letrec-values (((odd even) @verbatim (values (lambda (n) (if (zero? n) #f (even (sub1 n)))) (lambda (n) (if (zero? n) #t (odd (sub1 n)))) ) ) ) (odd 17) ) ==> #t @end verbatim @node Non-standard macros and special forms - Other binding forms - parameterize, Non-standard macros and special forms - Other binding forms - receive, Non-standard macros and special forms - Other binding forms - letrec-values, Non-standard macros and special forms - Other binding forms @subsection parameterize @verbatim [syntax] (parameterize ((PARAMETER1 X1) ...) BODY ...) @end verbatim Binds the parameters @code{PARAMETER1 ...} dynamically to the values @code{X1 ...} during execution of @code{BODY ...}. (see also: @code{make-parameter} in @ref{Parameters, Parameters}). Note that @code{PARAMETER} may be any expression that evaluates to a parameter procedure. @node Non-standard macros and special forms - Other binding forms - receive, Non-standard macros and special forms - Other binding forms - set!-values, Non-standard macros and special forms - Other binding forms - parameterize, Non-standard macros and special forms - Other binding forms @subsection receive @verbatim [syntax] (receive (NAME1 ... [. NAMEn]) VALUEEXP BODY ...) [syntax] (receive VALUEEXP) @end verbatim SRFI-8. Syntactic sugar for @code{call-with-values}. Binds variables to the result values of @code{VALUEEXP} and evaluates @code{BODY ...}. The syntax (receive VALUEEXP) is equivalent to (receive _ VALUEEXP _) @node Non-standard macros and special forms - Other binding forms - set!-values, , Non-standard macros and special forms - Other binding forms - receive, Non-standard macros and special forms - Other binding forms @subsection set!-values @verbatim [syntax] (set!-values (NAME ...) EXP) @end verbatim Assigns the result values of expression @code{EXP} to multiple variables. @node Non-standard macros and special forms - Substitution forms and macros, Non-standard macros and special forms - Conditional forms, Non-standard macros and special forms - Other binding forms, Non-standard macros and special forms @section Substitution forms and macros @menu * Non-standard macros and special forms - Substitution forms and macros - define-constant:: * Non-standard macros and special forms - Substitution forms and macros - define-inline:: * Non-standard macros and special forms - Substitution forms and macros - define-macro:: * Non-standard macros and special forms - Substitution forms and macros - define-for-syntax:: @end menu @node Non-standard macros and special forms - Substitution forms and macros - define-constant, Non-standard macros and special forms - Substitution forms and macros - define-inline, , Non-standard macros and special forms - Substitution forms and macros @subsection define-constant @verbatim [syntax] (define-constant NAME CONST) @end verbatim Define a variable with a constant value, evaluated at compile-time. Any reference to such a constant should appear textually @b{after} its definition. This construct is equivalent to @code{define} when evaluated or interpreted. Constant definitions should only appear at toplevel. Note that constants are local to the current compilation unit and are not available outside of the source file in which they are defined. Names of constants still exist in the Scheme namespace and can be lexically shadowed. If the value is mutable, then the compiler is careful to preserve its identity. @code{CONST} may be any constant expression, and may also refer to constants defined via @code{define-constant} previously. This for should only be used at top-level. @node Non-standard macros and special forms - Substitution forms and macros - define-inline, Non-standard macros and special forms - Substitution forms and macros - define-macro, Non-standard macros and special forms - Substitution forms and macros - define-constant, Non-standard macros and special forms - Substitution forms and macros @subsection define-inline @verbatim [syntax] (define-inline (NAME VAR ... [. VAR]) BODY ...) [syntax] (define-inline NAME EXP) @end verbatim Defines an inline procedure. Any occurrence of @code{NAME} will be replaced by @code{EXP} or @code{(lambda (VAR ... [. VAR]) BODY ...)}. This is similar to a macro, but variable-names and -scope will be correctly handled. Inline substitutions take place @b{after} macro-expansion. @code{EXP} should be a lambda-expression. Any reference to @code{NAME} should appear textually @b{after} its definition. Note that inline procedures are local to the current compilation unit and are not available outside of the source file in which they are defined. Names of inline procedures still exist in the Scheme namespace and can be lexically shadowed. This construct is equivalent to @code{define} when evaluated or interpreted. Inline definitions should only appear at toplevel. @node Non-standard macros and special forms - Substitution forms and macros - define-macro, Non-standard macros and special forms - Substitution forms and macros - define-for-syntax, Non-standard macros and special forms - Substitution forms and macros - define-inline, Non-standard macros and special forms - Substitution forms and macros @subsection define-macro @verbatim [syntax] (define-macro (NAME VAR ... [. VAR]) EXP1 ...) [syntax] (define-macro NAME (lambda (VAR ... [. VAR]) EXP1 ...)) [syntax] (define-macro NAME1 NAME2) @end verbatim Define a globally visible macro special form. The macro is available as soon as it is defined, i.e. it is registered at compile-time. If the file containing this definition invokes @code{eval} and the declaration @code{run-time-macros} (or the command line option @code{-run-time-macros}) has been used, then the macro is visible in evaluated expressions during runtime. The second possible syntax for @code{define-macro} is allowed for portability purposes only. In this case the second argument @b{must} be a lambda-expression or a macro name. Only global macros can be defined using this form. @code{(define-macro NAME1 NAME2)} simply copies the macro definition from @code{NAME2} to @code{NAME1}, creating an alias. Extended lambda list syntax (@code{#!optional}, etc.) can be used but note that arguments are source expressions and thus default values for optional or keyword arguments should take this into consideration. @node Non-standard macros and special forms - Substitution forms and macros - define-for-syntax, , Non-standard macros and special forms - Substitution forms and macros - define-macro, Non-standard macros and special forms - Substitution forms and macros @subsection define-for-syntax @verbatim [syntax] (define-for-syntax (NAME VAR ... [. VAR]) EXP1 ...) [syntax] (define-for-syntax NAME [VALUE]) @end verbatim Defines the toplevel variable @code{NAME} at macro-expansion time. This can be helpful when you want to define support procedures for use in macro-transformers, for example. @node Non-standard macros and special forms - Conditional forms, Non-standard macros and special forms - Record structures, Non-standard macros and special forms - Substitution forms and macros, Non-standard macros and special forms @section Conditional forms @menu * Non-standard macros and special forms - Conditional forms - select:: * Non-standard macros and special forms - Conditional forms - unless:: * Non-standard macros and special forms - Conditional forms - when:: @end menu @node Non-standard macros and special forms - Conditional forms - select, Non-standard macros and special forms - Conditional forms - unless, , Non-standard macros and special forms - Conditional forms @subsection select @verbatim [syntax] (select EXP ((KEY ...) EXP1 ...) ... [(else EXPn ...)]) @end verbatim This is similar to @code{case}, but the keys are evaluated. @node Non-standard macros and special forms - Conditional forms - unless, Non-standard macros and special forms - Conditional forms - when, Non-standard macros and special forms - Conditional forms - select, Non-standard macros and special forms - Conditional forms @subsection unless @verbatim [syntax] (unless TEST EXP1 EXP2 ...) @end verbatim Equivalent to: (if (not TEST) (begin EXP1 EXP2 ...)) @node Non-standard macros and special forms - Conditional forms - when, , Non-standard macros and special forms - Conditional forms - unless, Non-standard macros and special forms - Conditional forms @subsection when @verbatim [syntax] (when TEST EXP1 EXP2 ...) @end verbatim Equivalent to: (if TEST (begin EXP1 EXP2 ...)) @node Non-standard macros and special forms - Record structures, Non-standard macros and special forms - Other forms, Non-standard macros and special forms - Conditional forms, Non-standard macros and special forms @section Record structures @menu * Non-standard macros and special forms - Record structures - define-record:: * Non-standard macros and special forms - Record structures - define-record-printer:: * Non-standard macros and special forms - Record structures - define-record-type:: @end menu @node Non-standard macros and special forms - Record structures - define-record, Non-standard macros and special forms - Record structures - define-record-printer, , Non-standard macros and special forms - Record structures @subsection define-record @verbatim [syntax] (define-record NAME SLOTNAME ...) @end verbatim Defines a record type. Call @code{make-NAME} to create an instance of the structure (with one initialization-argument for each slot). @code{(NAME? STRUCT)} tests any object for being an instance of this structure. Slots are accessed via @code{(NAME-SLOTNAME STRUCT)} and updated using @code{(NAME-SLOTNAME-set!} @code{STRUCT} @code{VALUE)}. (define-record point x y) (define p1 (make-point 123 456)) (point? p1) ==> #t (point-x p1) ==> 123 (point-y-set! p1 99) (point-y p1) ==> 99 @node Non-standard macros and special forms - Record structures - define-record-printer, Non-standard macros and special forms - Record structures - define-record-type, Non-standard macros and special forms - Record structures - define-record, Non-standard macros and special forms - Record structures @subsection define-record-printer @verbatim [syntax] (define-record-printer (NAME RECORDVAR PORTVAR) BODY ...) [syntax] (define-record-printer NAME PROCEDURE) @end verbatim Defines a printing method for record of the type @code{NAME} by associating a procedure with the record type. When a record of this type is written using @code{display, write} or @code{print}, then the procedure is called with two arguments: the record to be printed and an output-port. (define-record foo x y z) (define f (make-foo 1 2 3)) (define-record-printer (foo x out) @verbatim (fprintf out "#,(foo ~S ~S ~S)" (foo-x x) (foo-y x) (foo-z x)) ) @end verbatim (define-reader-ctor 'foo make-foo) (define s (with-output-to-string @verbatim (lambda () (write f)))) @end verbatim s ==> "#,(foo 1 2 3)" (equal? f (with-input-from-string @verbatim s read))) ==> #t @end verbatim @code{define-record-printer} works also with SRFI-9 record types. @node Non-standard macros and special forms - Record structures - define-record-type, , Non-standard macros and special forms - Record structures - define-record-printer, Non-standard macros and special forms - Record structures @subsection define-record-type @verbatim [syntax] (define-record-type NAME (CONSTRUCTOR TAG ...) PREDICATE (FIELD ACCESSOR [MODIFIER]) ...) @end verbatim SRFI-9 record types. For more information see the documentation for @uref{http://srfi.schemers.org/srfi-9/srfi-9.html, SRFI-9}. @node Non-standard macros and special forms - Other forms, , Non-standard macros and special forms - Record structures, Non-standard macros and special forms @section Other forms @menu * Non-standard macros and special forms - Other forms - assert:: * Non-standard macros and special forms - Other forms - cond-expand:: * Non-standard macros and special forms - Other forms - ensure:: * Non-standard macros and special forms - Other forms - eval-when:: * Non-standard macros and special forms - Other forms - include:: * Non-standard macros and special forms - Other forms - nth-value:: * Non-standard macros and special forms - Other forms - time:: @end menu @node Non-standard macros and special forms - Other forms - assert, Non-standard macros and special forms - Other forms - cond-expand, , Non-standard macros and special forms - Other forms @subsection assert @verbatim [syntax] (assert EXP [STRING ARG ...]) @end verbatim Signals an error if @code{EXP} evaluates to false. An optional message @code{STRING} and arguments @code{ARG ...} may be supplied to give a more informative error-message. If compiled in @emph{unsafe} mode (either by specifying the @code{-unsafe} compiler option or by declaring @code{(unsafe)}), then this expression expands to an unspecified value. The result is the value of @code{EXP}. @node Non-standard macros and special forms - Other forms - cond-expand, Non-standard macros and special forms - Other forms - ensure, Non-standard macros and special forms - Other forms - assert, Non-standard macros and special forms - Other forms @subsection cond-expand @verbatim [syntax] (cond-expand FEATURE-CLAUSE ...) @end verbatim Expands by selecting feature clauses. This form is allowed to appear in non-toplevel expressions. Predefined feature-identifiers are "situation" specific: @table @b @item compile @code{eval}, @code{library}, @code{match}, @code{compiling}, @code{srfi-11}, @code{srfi-15}, @code{srfi-31}, @code{srfi-26}, @code{srfi-16}, @code{utils}, @code{regex}, @code{srfi-4}, @code{match}, @code{srfi-1}, @code{srfi-69}, @code{srfi-28}, @code{extras}, @code{srfi-8}, @code{srfi-6}, @code{srfi-2}, @code{srfi-0}, @code{srfi-10}, @code{srfi-9}, @code{srfi-55}, @code{srfi-61} @code{chicken}, @code{srfi-23}, @code{srfi-30}, @code{srfi-39}, @code{srfi-62}, @code{srfi-17}, @code{srfi-12}. @item load @code{srfi-69}, @code{srfi-28}, @code{extras}, @code{srfi-8}, @code{srfi-6}, @code{srfi-2}, @code{srfi-0}, @code{srfi-10}, @code{srfi-9}, @code{srfi-55}, @code{srfi-61}, @code{chicken}, @code{srfi-23}, @code{srfi-30}, @code{srfi-39}, @code{srfi-62}, @code{srfi-17}, @code{srfi-12}. @code{library} is implicit. @item eval @code{match}, @code{csi}, @code{srfi-11}, @code{srfi-15}, @code{srfi-31}, @code{srfi-26}, @code{srfi-16}, @code{srfi-69}, @code{srfi-28}, @code{extras}, @code{srfi-8}, @code{srfi-6}, @code{srfi-2}, @code{srfi-0}, @code{srfi-10}, @code{srfi-9}, @code{srfi-55}, @code{srfi-61}, @code{chicken}, @code{srfi-23}, @code{srfi-30}, @code{srfi-39}, @code{srfi-62}, @code{srfi-17}, @code{srfi-12}. @code{library} is implicit. @end table The following feature-identifiers are available in all situations: @code{(machine-byte-order)}, @code{(machine-type)}, @code{(software-type)}, @code{(software-version)}, where the actual feature-identifier is platform dependent. In addition the following feature-identifiers may exist: @code{applyhook}, @code{extraslot}, @code{ptables}, @code{dload}, @code{libffi}. For further information, see the documentation for @uref{http://srfi.schemers.org/srfi-0/srfi-0.html, SRFI-0}. @node Non-standard macros and special forms - Other forms - ensure, Non-standard macros and special forms - Other forms - eval-when, Non-standard macros and special forms - Other forms - cond-expand, Non-standard macros and special forms - Other forms @subsection ensure @verbatim [syntax] (ensure PREDICATE EXP [ARGUMENTS ...]) @end verbatim Evaluates the expression @code{EXP} and applies the one-argument procedure @code{PREDICATE} to the result. If the predicate returns @code{#f} an error is signaled, otherwise the result of @code{EXP} is returned. If compiled in @emph{unsafe} mode (either by specifying the @code{-unsafe} compiler option or by declaring @code{(unsafe)}), then this expression expands to an unspecified value. If specified, the optional @code{ARGUMENTS} are used as arguments to the invocation of the error-signalling code, as in @code{(error ARGUMENTS ...)}. If no @code{ARGUMENTS} are given, a generic error message is displayed with the offending value and @code{PREDICATE} expression. @node Non-standard macros and special forms - Other forms - eval-when, Non-standard macros and special forms - Other forms - include, Non-standard macros and special forms - Other forms - ensure, Non-standard macros and special forms - Other forms @subsection eval-when @verbatim [syntax] (eval-when (SITUATION ...) EXP ...) @end verbatim Controls evaluation/compilation of subforms. @code{SITUATION} should be one of the symbols @code{eval}, @code{compile} or @code{load}. When encountered in the evaluator, and the situation specifier @code{eval} is not given, then this form is not evaluated and an unspecified value is returned. When encountered while compiling code, and the situation specifier @code{compile} is given, then this form is evaluated at compile-time. When encountered while compiling code, and the situation specifier @code{load} is not given, then this form is ignored and an expression resulting into an unspecified value is compiled instead. The following table should make this clearer:
In compiled codeIn interpreted code
@code{eval}ignoreevaluate
@code{compile}evaluate at compile timeignore
@code{load}compile as normalignore
The situation specifiers @code{compile-time} and @code{run-time} are also defined and have the same meaning as @code{compile} and @code{load}, respectively. @node Non-standard macros and special forms - Other forms - include, Non-standard macros and special forms - Other forms - nth-value, Non-standard macros and special forms - Other forms - eval-when, Non-standard macros and special forms - Other forms @subsection include @verbatim [syntax] (include STRING) @end verbatim Include toplevel-expressions from the given source file in the currently compiled/interpreted program. If the included file has the extension @code{.scm}, then it may be omitted. The file is searched in the current directory and, if not found, in all directories specified in the @code{-include-path} option. @node Non-standard macros and special forms - Other forms - nth-value, Non-standard macros and special forms - Other forms - time, Non-standard macros and special forms - Other forms - include, Non-standard macros and special forms - Other forms @subsection nth-value @verbatim [syntax] (nth-value N EXP) @end verbatim Returns the @code{N}th value (counting from zero) of the values returned by expression @code{EXP}. @node Non-standard macros and special forms - Other forms - time, , Non-standard macros and special forms - Other forms - nth-value, Non-standard macros and special forms - Other forms @subsection time @verbatim [syntax] (time EXP1 ...) @end verbatim Evaluates @code{EXP1 ...} and prints elapsed time and some values about GC use, like time spent in major GCs, number of minor and major GCs. Previous: @ref{Non-standard read syntax, Non-standard read syntax} Next: @ref{Pattern matching, Pattern matching} @node Pattern matching, Declarations, Non-standard macros and special forms, Top @chapter Pattern matching @menu * Pattern matching - Pattern Matching Expressions:: * Pattern matching - Patterns:: * Pattern matching - Match Failure:: * Pattern matching - Record Structures Pattern:: * Pattern matching - Code Generation:: @end menu (This description has been taken mostly from Andrew Wright's postscript document) Pattern matching allows complicated control decisions based on data structure to be expressed in a concise manner. Pattern matching is found in several modern languages, notably Standard ML, Haskell and Miranda. These syntactic extensions internally use the @code{match} library unit. The basic form of pattern matching expression is: (match exp [pat body] ...) where @code{exp} is an expression, @code{pat} is a pattern, and @code{body} is one or more expressions (like the body of a lambda-expression). The @code{match} form matches its first subexpression against a sequence of patterns, and branches to the @code{body} corresponding to the first pattern successfully matched. For example, the following code defines the usual @code{map} function: (define map @verbatim (lambda (f l) (match l [() '()] [(x . y) (cons (f x) (map f y))]))) @end verbatim The first pattern @code{()} matches the empty list. The second pattern @code{(x . y)} matches a pair, binding @code{x} to the first component of the pair and @code{y} to the second component of the pair. @node Pattern matching - Pattern Matching Expressions, Pattern matching - Patterns, , Pattern matching @section Pattern Matching Expressions The complete syntax of the pattern matching expressions follows: @verbatim exp ::= (match exp clause ...) | (match-lambda clause ...) | (match-lambda* clause ...) | (match-let ([pat exp] ...) body) | (match-let* ([pat exp] ...) body) | (match-letrec ([pat exp] ...) body) | (match-let var ([pat exp] ...) body) | (match-define pat exp) @end verbatim @verbatim clause ::= [pat body] | [pat (=> identifier) body] @end verbatim @verbatim pat ::= identifier matches anything, and binds identifier as a variable | _ anything | () itself (the empty list) | #t itself | #f itself | string an `equal?' string | number an `equal?' number | character an `equal?' character | 's-expression an `equal?' s-expression | (pat-1 ... pat-n) a proper list of n elements | (pat-1 ... pat-n . pat-n+1) a list of n or more elements | (pat-1 ... pat-n pat-n+1 ..k) a proper list of n+k or more elements [1] | #(pat-1 ... pat-n) a vector of n elements | #(pat-1 ... pat-n pat-n+1 ..k) a vector of n+k or more elements | ($ struct pat-1 ... pat-n) a structure | (= field pat) a field of a structure | (and pat-1 ... pat-n) if all of pat-1 through pat-n match | (or pat-1 ... pat-n) if any of pat-1 through pat-n match | (not pat-1 ... pat-n) if none of pat-1 through pat-n match | (? predicate pat-1 ... pat-n) if predicate true and pat-1 through pat-n all match | (set! identifier) anything, and binds identifier as a setter | (get! identifier) anything, and binds identifier as a getter | `qp a quasipattern @end verbatim @verbatim qp ::= () itself (the empty list) | #t itself | #f itself | string an `equal?' string | number an `equal?' number | character an `equal?' character | symbol an `equal?' symbol | (qp-1 ... qp-n) a proper list of n elements | (qp-1 ... qp-n . qp-n+1) a list of n or more elements | (qp-1 ... qp-n qp-n+1 ..k) a proper list of n+k or more elements | #(qp-1 ... qp-n) a vector of n elements | #(qp-1 ... qp-n qp-n+1 ..k) a vector of n+k or more elements | ,pat a pattern | ,@@pat a pattern, spliced @end verbatim The notation @code{..k} denotes a keyword consisting of three consecutive dots (ie., @emph{@code{...}}), or two dots and an non-negative integer (eg., @emph{@code{..1}}, @emph{@code{..2}}), or three consecutive underscores (ie., @emph{@code{___}}), or two underscores and a non-negative integer. The keywords @emph{@code{..k}} and @emph{@code{__ k}} are equivalent. The keywords @emph{@code{...}}, @emph{@code{___}}, @emph{@code{..0}}, and @emph{@code{__0}} are equivalent. The next subsection describes the various patterns. The @code{match-lambda} and @code{match-lambda*} forms are convenient combinations of @code{match} and @code{lambda}, and can be explained as follows: (match-lambda [pat body] ...) = (lambda (x) (match x [pat body] ...)) (match-lambda* [pat body] ...) = (lambda x (match x [pat body] ...)) where @code{x} is a unique variable. The @code{match-lambda} form is convenient when defining a single argument function that immediately destructures its argument. The @code{match-lambda*} form constructs a function that accepts any number of arguments; the patterns of @code{match-lambda*} should be lists. The @code{match-let}, @code{match-let*}, @code{match-letrec}, and @code{match-define} forms generalize Scheme's @code{let}, @code{let*}, @code{letrec}, and @code{define} expressions to allow patterns in the binding position rather than just variables. For example, the following expression: (match-let ([(x y z) (list 1 2 3)]) body ...) binds @code{x} to 1, @code{y} to 2, and @code{z} to 3 in @code{body ...}. These forms are convenient for destructuring the result of a function that returns multiple values as a list or vector. As usual for @code{letrec} and @code{define}, pattern variables bound by @code{match-letrec} and @code{match-define} should not be used in computing the bound value. The @code{match}, @code{match-lambda}, and @code{match-lambda*} forms allow the optional syntax @code{(=> identifier)} between the pattern and the body of a clause. When the pattern match for such a clause succeeds, the @code{identifier} is bound to a `failure procedure' of zero arguments within the @code{body}. If this procedure is invoked, it jumps back to the pattern matching expression, and resumes the matching process as if the pattern had failed to match. The @code{body} must not mutate the object being matched, otherwise unpredictable behavior may result. @node Pattern matching - Patterns, Pattern matching - Match Failure, Pattern matching - Pattern Matching Expressions, Pattern matching @section Patterns @code{identifier}: (excluding the reserved names @code{?}, @code{,}, @code{=}, @code{_}, @code{and}, @code{or}, @code{not}, @code{set!}, @code{get!}, @code{...}, and @code{..k} for non-negative integers @code{k}) matches anything, and binds a variable of this name to the matching value in the @code{body}. @code{_}: matches anything, without binding any variables. @code{()}, @code{#t}, @code{#f}, @code{string}, @code{number}, @code{character}, '@code{s-expression}: These constant patterns match themselves, i.e., the corresponding value must be @code{equal?} to the pattern. @code{(pat-1 ... pat-n)}: matches a proper list of @code{n} elements that match @code{pat-1} through @code{pat-n}. @code{(pat-1 ... pat-n . pat-n+1)}: matches a (possibly improper) list of at least @code{n} elements that ends in something matching @code{pat-n+1}. @code{(pat-1 ... pat-n pat-n+1 ...)}: matches a proper list of @code{n} or more elements, where each element of the tail matches @code{pat-n+1}. Each pattern variable in @code{pat-n+1} is bound to a list of the matching values. For example, the expression: (match '(let ([x 1][y 2]) z) @verbatim [('let ((binding values) ...) exp) body]) @end verbatim binds @code{binding} to the list @code{'(x y)}, @code{values} to the list \@code{'(1 2)}, and @code{exp} to @code{'z} in the body of the @code{match}-expression. For the special case where @code{pat-n+1} is a pattern variable, the list bound to that variable may share with the matched value. @code{(pat-1 ... pat-n pat-n+1 ___)}: This pattern means the same thing as the previous pattern. @code{(pat-1 ... pat-n pat-n+1 ..k)}: This pattern is similar to the previous pattern, but the tail must be at least @code{k} elements long. The pattern keywords @code{..0} and @code{...} are equivalent. @code{(pat-1 ... pat-n ~ pat-n+1 __k)}: This pattern means the same thing as the previous pattern. @code{#(pat-1 ... pat-n)}: matches a vector of length @code{n}, whose elements match @code{pat-1} through @code{pat-n}. @code{#(pat-1 ... pat-n pat-n+1 ...)}: matches a vector of length @code{n} or more, where each element beyond @code{n} matches @code{pat-n+1}. @code{#(pat-1 ... pat-n pat-n+1 ..k)}: matches a vector of length @code{n+k} or more, where each element beyond @code{n} matches @code{pat-n+1}. @code{($ struct pat-1 ... pat-n)}: matches a structure declared with @code{define-record} or @code{define-record-type}. @code{(= field pat)}: is intended for selecting a field from a structure. @emph{field} may be any expression; it is applied to the value being matched, and the result of this application is matched against @code{pat}. @code{(and pat-1 ... pat-n)}: matches if all of the subpatterns match. At least one subpattern must be present. This pattern is often used as @code{(and x pat)} to bind @code{x} to to the entire value that matches @code{pat} (cf. @emph{as-patterns} in ML or Haskell). @code{(or pat-1 ... pat-n)}: matches if any of the subpatterns match. At least one subpattern must be present. All subpatterns must bind the same set of pattern variables. @code{(not pat-1 ... pat-n)}: matches if none of the subpatterns match. At least one subpattern must be present. The subpatterns may not bind any pattern variables. @code{(? predicate pat-1 ... pat-n)}: In this pattern, @code{predicate} must be an expression evaluating to a single argument function. This pattern matches if @code{predicate} applied to the corresponding value is true, and the subpatterns @code{pat-1 ... pat-n} all match. The @code{predicate} should not have side effects, as the code generated by the pattern matcher may invoke predicates repeatedly in any order. The @code{predicate} expression is bound in the same scope as the match expression, i.e., free variables in @code{predicate} are not bound by pattern variables. @code{(set! identifier)}: matches anything, and binds @code{identifier} to a procedure of one argument that mutates the corresponding field of the matching value. This pattern must be nested within a pair, vector, box, or structure pattern. For example, the expression: (define x (list 1 (list 2 3))) (match x [(_ (_ (set! setit))) (setit 4)]) mutates the @code{cadadr} of @code{x} to 4, so that @code{x} is @code{'(1 (2 4))}. @code{(get! identifier)}: matches anything, and binds @code{identifier} to a procedure of zero arguments that accesses the corresponding field of the matching value. This pattern is the complement to @code{set!}. As with @code{set!}, this pattern must be nested within a pair, vector, box, or structure pattern. @emph{Quasipatterns}: Quasiquote introduces a quasipattern, in which identifiers are considered to be symbolic constants. Like Scheme's quasiquote for data, @code{unquote} (,) and @code{unquote-splicing} (,@@) escape back to normal patterns. @node Pattern matching - Match Failure, Pattern matching - Record Structures Pattern, Pattern matching - Patterns, Pattern matching @section Match Failure If no clause matches the value, the default action is to invoke the procedure @code{(match-error-procedure)} with the value that did not match. The default definition of @code{(match-error-procedure)} calls @code{error} with an appropriate message: @enumerate @item ;1> (match 1 (2 2)) @end enumerate Failed match: Error: no matching clause for : 1 For most situations, this behavior is adequate, but it can be changed by altering the value of the parameter @code{match-error-control}: @table @b @item @{procedure@} match-error-control @end table (match-error-control [MODE]) Selects a mode that specifies how @code{match...} macro forms are to be expanded. With no argument this procedure returns the current mode. A single argument specifies the new mode that decides what should happen if no match-clause applies. The following modes are supported:
#:error Signal an error. This is the default.
#:match Signal an error and output the offending form.
#:fail Omits @code{pair?} tests when the consequence is to fail in @code{car} or @code{cdr} rather than to signal an error.
unspecified Non-matching expressions will either fail in @code{car} or @code{cdr} or return an unspecified value. This mode applies to files compiled with the @code{unsafe} option or declaration.
When an error is signalled, the raised exception will be of kind @code{(exn match)}. @table @b @item [procedure] match-error-procedure @end table (match-error-procedure [PROCEDURE]) Sets or returns the procedure called upon a match error. The procedure takes one argument, the value which failed to match. When the error control mode is @code{#:match} a second argument, the source form of the match expression is available. @node Pattern matching - Record Structures Pattern, Pattern matching - Code Generation, Pattern matching - Match Failure, Pattern matching @section Record Structures Pattern The @code{$} pattern handles native record structures and @uref{http://srfi.schemers.org/srfi-9/srfi-9.html, SRFI-9} records transparently. Currently it is required that @uref{http://srfi.schemers.org/srfi-9/srfi-9.html, SRFI-9} record predicates are named exactly like the record type name, followed by a @code{?} (question mark) character. @node Pattern matching - Code Generation, , Pattern matching - Record Structures Pattern, Pattern matching @section Code Generation Pattern matching macros are compiled into @code{if}-expressions that decompose the value being matched with standard Scheme procedures, and test the components with standard predicates. Rebinding or lexically shadowing the names of any of these procedures will change the semantics of the @code{match} macros. The names that should not be rebound or shadowed are: null? pair? number? string? symbol? boolean? char? procedure? vector? list? equal? car cdr cadr cdddr ... vector-length vector-ref reverse length call/cc Additionally, the code generated to match a structure pattern like @code{($ Foo pat-1 ... pat-n)} refers to the name @code{Foo?}. This name also should not be shadowed. Previous: @ref{Non-standard macros and special forms, Non-standard macros and special forms} Next: @ref{Declarations, Declarations} @node Declarations, Parameters, Pattern matching, Top @chapter Declarations @menu * Declarations - declare:: * Declarations - always-bound:: * Declarations - block:: * Declarations - block-global:: * Declarations - hide:: * Declarations - bound-to-procedure:: * Declarations - c-options:: * Declarations - check-c-syntax:: * Declarations - compress-literals:: * Declarations - constant:: * Declarations - export:: * Declarations - emit-exports:: * Declarations - emit-external-prototypes-first:: * Declarations - disable-interrupts:: * Declarations - disable-warning:: * Declarations - import:: * Declarations - inline:: * Declarations - inline-limit:: * Declarations - interrupts-enabled:: * Declarations - keep-shadowed-macros:: * Declarations - lambda-lift:: * Declarations - link-options:: * Declarations - no-argc-checks:: * Declarations - no-bound-checks:: * Declarations - no-procedure-checks:: * Declarations - post-process:: * Declarations - number-type:: * Declarations - fixnum-arithmetic:: * Declarations - run-time-macros:: * Declarations - standard-bindings:: * Declarations - extended-bindings:: * Declarations - usual-integrations:: * Declarations - unit:: * Declarations - unsafe:: * Declarations - unused:: * Declarations - uses:: @end menu @node Declarations - declare, Declarations - always-bound, , Declarations @section declare @verbatim [syntax] (declare DECLSPEC ...) @end verbatim Process declaration specifiers. Declarations always override any command-line settings. Declarations are valid for the whole compilation-unit (source file), the position of the declaration in the source file can be arbitrary. Declarations are ignored in the interpreter but not in code evaluated at compile-time (by @code{eval-when} or in syntax extensions loaded via @code{require-extension} or @code{require-for-syntax}. @code{DECLSPEC} may be any of the following: @node Declarations - always-bound, Declarations - block, Declarations - declare, Declarations @section always-bound @verbatim [declaration specifier] (always-bound SYMBOL ...) @end verbatim Declares that the given variables are always bound and accesses to those have not to be checked. @node Declarations - block, Declarations - block-global, Declarations - always-bound, Declarations @section block @verbatim [declaration specifier] (block) @end verbatim Assume global variables are never redefined. This is the same as specifying the @code{-block} option. @node Declarations - block-global, Declarations - hide, Declarations - block, Declarations @section block-global @node Declarations - hide, Declarations - bound-to-procedure, Declarations - block-global, Declarations @section hide @verbatim [declaration specifier] (block-global SYMBOL ...) [declaration specifier] (hide SYMBOL ...) @end verbatim Declares that the toplevel bindings for @code{SYMBOL ...} should not be accessible from code in other compilation units or by @code{eval}. Access to toplevel bindings declared as block global is also more efficient. @node Declarations - bound-to-procedure, Declarations - c-options, Declarations - hide, Declarations @section bound-to-procedure @verbatim [declaration specifier] (bound-to-procedure SYMBOL ...) @end verbatim Declares that the given identifiers are always bound to procedure values. @node Declarations - c-options, Declarations - check-c-syntax, Declarations - bound-to-procedure, Declarations @section c-options @verbatim [declaration specifier] (c-options STRING ...) @end verbatim Declares additional C/C++ compiler options that are to be passed to the subsequent compilation pass that translates C to machine code. This declaration will only work if the source file is compiled with the @code{csc} compiler driver. @node Declarations - check-c-syntax, Declarations - compress-literals, Declarations - c-options, Declarations @section check-c-syntax @verbatim [declaration specifier] (check-c-syntax) [declaration specifier] (not check-c-syntax) @end verbatim Enables or disables syntax-checking of embedded C/C++ code fragments. Checking C syntax is the default. @node Declarations - compress-literals, Declarations - constant, Declarations - check-c-syntax, Declarations @section compress-literals @verbatim [declaration specifier] (compress-literals [THRESHOLD [INITIALIZER]]) @end verbatim The same as the @code{-compress-literals} compiler option. The threshold argument defaults to 50. If the optional argument @code{INITIALIZER} is given, then the literals will not be created at module startup, but when the procedure with this name will be called. @node Declarations - constant, Declarations - export, Declarations - compress-literals, Declarations @section constant @verbatim [declaration specifier] (constant SYMBOL ...) @end verbatim Declares the procedures with the names @code{SYMBOL ...} as constant, that is, as not having any side effects. This can help the compiler to remove non-side-effecting expressions. @node Declarations - export, Declarations - emit-exports, Declarations - constant, Declarations @section export @verbatim [declaration specifier] (export SYMBOL ...) @end verbatim The opposite of @code{hide}. All given identifiers will be exported and all toplevel variables not listed will be hidden and not be accessible outside of this compilation unit. @node Declarations - emit-exports, Declarations - emit-external-prototypes-first, Declarations - export, Declarations @section emit-exports @verbatim [declaration specifier] (emit-exports STRING) @end verbatim Write exported toplevel variables to file with name @code{STRING}. @node Declarations - emit-external-prototypes-first, Declarations - disable-interrupts, Declarations - emit-exports, Declarations @section emit-external-prototypes-first @verbatim [declaration specifier] (emit-external-prototypes-first) @end verbatim Emit prototypes for callbacks defined with @code{define-external} before any other foreign declarations. Equivalent to giving the @code{-emit-external-prototypes-first} option to the compiler. @node Declarations - disable-interrupts, Declarations - disable-warning, Declarations - emit-external-prototypes-first, Declarations @section disable-interrupts @verbatim [declaration specifier] (disable-interrupts) [declaration specifier] (not interrupts-enabled) @end verbatim Disable timer-interrupts checks in the compiled program. Threads can not be preempted in main- or library-units that contain this declaration. @node Declarations - disable-warning, Declarations - import, Declarations - disable-interrupts, Declarations @section disable-warning @verbatim [declaration specifier] (disable-warning CLASS ...) @end verbatim Disable warnings of type @code{CLASS ...} (equivalent to the @code{-disable-warning CLASS} compiler option). @node Declarations - import, Declarations - inline, Declarations - disable-warning, Declarations @section import @verbatim [declaration specifier] (import SYMBOL-OR-STRING ...) @end verbatim Adds new imports to the list of externally available toplevel variables. Arguments to this declaration may be either strings (designating @code{.exports} files, without the file-extension) or symbols which directly designate imported variables. @node Declarations - inline, Declarations - inline-limit, Declarations - import, Declarations @section inline @verbatim [declaration specifier] (inline) [declaration specifier] (not inline) [declaration specifier] (inline IDENTIFIER ...) [declaration specifier] (not inline IDENTIFIER ...) @end verbatim If given without an identifier-list, inlining of known procedures is enabled (this is equivalent to the @code{-inline} compiler option). When an identifier-list is given, then inlining is enabled only for the specified global procedures. The negated forms @code{(not inline)} and @code{(not inline IDENTIFIER)} disable global inlining, or inlining for the given global procedures only, respectively. @node Declarations - inline-limit, Declarations - interrupts-enabled, Declarations - inline, Declarations @section inline-limit @verbatim [declaration specifier] (inline-limit THRESHOLD) @end verbatim Sets the maximum size of procedures which may potentially be inlined. The default threshold is @code{10}. @node Declarations - interrupts-enabled, Declarations - keep-shadowed-macros, Declarations - inline-limit, Declarations @section interrupts-enabled @verbatim [declaration specifier] (interrupts-enabled) @end verbatim Enable timer-interrupts checks in the compiled program (the default). @node Declarations - keep-shadowed-macros, Declarations - lambda-lift, Declarations - interrupts-enabled, Declarations @section keep-shadowed-macros @verbatim [declaration specifier] (keep-shadowed-macros) @end verbatim Normally, when a toplevel variable is assigned or defined that has the same name as a macro, the macro-definition will be removed (in addition to showing a warning). This declaration will disable the removal of the macro. @node Declarations - lambda-lift, Declarations - link-options, Declarations - keep-shadowed-macros, Declarations @section lambda-lift @verbatim [declaration specifier] (lambda-lift) @end verbatim Enables lambda-lifting (equivalent to the @code{-lambda-lift} option). @node Declarations - link-options, Declarations - no-argc-checks, Declarations - lambda-lift, Declarations @section link-options @verbatim [declaration specifier] (link-options STRING ...) @end verbatim Declares additional linker compiler options that are to be passed to the subsequent compilation pass that links the generated code into an executable or library. This declaration will only work if the source file is compiled with the @code{csc} compiler driver. @node Declarations - no-argc-checks, Declarations - no-bound-checks, Declarations - link-options, Declarations @section no-argc-checks @verbatim [declaration specifier] (no-argc-checks) @end verbatim Disables argument count checking. @node Declarations - no-bound-checks, Declarations - no-procedure-checks, Declarations - no-argc-checks, Declarations @section no-bound-checks @verbatim [declaration specifier] (no-bound-checks) @end verbatim Disables the bound-checking of toplevel bindings. @node Declarations - no-procedure-checks, Declarations - post-process, Declarations - no-bound-checks, Declarations @section no-procedure-checks @verbatim [declaration specifier] (no-procedure-checks) @end verbatim Disables checking of values in operator position for being of procedure type. @node Declarations - post-process, Declarations - number-type, Declarations - no-procedure-checks, Declarations @section post-process @verbatim [declaration specifier] (post-process STRING ...) @end verbatim Arranges for the shell commands @code{STRING ...} to be invoked after the current file has been translated to C. Any occurrences of the substring @code{$@@@@} in the strings given for this declaration will be replaced by the pathname of the currently compiled file, without the file-extension. This declaration will only work if the source file is compiled with the @code{csc} compiler driver. @node Declarations - number-type, Declarations - fixnum-arithmetic, Declarations - post-process, Declarations @section number-type @node Declarations - fixnum-arithmetic, Declarations - run-time-macros, Declarations - number-type, Declarations @section fixnum-arithmetic @verbatim [declaration specifier] ([number-type] TYPE) [declaration specifier] (fixnum-arithmetic) @end verbatim Declares that only numbers of the given type are used. @code{TYPE} may be @code{fixnum} or @code{generic} (which is the default). @node Declarations - run-time-macros, Declarations - standard-bindings, Declarations - fixnum-arithmetic, Declarations @section run-time-macros @verbatim [declaration specifier] (run-time-macros) @end verbatim Equivalent to the compiler option of the same name - macros defined in the compiled code are also made available at runtime. @node Declarations - standard-bindings, Declarations - extended-bindings, Declarations - run-time-macros, Declarations @section standard-bindings @verbatim [declaration specifier] (standard-bindings SYMBOL ...) [declaration specifier] (not standard-bindings SYMBOL ...) @end verbatim Declares that all given standard procedures (or all if no symbols are specified) are never globally redefined. If @code{not} is specified, then all but the given standard bindings are assumed to be never redefined. @node Declarations - extended-bindings, Declarations - usual-integrations, Declarations - standard-bindings, Declarations @section extended-bindings @verbatim [declaration specifier] (extended-bindings SYMBOL ...) [declaration specifier] (not extended-bindings SYMBOL ...) @end verbatim Declares that all given non-standard and CHICKEN-specific procedures (or all if no symbols are specified) are never globally redefined. If @code{not} is specified, then all but the given extended bindings are assumed to be never redefined. @node Declarations - usual-integrations, Declarations - unit, Declarations - extended-bindings, Declarations @section usual-integrations @verbatim [declaration specifier] (usual-integrations SYMBOL ...) [declaration specifier] (not usual-integrations SYMBOL ...) @end verbatim Declares that all given standard and extended bindings (or all if no symbols are specified) are never globally redefined. If @code{not} is specified, then all but the given standard and extended bindings are assumed to be never redefined. Note that this is the default behaviour, unless the @code{-no-usual-integrations} option has been given. @node Declarations - unit, Declarations - unsafe, Declarations - usual-integrations, Declarations @section unit @verbatim [declaration specifier] (unit SYMBOL) @end verbatim Specify compilation unit-name (if this is a library) @node Declarations - unsafe, Declarations - unused, Declarations - unit, Declarations @section unsafe @verbatim [declaration specifier] (unsafe) [declaration specifier] (not safe) @end verbatim Do not generate safety-checks. This is the same as specifying the @code{-unsafe} option. Also implies @verbatim (declare (no-bound-checks) (no-procedure-checks) (no-argc-checks)) @end verbatim @node Declarations - unused, Declarations - uses, Declarations - unsafe, Declarations @section unused @verbatim [declaration specifier] (unused SYMBOL ...) @end verbatim Disables any warnings when the global variable @code{SYMBOL} is not defined but used, or defined but never used and not exported. @node Declarations - uses, , Declarations - unused, Declarations @section uses @verbatim [declaration specifier] (uses SYMBOL ...) @end verbatim Gives a list of used library-units. Before the toplevel-expressions of the main-module are executed, all used units evaluate their toplevel-expressions in the order in which they appear in this declaration. If a library unit A uses another unit B, then B's toplevel expressions are evaluated before A's. Furthermore, the used symbols are registered as features during compile-time, so @code{cond-expand} knows about them. Previous: @ref{Pattern matching, Pattern matching} Next: @ref{Parameters, Parameters} @node Parameters, Unit library, Declarations, Top @chapter Parameters @menu * Parameters - make-parameter:: * Parameters - case-sensitive:: * Parameters - dynamic-load-libraries:: * Parameters - command-line-arguments:: * Parameters - current-read-table:: * Parameters - exit-handler:: * Parameters - eval-handler:: * Parameters - force-finalizers:: * Parameters - implicit-exit-handler:: * Parameters - keyword-style:: * Parameters - load-verbose:: * Parameters - program-name:: * Parameters - repl-prompt:: * Parameters - reset-handler:: @end menu Certain behavior of the interpreter and compiled programs can be customized via 'parameters', where a parameter is a procedure of zero or one arguments. To retrieve the value of a parameter call the parameter-procedure with zero arguments. To change the setting of the parameter, call the parameter-procedure with the new value as argument: (define foo (make-parameter 123)) (foo) ==> 123 (foo 99) (foo) ==> 99 Parameters are fully thread-local, each thread of execution owns a local copy of a parameters' value. CHICKEN implements @uref{http://srfi.schemers.org/srfi-39/srfi-39.html, SRFI-39}. @node Parameters - make-parameter, Parameters - case-sensitive, , Parameters @section make-parameter @verbatim [procedure] (make-parameter VALUE [GUARD]) @end verbatim Returns a procedure that accepts zero or one argument. Invoking the procedure with zero arguments returns @code{VALUE}. Invoking the procedure with one argument changes its value to the value of that argument (subsequent invocations with zero parameters return the new value). @code{GUARD} should be a procedure of a single argument. Any new values of the parameter (even the initial value) are passed to this procedure. The guard procedure should check the value and/or convert it to an appropriate form. @node Parameters - case-sensitive, Parameters - dynamic-load-libraries, Parameters - make-parameter, Parameters @section case-sensitive If true, then @code{read} reads symbols and identifiers in case-sensitive mode and uppercase characters in symbols are printed escaped. Defaults to @code{#t}. @node Parameters - dynamic-load-libraries, Parameters - command-line-arguments, Parameters - case-sensitive, Parameters @section dynamic-load-libraries A list of strings containing shared libraries that should be checked for explicitly loaded library units (this facility is not available on all platforms). See @code{load-library}. @node Parameters - command-line-arguments, Parameters - current-read-table, Parameters - dynamic-load-libraries, Parameters @section command-line-arguments Contains the list of arguments passed to this program, with the name of the program and any runtime options (all options starting with @code{-:}) removed. @node Parameters - current-read-table, Parameters - exit-handler, Parameters - command-line-arguments, Parameters @section current-read-table A read-table object that holds read-procedures for special non-standard read-syntax (see @code{set-read-syntax!} for more information). @node Parameters - exit-handler, Parameters - eval-handler, Parameters - current-read-table, Parameters @section exit-handler A procedure of a single optional argument. When @code{exit} is called, then this procedure will be invoked with the exit-code as argument. The default behavior is to terminate the program. @node Parameters - eval-handler, Parameters - force-finalizers, Parameters - exit-handler, Parameters @section eval-handler A procedure of one or two arguments. When @code{eval} is invoked, it calls the value of this parameter with the same arguments. The default behavior is to evaluate the argument expression and to ignore the second parameter. @node Parameters - force-finalizers, Parameters - implicit-exit-handler, Parameters - eval-handler, Parameters @section force-finalizers If true, force and execute all pending finalizers before exiting the program (either explicitly by @code{exit} or implicitly when the last toplevel expression has been executed). Default is @code{#t}. @node Parameters - implicit-exit-handler, Parameters - keyword-style, Parameters - force-finalizers, Parameters @section implicit-exit-handler A procedure of no arguments. When the last toplevel expression of the program has executed, then the value of this parameter is called. The default behaviour is to invoke all pending finalizers. @node Parameters - keyword-style, Parameters - load-verbose, Parameters - implicit-exit-handler, Parameters @section keyword-style Enables alternative keyword syntax, where @code{STYLE} may be either @code{#:prefix} (as in Common Lisp) or @code{#:suffix} (as in DSSSL). Any other value disables the alternative syntaxes. @node Parameters - load-verbose, Parameters - program-name, Parameters - keyword-style, Parameters @section load-verbose A boolean indicating whether loading of source files, compiled code (if available) and compiled libraries should display a message. @node Parameters - program-name, Parameters - repl-prompt, Parameters - load-verbose, Parameters @section program-name The name of the currently executing program. This is equivalent to @code{(car (argv))} for compiled programs or the filename following the @code{-script} option in interpreted scripts. @node Parameters - repl-prompt, Parameters - reset-handler, Parameters - program-name, Parameters @section repl-prompt A procedure that should evaluate to a string that will be printed before reading interactive input from the user in a read-eval-print loop. Defaults to @code{(lambda () "#;N> ")}. @node Parameters - reset-handler, , Parameters - repl-prompt, Parameters @section reset-handler A procedure of zero arguments that is called via @code{reset}. The default behavior in compiled code is to invoke the value of @code{(exit-handler)}. The default behavior in the interpreter is to abort the current computation and to restart the read-eval-print loop. Previous: @ref{Declarations, Declarations} Next: @ref{Unit library, Unit library} @node Unit library, Unit eval, Parameters, Top @chapter Unit library @menu * Unit library - Arithmetic:: * Unit library - File Input/Output:: * Unit library - Files:: * Unit library - String ports:: * Unit library - Feature identifiers:: * Unit library - Keywords:: * Unit library - Exceptions:: * Unit library - Environment information and system interface:: * Unit library - Execution time:: * Unit library - Interrupts and error-handling:: * Unit library - Garbage collection:: * Unit library - Other control structures:: * Unit library - String utilities:: * Unit library - Generating uninterned symbols:: * Unit library - Standard Input/Output:: * Unit library - User-defined named characters:: * Unit library - Vectors:: * Unit library - The unspecified value:: * Unit library - Continuations:: * Unit library - Setters:: * Unit library - Reader extensions:: @end menu This unit contains basic Scheme definitions. This unit is used by default, unless the program is compiled with the @code{-explicit-use} option. @node Unit library - Arithmetic, Unit library - File Input/Output, , Unit library @section Arithmetic @menu * Unit library - Arithmetic - add1/sub1:: * Unit library - Arithmetic - Binary integer operations:: * Unit library - Arithmetic - bit-set?:: * Unit library - Arithmetic - fixnum?:: * Unit library - Arithmetic - Arithmetic fixnum operations:: * Unit library - Arithmetic - Arithmetic floating-point operations:: * Unit library - Arithmetic - signum:: * Unit library - Arithmetic - finite?:: @end menu @node Unit library - Arithmetic - add1/sub1, Unit library - Arithmetic - Binary integer operations, , Unit library - Arithmetic @subsection add1/sub1 @table @b @item [procedure] (add1 N) @item [procedure] (sub1 N) @end table Adds/subtracts 1 from @code{N}. @node Unit library - Arithmetic - Binary integer operations, Unit library - Arithmetic - bit-set?, Unit library - Arithmetic - add1/sub1, Unit library - Arithmetic @subsection Binary integer operations Binary integer operations. @code{arithmetic-shift} shifts the argument @code{N1} by @code{N2} bits to the left. If @code{N2} is negative, than @code{N1} is shifted to the right. These operations only accept exact integers or inexact integers in word range (32 bit signed on 32-bit platforms, or 64 bit signed on 64-bit platforms). @table @b @item [procedure] (bitwise-and N1 ...) @item [procedure] (bitwise-ior N1 ...) @item [procedure] (bitwise-xor N1 ...) @item [procedure] (bitwise-not N) @item [procedure] (arithmetic-shift N1 N2) @end table @node Unit library - Arithmetic - bit-set?, Unit library - Arithmetic - fixnum?, Unit library - Arithmetic - Binary integer operations, Unit library - Arithmetic @subsection bit-set? @verbatim [procedure] (bit-set? N INDEX) @end verbatim Returns @code{#t} if the bit at the position @code{INDEX} in the integer @code{N} is set, or @code{#f} otherwise. The rightmost/least-significant bit is bit 0. @node Unit library - Arithmetic - fixnum?, Unit library - Arithmetic - Arithmetic fixnum operations, Unit library - Arithmetic - bit-set?, Unit library - Arithmetic @subsection fixnum? @verbatim [procedure] (fixnum? X) @end verbatim Returns @code{#t} if @code{X} is a fixnum, or @code{#f} otherwise. @node Unit library - Arithmetic - Arithmetic fixnum operations, Unit library - Arithmetic - Arithmetic floating-point operations, Unit library - Arithmetic - fixnum?, Unit library - Arithmetic @subsection Arithmetic fixnum operations These procedures do not check their arguments, so non-fixnum parameters will result in incorrect results. @code{fxneg} negates its argument. On division by zero, @code{fx/} and @code{fxmod} signal a condition of kind @code{(exn arithmetic)}. @code{fxshl} and @code{fxshr} perform arithmetic shift left and right, respectively. @table @b @item [procedure] (fx+ N1 N2) @item [procedure] (fx- N1 N2) @item [procedure] (fx* N1 N2) @item [procedure] (fx/ N1 N2) @item [procedure] (fxmod N1 N2) @item [procedure] (fxneg N) @item [procedure] (fxmin N1 N2) @item [procedure] (fxmax N1 N2) @item [procedure] (fx= N1 N2) @item [procedure] (fx> N1 N2) @item [procedure] (fx< N1 N2) @item [procedure] (fx>= N1 N2) @item [procedure] (fx<= N1 N2) @item [procedure] (fxand N1 N2) @item [procedure] (fxior N1 N2) @item [procedure] (fxxor N1 N2) @item [procedure] (fxnot N) @item [procedure] (fxshl N1 N2) @item [procedure] (fxshr N1 N2) @end table @node Unit library - Arithmetic - Arithmetic floating-point operations, Unit library - Arithmetic - signum, Unit library - Arithmetic - Arithmetic fixnum operations, Unit library - Arithmetic @subsection Arithmetic floating-point operations In safe mode, these procedures throw a type error with non-float arguments (except @code{flonum?}, which returns @code{#f}). In unsafe mode, these procedures do not check their arguments. A non-flonum argument in unsafe mode can crash the system. @table @b @item [procedure] (flonum? X) @item [procedure] (fp+ X Y) @item [procedure] (fp- X Y) @item [procedure] (fp* X Y) @item [procedure] (fp/ X Y) @item [procedure] (fpneg X) @item [procedure] (fpmin X Y) @item [procedure] (fpmax X Y) @item [procedure] (fp= X Y) @item [procedure] (fp> X Y) @item [procedure] (fp< X Y) @item [procedure] (fp>= X Y) @item [procedure] (fp<= X Y) @end table @node Unit library - Arithmetic - signum, Unit library - Arithmetic - finite?, Unit library - Arithmetic - Arithmetic floating-point operations, Unit library - Arithmetic @subsection signum @verbatim [procedure] (signum N) @end verbatim Returns @code{1} if @code{N} is positive, @code{-1} if @code{N} is negative or @code{0} if @code{N} is zero. @code{signum} is exactness preserving. @node Unit library - Arithmetic - finite?, , Unit library - Arithmetic - signum, Unit library - Arithmetic @subsection finite? @verbatim [procedure] (finite? N) @end verbatim Returns @code{#f} if @code{N} is negative or positive infinity, and @code{#t} otherwise. @node Unit library - File Input/Output, Unit library - Files, Unit library - Arithmetic, Unit library @section File Input/Output @menu * Unit library - File Input/Output - current-output-port:: * Unit library - File Input/Output - current-error-port:: * Unit library - File Input/Output - flush-output:: * Unit library - File Input/Output - port-name:: * Unit library - File Input/Output - port-position:: * Unit library - File Input/Output - set-port-name!:: @end menu @node Unit library - File Input/Output - current-output-port, Unit library - File Input/Output - current-error-port, , Unit library - File Input/Output @subsection current-output-port @verbatim [procedure] (current-output-port [PORT]) @end verbatim Returns default output port. If @code{PORT} is given, then that port is selected as the new current output port. Note that the default output port is not buffered. Use @ref{Unit posix - Setting the file buffering mode, @code{set-buffering-mode!}} if you need a different behaviour. @node Unit library - File Input/Output - current-error-port, Unit library - File Input/Output - flush-output, Unit library - File Input/Output - current-output-port, Unit library - File Input/Output @subsection current-error-port @verbatim [procedure] (current-error-port [PORT]) @end verbatim Returns default error output port. If @code{PORT} is given, then that port is selected as the new current error output port. Note that the default error output port is not buffered. Use @ref{Unit posix - Setting the file buffering mode, @code{set-buffering-mode!}} if you need a different behaviour. @node Unit library - File Input/Output - flush-output, Unit library - File Input/Output - port-name, Unit library - File Input/Output - current-error-port, Unit library - File Input/Output @subsection flush-output @verbatim [procedure] (flush-output [PORT]) @end verbatim Write buffered output to the given output-port. @code{PORT} defaults to the value of @code{(current-output-port)}. @node Unit library - File Input/Output - port-name, Unit library - File Input/Output - port-position, Unit library - File Input/Output - flush-output, Unit library - File Input/Output @subsection port-name @verbatim [procedure] (port-name [PORT]) @end verbatim Fetch filename from @code{PORT}. This returns the filename that was used to open this file. Returns a special tag string, enclosed into parentheses for non-file ports. @code{PORT} defaults to the value of @code{(current-input-port)}. @node Unit library - File Input/Output - port-position, Unit library - File Input/Output - set-port-name!, Unit library - File Input/Output - port-name, Unit library - File Input/Output @subsection port-position @verbatim [procedure] (port-position [PORT]) @end verbatim Returns the current position of @code{PORT} as two values: row and column number. If the port does not support such an operation an error is signaled. This procedure is currently only available for input ports. @code{PORT} defaults to the value of @code{(current-input-port)}. @node Unit library - File Input/Output - set-port-name!, , Unit library - File Input/Output - port-position, Unit library - File Input/Output @subsection set-port-name! @verbatim [procedure] (set-port-name! PORT STRING) @end verbatim Sets the name of @code{PORT} to @code{STRING}. @node Unit library - Files, Unit library - String ports, Unit library - File Input/Output, Unit library @section Files @menu * Unit library - Files - delete-file:: * Unit library - Files - file-exists?:: * Unit library - Files - rename-file:: @end menu @node Unit library - Files - delete-file, Unit library - Files - file-exists?, , Unit library - Files @subsection delete-file @verbatim [procedure] (delete-file STRING) @end verbatim Deletes the file with the pathname @code{STRING}. If the file does not exist, an error is signaled. @node Unit library - Files - file-exists?, Unit library - Files - rename-file, Unit library - Files - delete-file, Unit library - Files @subsection file-exists? @verbatim [procedure] (file-exists? STRING) @end verbatim Returns @code{STRING} if a file with the given pathname exists, or @code{#f} otherwise. @node Unit library - Files - rename-file, , Unit library - Files - file-exists?, Unit library - Files @subsection rename-file @verbatim [procedure] (rename-file OLD NEW) @end verbatim Renames the file or directory with the pathname @code{OLD} to @code{NEW}. If the operation does not succeed, an error is signaled. @node Unit library - String ports, Unit library - Feature identifiers, Unit library - Files, Unit library @section String ports @menu * Unit library - String ports - get-output-string:: * Unit library - String ports - open-input-string:: * Unit library - String ports - open-output-string:: @end menu @node Unit library - String ports - get-output-string, Unit library - String ports - open-input-string, , Unit library - String ports @subsection get-output-string @verbatim [procedure] (get-output-string PORT) @end verbatim Returns accumulated output of a port created with @code{(open-output-string)}. @node Unit library - String ports - open-input-string, Unit library - String ports - open-output-string, Unit library - String ports - get-output-string, Unit library - String ports @subsection open-input-string @verbatim [procedure] (open-input-string STRING) @end verbatim Returns a port for reading from @code{STRING}. @node Unit library - String ports - open-output-string, , Unit library - String ports - open-input-string, Unit library - String ports @subsection open-output-string @verbatim [procedure] (open-output-string) @end verbatim Returns a port for accumulating output in a string. @node Unit library - Feature identifiers, Unit library - Keywords, Unit library - String ports, Unit library @section Feature identifiers @menu * Unit library - Feature identifiers - features:: * Unit library - Feature identifiers - feature?:: * Unit library - Feature identifiers - register-feature!:: * Unit library - Feature identifiers - unregister-feature!:: @end menu CHICKEN maintains a global list of @emph{features} naming functionality available int the current system. Additionally the @code{cond-expand} form accesses this feature list to infer what features are provided. Predefined features are @code{chicken}, and the SRFIs (Scheme Request For Implementation) provided by the base system: @code{srfi-23, srfi-30, srfi-39}. If the @code{eval} unit is used (the default), the features @code{srfi-0, srfi-2, srfi-6, srfi-8, srfi-9} and @code{srfi-10} are defined. When compiling code (during compile-time) the feature @code{compiling} is registered. When evaluating code in the interpreter (csi), the feature @code{csi} is registered. @node Unit library - Feature identifiers - features, Unit library - Feature identifiers - feature?, , Unit library - Feature identifiers @subsection features @verbatim [procedure] (features) @end verbatim Returns a list of all registered features that will be accepted as valid feature-identifiers by @code{cond-expand}. @node Unit library - Feature identifiers - feature?, Unit library - Feature identifiers - register-feature!, Unit library - Feature identifiers - features, Unit library - Feature identifiers @subsection feature? @verbatim [procedure] (feature? ID ...) @end verbatim Returns @code{#t} if all features with the given feature-identifiers @code{ID ...} are registered. @node Unit library - Feature identifiers - register-feature!, Unit library - Feature identifiers - unregister-feature!, Unit library - Feature identifiers - feature?, Unit library - Feature identifiers @subsection register-feature! @verbatim [procedure] (register-feature! FEATURE ...) @end verbatim Register one or more features that will be accepted as valid feature-identifiers by @code{cond-expand}. @code{FEATURE ...} may be a keyword, string or symbol. @node Unit library - Feature identifiers - unregister-feature!, , Unit library - Feature identifiers - register-feature!, Unit library - Feature identifiers @subsection unregister-feature! @verbatim [procedure] (unregister-feature! FEATURE ...) @end verbatim Unregisters the specified feature-identifiers. @code{FEATURE ...} may be a keyword, string or symbol. @node Unit library - Keywords, Unit library - Exceptions, Unit library - Feature identifiers, Unit library @section Keywords @menu * Unit library - Keywords - get-keyword:: * Unit library - Keywords - keyword?:: * Unit library - Keywords - keyword->string:: * Unit library - Keywords - string->keyword:: @end menu Keywords are special symbols prefixed with @code{#:} that evaluate to themselves. Procedures can use keywords to accept optional named parameters in addition to normal required parameters. Assignment to and bindings of keyword symbols is not allowed. The parameter @code{keyword-style} and the compiler/interpreter option @code{-keyword-style} can be used to allow an additional keyword syntax, either compatible to Common LISP, or to DSSSL. @node Unit library - Keywords - get-keyword, Unit library - Keywords - keyword?, , Unit library - Keywords @subsection get-keyword @verbatim [procedure] (get-keyword KEYWORD ARGLIST [THUNK]) @end verbatim Returns the argument from @code{ARGLIST} specified under the keyword @code{KEYWORD}. If the keyword is not found, then the zero-argument procedure @code{THUNK} is invoked and the result value is returned. If @code{THUNK} is not given, @code{#f} is returned. (define (increase x . args) @verbatim (+ x (get-keyword #:amount args (lambda () 1))) ) @end verbatim (increase 123) ==> 124 (increase 123 #:amount 10) ==> 133 Note: the @code{KEYWORD} may actually be any kind of object. @node Unit library - Keywords - keyword?, Unit library - Keywords - keyword->string, Unit library - Keywords - get-keyword, Unit library - Keywords @subsection keyword? @verbatim [procedure] (keyword? X) @end verbatim Returns @code{#t} if @code{X} is a keyword symbol, or @code{#f} otherwise. @node Unit library - Keywords - keyword->string, Unit library - Keywords - string->keyword, Unit library - Keywords - keyword?, Unit library - Keywords @subsection keyword->string @verbatim [procedure] (keyword->string KEYWORD) @end verbatim Transforms @code{KEYWORD} into a string. @node Unit library - Keywords - string->keyword, , Unit library - Keywords - keyword->string, Unit library - Keywords @subsection string->keyword @verbatim [procedure] (string->keyword STRING) @end verbatim Returns a keyword with the name @code{STRING}. @node Unit library - Exceptions, Unit library - Environment information and system interface, Unit library - Keywords, Unit library @section Exceptions @menu * Unit library - Exceptions - condition-case:: * Unit library - Exceptions - breakpoint:: @end menu CHICKEN implements the (currently withdrawn) @uref{http://srfi.schemers.org/srfi-12/srfi-12.html, SRFI-12} exception system. For more information, see the @uref{http://srfi.schemers.org/srfi-12/srfi-12.html, SRFI-12} document. @node Unit library - Exceptions - condition-case, Unit library - Exceptions - breakpoint, , Unit library - Exceptions @subsection condition-case @verbatim [syntax] (condition-case EXPRESSION CLAUSE ...) @end verbatim Evaluates @code{EXPRESSION} and handles any exceptions that are covered by @code{CLAUSE ...}, where @code{CLAUSE} should be of the following form: CLAUSE = ([VARIABLE] (KIND ...) BODY ...) If provided, @code{VARIABLE} will be bound to the signalled exception object. @code{BODY ...} is executed when the exception is a property- or composite condition with the kinds given @code{KIND ...} (unevaluated). If no clause applies, the exception is re-signalled in the same dynamic context as the @code{condition-case} form. (define (check thunk) @verbatim (condition-case (thunk) [(exn file) (print "file error")] [(exn) (print "other error")] [var () (print "something else")] ) ) @end verbatim (check (lambda () (open-input-file ""))) ; -> "file error" (check (lambda () some-unbound-variable)) ; -> "othererror" (check (lambda () (signal 99))) ; -> "something else" (condition-case some-unbound-variable @verbatim [(exn file) (print "ignored")] ) ; -> signals error @end verbatim @node Unit library - Exceptions - breakpoint, , Unit library - Exceptions - condition-case, Unit library - Exceptions @subsection breakpoint @verbatim [procedure] (breakpoint [NAME]) @end verbatim Programmatically triggers a breakpoint (similar to the @code{,br} top-level csi command). All error-conditions signalled by the system are of kind @code{exn}. The following composite conditions are additionally defined:
(exn arity) Signalled when a procedure is called with the wrong number of arguments.
(exn type) Signalled on type-mismatch errors, for example when an argument of the wrong type is passed to a builtin procedure.
(exn arithmetic) Signalled on arithmetic errors, like division by zero.
(exn i/o) Signalled on input/output errors.
(exn i/o file) Signalled on file-related errors.
(exn i/o net) Signalled on network errors.
(exn bounds) Signalled on errors caused by accessing non-existent elements of a collection.
(exn runtime) Signalled on low-level runtime-system error-situations.
(exn runtime limit) Signalled when an internal limit is exceeded (like running out of memory).
(exn match) Signalled on errors raised by failed matches (see the section on @code{match}).
(exn syntax) Signalled on syntax errors.
(exn breakpoint) Signalled when a breakpoint is reached.
Notes: @itemize @item All error-exceptions (of the kind @code{exn}) are non-continuable. @item Error-exceptions of the @code{exn} kind have additional @code{arguments} and @code{location} properties that contain the arguments passed to the exception-handler and the name of the procedure where the error occurred (if available). @item When the @code{posix} unit is available and used, then a user-interrupt (@code{signal/int}) signals an exception of the kind @code{user-interrupt}. @item the procedure @code{condition-property-accessor} accepts an optional third argument. If the condition does not have a value for the desired property and if the optional argument is given, no error is signalled and the accessor returns the third argument. @item In composite conditionss all properties are currently collected in a single property-list, so in the case that to conditions have the same named property, only one will be visible. @end itemize @node Unit library - Environment information and system interface, Unit library - Execution time, Unit library - Exceptions, Unit library @section Environment information and system interface @menu * Unit library - Environment information and system interface - argv:: * Unit library - Environment information and system interface - exit:: * Unit library - Environment information and system interface - build-platform:: * Unit library - Environment information and system interface - build-style:: * Unit library - Environment information and system interface - chicken-version:: * Unit library - Environment information and system interface - errno:: * Unit library - Environment information and system interface - getenv:: * Unit library - Environment information and system interface - machine-byte-order:: * Unit library - Environment information and system interface - machine-type:: * Unit library - Environment information and system interface - on-exit:: * Unit library - Environment information and system interface - software-type:: * Unit library - Environment information and system interface - software-version:: * Unit library - Environment information and system interface - c-runtime:: * Unit library - Environment information and system interface - system:: @end menu @node Unit library - Environment information and system interface - argv, Unit library - Environment information and system interface - exit, , Unit library - Environment information and system interface @subsection argv @verbatim [procedure] (argv) @end verbatim Return a list of all supplied command-line arguments. The first item in the list is a string containing the name of the executing program. The other items are the arguments passed to the application. This list is freshly created on every invocation of @code{(argv)}. It depends on the host-shell whether arguments are expanded ('globbed') or not. @node Unit library - Environment information and system interface - exit, Unit library - Environment information and system interface - build-platform, Unit library - Environment information and system interface - argv, Unit library - Environment information and system interface @subsection exit @verbatim [procedure] (exit [CODE]) @end verbatim Exit the running process and return exit-code, which defaults to 0 (Invokes @code{exit-handler}). @node Unit library - Environment information and system interface - build-platform, Unit library - Environment information and system interface - build-style, Unit library - Environment information and system interface - exit, Unit library - Environment information and system interface @subsection build-platform @verbatim [procedure] (build-platform) @end verbatim Returns a symbol specifying the toolset which has been used for building the executing system, which is one of the following: @verbatim cygwin msvc mingw32 gnu metrowerks intel watcom unknown @end verbatim @node Unit library - Environment information and system interface - build-style, Unit library - Environment information and system interface - chicken-version, Unit library - Environment information and system interface - build-platform, Unit library - Environment information and system interface @subsection build-style @verbatim [procedure] (build-style) @end verbatim Returns a symbol indicating the build system used to create the CHICKEN instance running this program. Possible values are: @verbatim cmake autotools diy custom @end verbatim @node Unit library - Environment information and system interface - chicken-version, Unit library - Environment information and system interface - errno, Unit library - Environment information and system interface - build-style, Unit library - Environment information and system interface @subsection chicken-version @verbatim [procedure] (chicken-version [FULL]) @end verbatim Returns a string containing the version number of the CHICKEN runtime system. If the optional argument @code{FULL} is given and true, then a full version string is returned. @node Unit library - Environment information and system interface - errno, Unit library - Environment information and system interface - getenv, Unit library - Environment information and system interface - chicken-version, Unit library - Environment information and system interface @subsection errno @verbatim [procedure] (errno) @end verbatim Returns the error code of the last system call. @node Unit library - Environment information and system interface - getenv, Unit library - Environment information and system interface - machine-byte-order, Unit library - Environment information and system interface - errno, Unit library - Environment information and system interface @subsection getenv @verbatim [procedure] (getenv STRING) @end verbatim Returns the value of the environment variable @code{STRING} or @code{#f} if that variable is not defined. @node Unit library - Environment information and system interface - machine-byte-order, Unit library - Environment information and system interface - machine-type, Unit library - Environment information and system interface - getenv, Unit library - Environment information and system interface @subsection machine-byte-order @verbatim [procedure] (machine-byte-order) @end verbatim Returns the symbol @code{little-endian} or @code{big-endian}, depending on the machine's byte-order. @node Unit library - Environment information and system interface - machine-type, Unit library - Environment information and system interface - on-exit, Unit library - Environment information and system interface - machine-byte-order, Unit library - Environment information and system interface @subsection machine-type @verbatim [procedure] (machine-type) @end verbatim Returns a symbol specifying the processor on which this process is currently running, which is one of the following: @verbatim alpha mips hppa ultrasparc sparc ppc ppc64 ia64 x86 x86-64 unknown @end verbatim @node Unit library - Environment information and system interface - on-exit, Unit library - Environment information and system interface - software-type, Unit library - Environment information and system interface - machine-type, Unit library - Environment information and system interface @subsection on-exit @verbatim [procedure] (on-exit THUNK) @end verbatim Schedules the zero-argument procexdures @code{THUNK} to be executed before the process exits, either explicitly via @code{exit} or implicitly after exection of the last toplevel form. Note that finalizers for unreferenced finalized data are run before exit procedures. @node Unit library - Environment information and system interface - software-type, Unit library - Environment information and system interface - software-version, Unit library - Environment information and system interface - on-exit, Unit library - Environment information and system interface @subsection software-type @verbatim [procedure] (software-type) @end verbatim Returns a symbol specifying the operating system on which this process is currently running, which is one of the following: @verbatim windows unix macos ecos unknown @end verbatim @node Unit library - Environment information and system interface - software-version, Unit library - Environment information and system interface - c-runtime, Unit library - Environment information and system interface - software-type, Unit library - Environment information and system interface @subsection software-version @verbatim [procedure] (software-version) @end verbatim Returns a symbol specifying the operating system version on which this process is currently running, which is one of the following: @verbatim linux freebsd netbsd openbsd macosx hpux solaris sunos unknown @end verbatim @node Unit library - Environment information and system interface - c-runtime, Unit library - Environment information and system interface - system, Unit library - Environment information and system interface - software-version, Unit library - Environment information and system interface @subsection c-runtime @verbatim [procedure] (c-runtime) @end verbatim Returns a symbol that designates what kind of C runtime library has been linked with this version of the Chicken libraries. Possible return values are @code{static}, @code{dynamic} or @code{unknown}. On systems not compiled with the Microsoft C compiler, @code{c-runtime} always returns @code{unknown}. @node Unit library - Environment information and system interface - system, , Unit library - Environment information and system interface - c-runtime, Unit library - Environment information and system interface @subsection system @verbatim [procedure] (system STRING) @end verbatim Execute shell command. The functionality offered by this procedure depends on the capabilities of the host shell. If the forking of a subprocess failed, an exception is raised. Otherwise the return status of the subprocess is returned unaltered. @node Unit library - Execution time, Unit library - Interrupts and error-handling, Unit library - Environment information and system interface, Unit library @section Execution time @menu * Unit library - Execution time - cpu-time:: * Unit library - Execution time - current-milliseconds:: * Unit library - Execution time - current-seconds:: * Unit library - Execution time - current-gc-milliseconds:: @end menu @node Unit library - Execution time - cpu-time, Unit library - Execution time - current-milliseconds, , Unit library - Execution time @subsection cpu-time @verbatim [procedure] (cpu-time) @end verbatim Returns the used CPU time of the current process in milliseconds as two values: the time spent in user code, and the time spent in system code. On platforms where user and system time can not be differentiated, system time will be always be 0. @node Unit library - Execution time - current-milliseconds, Unit library - Execution time - current-seconds, Unit library - Execution time - cpu-time, Unit library - Execution time @subsection current-milliseconds @verbatim [procedure] (current-milliseconds) @end verbatim Returns the number of milliseconds since process- or machine startup. @node Unit library - Execution time - current-seconds, Unit library - Execution time - current-gc-milliseconds, Unit library - Execution time - current-milliseconds, Unit library - Execution time @subsection current-seconds @verbatim [procedure] (current-seconds) @end verbatim Returns the number of seconds since midnight, Jan. 1, 1970. @node Unit library - Execution time - current-gc-milliseconds, , Unit library - Execution time - current-seconds, Unit library - Execution time @subsection current-gc-milliseconds @verbatim [procedure] (current-gc-milliseconds) @end verbatim Returns the number of milliseconds spent in major garbage collections since the last call of @code{current-gc-milliseconds} and returns an exact integer. @node Unit library - Interrupts and error-handling, Unit library - Garbage collection, Unit library - Execution time, Unit library @section Interrupts and error-handling @menu * Unit library - Interrupts and error-handling - enable-warnings:: * Unit library - Interrupts and error-handling - error:: * Unit library - Interrupts and error-handling - get-call-chain:: * Unit library - Interrupts and error-handling - print-call-chain:: * Unit library - Interrupts and error-handling - print-error-message:: * Unit library - Interrupts and error-handling - procedure-information:: * Unit library - Interrupts and error-handling - reset:: * Unit library - Interrupts and error-handling - warning:: * Unit library - Interrupts and error-handling - singlestep:: @end menu @node Unit library - Interrupts and error-handling - enable-warnings, Unit library - Interrupts and error-handling - error, , Unit library - Interrupts and error-handling @subsection enable-warnings @verbatim [procedure] (enable-warnings [BOOL]) @end verbatim Enables or disables warnings, depending on wether @code{BOOL} is true or false. If called with no arguments, this procedure returns @code{#t} if warnings are currently enabled, or @code{#f} otherwise. Note that this is not a parameter. The current state (whether warnings are enabled or disabled) is global and not thread-local. @node Unit library - Interrupts and error-handling - error, Unit library - Interrupts and error-handling - get-call-chain, Unit library - Interrupts and error-handling - enable-warnings, Unit library - Interrupts and error-handling @subsection error @verbatim [procedure] (error [LOCATION] [STRING] EXP ...) @end verbatim Prints error message, writes all extra arguments to the value of @code{(current-error-port)} and invokes the current exception-handler. This conforms to @uref{http://srfi.schemers.org/srfi-23/srfi-23.html, SRFI-23}. If @code{LOCATION} is given and a symbol, it specifies the @emph{location} (the name of the procedure) where the error occurred. @node Unit library - Interrupts and error-handling - get-call-chain, Unit library - Interrupts and error-handling - print-call-chain, Unit library - Interrupts and error-handling - error, Unit library - Interrupts and error-handling @subsection get-call-chain @verbatim [procedure] (get-call-chain [START [THREAD]]) @end verbatim Returns a list with the call history. Backtrace information is only generated in code compiled without @code{-no-trace} and evaluated code. If the optional argument @code{START} is given, the backtrace starts at this offset, i.e. when @code{START} is 1, the next to last trace-entry is printed, and so on. If the optional argument @code{THREAD} is given, then the call-chain will only be constructed for calls performed by this thread. @node Unit library - Interrupts and error-handling - print-call-chain, Unit library - Interrupts and error-handling - print-error-message, Unit library - Interrupts and error-handling - get-call-chain, Unit library - Interrupts and error-handling @subsection print-call-chain @verbatim [procedure] (print-call-chain [PORT [START [THREAD]]]) @end verbatim Prints a backtrace of the procedure call history to @code{PORT}, which defaults to @code{(current-output-port)}. @node Unit library - Interrupts and error-handling - print-error-message, Unit library - Interrupts and error-handling - procedure-information, Unit library - Interrupts and error-handling - print-call-chain, Unit library - Interrupts and error-handling @subsection print-error-message @verbatim [procedure] (print-error-message EXN [PORT [STRING]]) @end verbatim Prints an appropriate error message to @code{PORT} (which defaults to the value of @code{(current-output-port)} for the object @code{EXN}. @code{EXN} may be a condition, a string or any other object. If the optional argument @code{STRING} is given, it is printed before the error-message. @code{STRING} defaults to @code{"Error:"}. @node Unit library - Interrupts and error-handling - procedure-information, Unit library - Interrupts and error-handling - reset, Unit library - Interrupts and error-handling - print-error-message, Unit library - Interrupts and error-handling @subsection procedure-information @verbatim [procedure] (procedure-information PROC) @end verbatim Returns an s-expression with debug information for the procedure @code{PROC}, or @code{#f}, if @code{PROC} has no associated debug information. @node Unit library - Interrupts and error-handling - reset, Unit library - Interrupts and error-handling - warning, Unit library - Interrupts and error-handling - procedure-information, Unit library - Interrupts and error-handling @subsection reset @verbatim [procedure] (reset) @end verbatim Reset program (Invokes @code{reset-handler}). @node Unit library - Interrupts and error-handling - warning, Unit library - Interrupts and error-handling - singlestep, Unit library - Interrupts and error-handling - reset, Unit library - Interrupts and error-handling @subsection warning @verbatim [procedure] (warning STRING EXP ...) @end verbatim Displays a warning message (if warnings are enabled with @code{enable-warnings}) and continues execution. @node Unit library - Interrupts and error-handling - singlestep, , Unit library - Interrupts and error-handling - warning, Unit library - Interrupts and error-handling @subsection singlestep @verbatim [procedure] (singlestep THUNK) @end verbatim Executes the code in the zero-procedure @code{THUNK} in single-stepping mode. @node Unit library - Garbage collection, Unit library - Other control structures, Unit library - Interrupts and error-handling, Unit library @section Garbage collection @menu * Unit library - Garbage collection - gc:: * Unit library - Garbage collection - memory-statistics:: * Unit library - Garbage collection - set-finalizer!:: * Unit library - Garbage collection - set-gc-report!:: @end menu @node Unit library - Garbage collection - gc, Unit library - Garbage collection - memory-statistics, , Unit library - Garbage collection @subsection gc @verbatim [procedure] (gc [FLAG]) @end verbatim Invokes a garbage-collection and returns the number of free bytes in the heap. The flag specifies whether a minor (@code{#f}) or major (@code{#t}) GC is to be triggered. If no argument is given, @code{#t} is assumed. When the argument is @code{#t}, all pending finalizers are executed. @node Unit library - Garbage collection - memory-statistics, Unit library - Garbage collection - set-finalizer!, Unit library - Garbage collection - gc, Unit library - Garbage collection @subsection memory-statistics @verbatim [procedure] (memory-statistics) @end verbatim Performs a major garbage collection and returns a three element vector containing the total heap size in bytes, the number of bytes currently used and the size of the nursery (the first heap generation). Note that the actual heap is actually twice the size given in the heap size, because CHICKEN uses a copying semi-space collector. @node Unit library - Garbage collection - set-finalizer!, Unit library - Garbage collection - set-gc-report!, Unit library - Garbage collection - memory-statistics, Unit library - Garbage collection @subsection set-finalizer! @verbatim [procedure] (set-finalizer! X PROC) @end verbatim Registers a procedure of one argument @code{PROC}, that will be called as soon as the non-immediate data object @code{X} is about to be garbage-collected (with that object as its argument). Note that the finalizer will @b{not} be called while interrupts are disabled. This procedure returns @code{X}. @node Unit library - Garbage collection - set-gc-report!, , Unit library - Garbage collection - set-finalizer!, Unit library - Garbage collection @subsection set-gc-report! @verbatim [procedure] (set-gc-report! FLAG) @end verbatim Print statistics after every GC, depending on @code{FLAG}. A value of @code{#t} shows statistics after every major GC. A true value different from @code{#t} shows statistics after every minor GC. @code{#f} switches statistics off. @node Unit library - Other control structures, Unit library - String utilities, Unit library - Garbage collection, Unit library @section Other control structures @menu * Unit library - Other control structures - andmap:: * Unit library - Other control structures - ormap:: * Unit library - Other control structures - promise?:: @end menu @node Unit library - Other control structures - andmap, Unit library - Other control structures - ormap, , Unit library - Other control structures @subsection andmap @verbatim [procedure] (andmap PROC LIST1 ...) @end verbatim Repeatedly calls @code{PROC} with arguments taken from @code{LIST1 ...}. If any invocation should return @code{#f}, the result of @code{andmap} is @code{#f}. If all invocations return a true result, then the result of @code{andmap} is @code{#t}. @node Unit library - Other control structures - ormap, Unit library - Other control structures - promise?, Unit library - Other control structures - andmap, Unit library - Other control structures @subsection ormap @verbatim [procedure] (ormap PROC LIST1 ...) @end verbatim Repeatedly calls @code{PROC} with arguments taken from @code{LIST1 ...}. If any invocation should return a value different from @code{#f}, then this value is returned as the result of @code{ormap}. If all invocations return @b{#f}, then the result of @code{ormap} is @code{#f}. @node Unit library - Other control structures - promise?, , Unit library - Other control structures - ormap, Unit library - Other control structures @subsection promise? @verbatim [procedure] (promise? X) @end verbatim Returns @code{#t} if @code{X} is a promise returned by @code{delay}, or @code{#f} otherwise. @node Unit library - String utilities, Unit library - Generating uninterned symbols, Unit library - Other control structures, Unit library @section String utilities @menu * Unit library - String utilities - reverse-list->string:: @end menu @node Unit library - String utilities - reverse-list->string, , , Unit library - String utilities @subsection reverse-list->string @verbatim [procedure] (reverse-list->string LIST) @end verbatim Returns a string with the characters in @code{LIST} in reverse order. This is equivalent to @code{(list->string (reverse LIST))}, but much more efficient. @node Unit library - Generating uninterned symbols, Unit library - Standard Input/Output, Unit library - String utilities, Unit library @section Generating uninterned symbols @menu * Unit library - Generating uninterned symbols - gensym:: * Unit library - Generating uninterned symbols - string->uninterned-symbol:: @end menu @node Unit library - Generating uninterned symbols - gensym, Unit library - Generating uninterned symbols - string->uninterned-symbol, , Unit library - Generating uninterned symbols @subsection gensym @verbatim [procedure] (gensym [STRING-OR-SYMBOL]) @end verbatim Returns a newly created uninterned symbol. If an argument is provided, the new symbol is prefixed with that argument. @node Unit library - Generating uninterned symbols - string->uninterned-symbol, , Unit library - Generating uninterned symbols - gensym, Unit library - Generating uninterned symbols @subsection string->uninterned-symbol @verbatim [procedure] (string->uninterned-symbol STRING) @end verbatim Returns a newly created, unique symbol with the name @code{STRING}. @node Unit library - Standard Input/Output, Unit library - User-defined named characters, Unit library - Generating uninterned symbols, Unit library @section Standard Input/Output @menu * Unit library - Standard Input/Output - port?:: * Unit library - Standard Input/Output - print:: * Unit library - Standard Input/Output - print*:: @end menu @node Unit library - Standard Input/Output - port?, Unit library - Standard Input/Output - print, , Unit library - Standard Input/Output @subsection port? @verbatim [procedure] (port? X) @end verbatim Returns @code{#t} if @code{X} is a port object or @code{#f} otherwise. @node Unit library - Standard Input/Output - print, Unit library - Standard Input/Output - print*, Unit library - Standard Input/Output - port?, Unit library - Standard Input/Output @subsection print @verbatim [procedure] (print EXP1 EXP2 ...) @end verbatim Outputs the arguments @code{EXP1 EXP2 ...} using @code{display} and writes a newline character to the port that is the value of @code{(current-output-port)}. Returns its first argument. @node Unit library - Standard Input/Output - print*, , Unit library - Standard Input/Output - print, Unit library - Standard Input/Output @subsection print* @verbatim [procedure] (print* EXP1 ...) @end verbatim Similar to @code{print}, but does not output a terminating newline character and performs a @code{flush-outout} after writing its arguments. @node Unit library - User-defined named characters, Unit library - Vectors, Unit library - Standard Input/Output, Unit library @section User-defined named characters @menu * Unit library - User-defined named characters - char-name:: @end menu @node Unit library - User-defined named characters - char-name, , , Unit library - User-defined named characters @subsection char-name @verbatim [procedure] (char-name SYMBOL-OR-CHAR [CHAR]) @end verbatim This procedure can be used to inquire about character names or to define new ones. With a single argument the behavior is as follows: If @code{SYMBOL-OR-CHAR} is a symbol, then @code{char-name} returns the character with this name, or @code{#f} if no character is defined under this name. If @code{SYMBOL-OR-CHAR} is a character, then the name of the character is returned as a symbol, or @code{#f} if the character has no associated name. If the optional argument @code{CHAR} is provided, then @code{SYMBOL-OR-CHAR} should be a symbol that will be the new name of the given character. If multiple names designate the same character, then the @code{write} will use the character name that was defined last. (char-name 'space) ==> #\space (char-name #\space) ==> space (char-name 'bell) ==> #f (char-name (integer->char 7)) ==> #f (char-name 'bell (integer->char 7)) (char-name 'bell) ==> #\bell (char->integer (char-name 'bell)) ==> 7 @node Unit library - Vectors, Unit library - The unspecified value, Unit library - User-defined named characters, Unit library @section Vectors @menu * Unit library - Vectors - vector-copy!:: * Unit library - Vectors - vector-resize:: @end menu @node Unit library - Vectors - vector-copy!, Unit library - Vectors - vector-resize, , Unit library - Vectors @subsection vector-copy! @verbatim [procedure] (vector-copy! VECTOR1 VECTOR2 [COUNT]) @end verbatim Copies contents of @code{VECTOR1} into @code{VECTOR2}. If the argument @code{COUNT} is given, it specifies the maximal number of elements to be copied. If not given, the minimum of the lengths of the argument vectors is copied. Exceptions: @code{(exn bounds)} @node Unit library - Vectors - vector-resize, , Unit library - Vectors - vector-copy!, Unit library - Vectors @subsection vector-resize @verbatim [procedure] (vector-resize VECTOR N [INIT]) @end verbatim Creates and returns a new vector with the contents of @code{VECTOR} and length @code{N}. If @code{N} is greater than the original length of @code{VECTOR}, then all additional items are initialized to @code{INIT}. If @code{INIT} is not specified, the contents are initialized to some unspecified value. @node Unit library - The unspecified value, Unit library - Continuations, Unit library - Vectors, Unit library @section The unspecified value @menu * Unit library - The unspecified value - void:: @end menu @node Unit library - The unspecified value - void, , , Unit library - The unspecified value @subsection void @verbatim [procedure] (void) @end verbatim Returns an unspecified value. @node Unit library - Continuations, Unit library - Setters, Unit library - The unspecified value, Unit library @section Continuations @menu * Unit library - Continuations - call/cc:: * Unit library - Continuations - continuation-capture:: * Unit library - Continuations - continuation?:: * Unit library - Continuations - continuation-graft:: * Unit library - Continuations - continuation-return:: @end menu @node Unit library - Continuations - call/cc, Unit library - Continuations - continuation-capture, , Unit library - Continuations @subsection call/cc @verbatim [procedure] (call/cc PROCEDURE) @end verbatim An alias for @code{call-with-current-continuation}. @node Unit library - Continuations - continuation-capture, Unit library - Continuations - continuation?, Unit library - Continuations - call/cc, Unit library - Continuations @subsection continuation-capture @verbatim [procedure] (continuation-capture PROCEDURE) @end verbatim Creates a continuation object representing the current continuation and tail-calls @code{PROCEDURE} with this continuation as the single argument. More information about this continuation API can be found in the paper @uref{http://repository.readscheme.org/ftp/papers/sw2001/feeley.pdf, http://repository.readscheme.org/ftp/papers/sw2001/feeley.pdf} @emph{A Better API for first class Continuations} by Marc Feeley. @node Unit library - Continuations - continuation?, Unit library - Continuations - continuation-graft, Unit library - Continuations - continuation-capture, Unit library - Continuations @subsection continuation? @verbatim [procedure] (continuation? X) @end verbatim Returns @code{#t} if @code{X} is a continuation object, or @code{#f} otherwise. @node Unit library - Continuations - continuation-graft, Unit library - Continuations - continuation-return, Unit library - Continuations - continuation?, Unit library - Continuations @subsection continuation-graft @verbatim [procedure] (continuation-graft CONT THUNK) @end verbatim Calls the procedure @code{THUNK} with no arguments and the implicit continuation @code{CONT}. @node Unit library - Continuations - continuation-return, , Unit library - Continuations - continuation-graft, Unit library - Continuations @subsection continuation-return @verbatim [procedure] (continuation-return CONT VALUE ...) @end verbatim Returns the value(s) to the continuation @code{CONT}. @code{continuation-return} could be implemented like this: (define (continuation-return k . vals) @verbatim (continuation-graft k (lambda () (apply values vals)) ) ) @end verbatim @node Unit library - Setters, Unit library - Reader extensions, Unit library - Continuations, Unit library @section Setters @menu * Unit library - Setters - setter:: * Unit library - Setters - getter-with-setter:: @end menu SRFI-17 is fully implemented. For more information see: @uref{http://srfi.schemers.org/srfi-17/srfi-17.html, SRFI-17}. @node Unit library - Setters - setter, Unit library - Setters - getter-with-setter, , Unit library - Setters @subsection setter @verbatim [procedure] (setter PROCEDURE) @end verbatim Returns the setter-procedure of @code{PROCEDURE}, or signals an error if @code{PROCEDURE} has no associated setter-procedure. Note that @code{(set! (setter PROC) ...)} for a procedure that has no associated setter procedure yet is a very slow operation (the old procedure is replaced by a modified copy, which involves a garbage collection). @node Unit library - Setters - getter-with-setter, , Unit library - Setters - setter, Unit library - Setters @subsection getter-with-setter @verbatim [procedure] (getter-with-setter GETTER SETTER) @end verbatim Returns a copy of the procedure @code{GETTER} with the associated setter procedure @code{SETTER}. Contrary to the SRFI specification, the setter of the returned procedure may be changed. @node Unit library - Reader extensions, , Unit library - Setters, Unit library @section Reader extensions @menu * Unit library - Reader extensions - define-reader-ctor:: * Unit library - Reader extensions - set-read-syntax!:: * Unit library - Reader extensions - set-sharp-read-syntax!:: * Unit library - Reader extensions - set-parameterized-read-syntax!:: * Unit library - Reader extensions - copy-read-table:: @end menu @node Unit library - Reader extensions - define-reader-ctor, Unit library - Reader extensions - set-read-syntax!, , Unit library - Reader extensions @subsection define-reader-ctor @verbatim [procedure] (define-reader-ctor SYMBOL PROC) @end verbatim Define new read-time constructor for @code{#,} read syntax. For further information, see the documentation for @uref{http://srfi.schemers.org/srfi-10/srfi-10.html, SRFI-10}. @node Unit library - Reader extensions - set-read-syntax!, Unit library - Reader extensions - set-sharp-read-syntax!, Unit library - Reader extensions - define-reader-ctor, Unit library - Reader extensions @subsection set-read-syntax! @verbatim [procedure] (set-read-syntax! CHAR-OR-SYMBOL PROC) @end verbatim When the reader is encounting the non-whitespace character @code{CHAR} while reading an expression from a given port, then the procedure @code{PROC} will be called with that port as its argument. The procedure should return a value that will be returned to the reader: @verbatim ; A simple RGB color syntax: @end verbatim @verbatim (set-read-syntax! #\% (lambda (port) (apply vector (map (cut string->number <> 16) @end verbatim (string-chop (read-string 6 port) 2) ) ) ) ) @verbatim (with-input-from-string "(1 2 %f0f0f0 3)" read) ; ==> (1 2 #(240 240 240) 3) @end verbatim If @code{CHAR-OR-SYMBOL} is a symbol, then a so-called @emph{read-mark} handler is defined. In that case the handler procedure will be called when a character-sequence of the form @verbatim #!SYMBOL @end verbatim is encountered. You can undo special handling of read-syntax by passing @code{#f} as the second argument (if the syntax was previously defined via @code{set-read-syntax!}). Note that all of CHICKEN's special non-standard read-syntax is handled directly by the reader. To disable built-in read-syntax, define a handler that triggers an error (for example). @node Unit library - Reader extensions - set-sharp-read-syntax!, Unit library - Reader extensions - set-parameterized-read-syntax!, Unit library - Reader extensions - set-read-syntax!, Unit library - Reader extensions @subsection set-sharp-read-syntax! @verbatim [procedure] (set-sharp-read-syntax! CHAR-OR-SYMBOL PROC) @end verbatim Similar to @code{set-read-syntax!}, but allows defining new @code{# ...} reader syntax. If the first argument is a symbol, then this procedure is equivalent to @code{set-read-syntax!}. @node Unit library - Reader extensions - set-parameterized-read-syntax!, Unit library - Reader extensions - copy-read-table, Unit library - Reader extensions - set-sharp-read-syntax!, Unit library - Reader extensions @subsection set-parameterized-read-syntax! @verbatim [procedure] (set-parameterized-read-syntax! CHAR-OR-SYMBOL PROC) @end verbatim Similar to @code{set-sharp-read-syntax!}, but intended for defining reader syntax of the form @code{# ...}. The handler procedure @code{PROC} will be called with two arguments: the input port and the number preceding the dispatching character. If the first argument is a symbol, then this procedure is equivalent to @code{set-read-syntax!}. @node Unit library - Reader extensions - copy-read-table, , Unit library - Reader extensions - set-parameterized-read-syntax!, Unit library - Reader extensions @subsection copy-read-table @verbatim [procedure] (copy-read-table READ-TABLE) @end verbatim Returns a copy of the given read-table. You can access the currently active read-table with @code{(current-read-table)}. Previous: @ref{Parameters, Parameters} Next: @ref{Unit eval, Unit eval} @node Unit eval, Unit extras, Unit library, Top @chapter Unit eval @menu * Unit eval - Loading code:: * Unit eval - Read-eval-print loop:: * Unit eval - Macros:: * Unit eval - Loading extension libraries:: * Unit eval - System information:: * Unit eval - Eval:: @end menu This unit has support for evaluation and macro-handling. This unit is used by default, unless the program is compiled with the @code{-explicit-use} option. @node Unit eval - Loading code, Unit eval - Read-eval-print loop, , Unit eval @section Loading code @menu * Unit eval - Loading code - load:: * Unit eval - Loading code - load-relative:: * Unit eval - Loading code - load-noisily:: * Unit eval - Loading code - load-library:: * Unit eval - Loading code - set-dynamic-load-mode!:: @end menu @node Unit eval - Loading code - load, Unit eval - Loading code - load-relative, , Unit eval - Loading code @subsection load @verbatim [procedure] (load FILE [EVALPROC]) @end verbatim Loads and evaluates expressions from the given source file, which may be either a string or an input port. Each expression read is passed to @code{EVALPROC} (which defaults to @code{eval}). On platforms that support it (currently native Windows, Linux ELF and Solaris), @code{load} can be used to load compiled programs: @verbatim % cat x.scm (define (hello) (print "Hello!")) % csc -s x.scm % csi -q #;1> (load "x.so") ; loading x.so ... #;2> (hello) Hello! #;3> @end verbatim The second argument to @code{load} is ignored when loading compiled code. If source code is loaded from a port, then that port is closed after all expressions have been read. Compiled code can be re-loaded, but care has to be taken, if code from the replaced dynamically loaded module is still executing (i.e. if an active continuation refers to compiled code in the old module). Support for reloading compiled code dynamically is still experimental. @node Unit eval - Loading code - load-relative, Unit eval - Loading code - load-noisily, Unit eval - Loading code - load, Unit eval - Loading code @subsection load-relative @verbatim [procedure] (load-relative FILE [EVALPROC]) @end verbatim Similar to @code{load}, but loads @code{FILE} relative to the path of the currently loaded file. @node Unit eval - Loading code - load-noisily, Unit eval - Loading code - load-library, Unit eval - Loading code - load-relative, Unit eval - Loading code @subsection load-noisily @verbatim [procedure] (load-noisily FILE #!key EVALUATOR TIME PRINTER) @end verbatim As @code{load} but the result(s) of each evaluated toplevel-expression is written to standard output. If @code{EVALUATOR} is given and not @code{#f}, then each expression is evaluated by calling this argument with the read expression as argument. If @code{TIME} is given and not false, then the execution time of each expression is shown (as with the @code{time} macro). If @code{PRINTER} is given and not false, then each expression is printed before evaluation by applying the expression to the value of this argument, which should be a one-argument procedure. See also the @uref{http://chicken.wiki.br/Parameters#load-verbose, load-verbose} parameter. @node Unit eval - Loading code - load-library, Unit eval - Loading code - set-dynamic-load-mode!, Unit eval - Loading code - load-noisily, Unit eval - Loading code @subsection load-library @verbatim [procedure] (load-library UNIT [LIBRARYFILE]) @end verbatim On platforms that support dynamic loading, @code{load-library} loads the compiled library unit @code{UNIT} (which should be a symbol). If the string @code{LIBRARYFILE} is given, then the given shared library will be loaded and the toplevel code of the contained unit will be executed. If no @code{LIBRARYFILE} argument is given, then the following libraries are checked for the required unit: @itemize @item a file named @emph{@code{.so}} @item the files given in the parameter @code{dynamic-load-libraries} @end itemize If the unit is not found, an error is signaled. When the library unit can be successfully loaded, a feature-identifier named @code{UNIT} is registered. If the feature is already registered before loading, the @code{load-library} does nothing. @node Unit eval - Loading code - set-dynamic-load-mode!, , Unit eval - Loading code - load-library, Unit eval - Loading code @subsection set-dynamic-load-mode! @verbatim [procedure] (set-dynamic-load-mode! MODELIST) @end verbatim On systems that support dynamic loading of compiled code via the @code{dlopen(3)} interface (for example Linux and Solaris), some options can be specified to fine-tune the behaviour of the dynamic linker. @code{MODE} should be a list of symbols (or a single symbol) taken from the following set: @table @b @item @code{local} If @code{local} is given, then any C/C++ symbols defined in the dynamically loaded file are not available for subsequently loaded files and libraries. Use this if you have linked foreign code into your dynamically loadable file and if you don't want to export them (for example because you want to load another file that defines the same symbols). @item @code{global} The default is @code{global}, which means all C/C++ symbols are available to code loaded at a later stage. @item @code{now} If @code{now} is specified, all symbols are resolved immediately. @item @code{lazy} Unresolved symbols are resolved as code from the file is executed. This is the default. @end table Note that this procedure does not control the way Scheme variables are handled - this facility is mainly of interest when accessing foreign code. @node Unit eval - Read-eval-print loop, Unit eval - Macros, Unit eval - Loading code, Unit eval @section Read-eval-print loop @menu * Unit eval - Read-eval-print loop - repl:: @end menu @node Unit eval - Read-eval-print loop - repl, , , Unit eval - Read-eval-print loop @subsection repl @verbatim [procedure] (repl) @end verbatim Start a new read-eval-print loop. Sets the @code{reset-handler} so that any invocation of @code{reset} restarts the read-eval-print loop. Also changes the current exception-handler to display a message, write any arguments to the value of @code{(current-error-port)} and reset. @node Unit eval - Macros, Unit eval - Loading extension libraries, Unit eval - Read-eval-print loop, Unit eval @section Macros @menu * Unit eval - Macros - get-line-number:: * Unit eval - Macros - macro?:: * Unit eval - Macros - macroexpand:: * Unit eval - Macros - macroexpand-1:: * Unit eval - Macros - undefine-macro!:: * Unit eval - Macros - syntax-error:: @end menu @node Unit eval - Macros - get-line-number, Unit eval - Macros - macro?, , Unit eval - Macros @subsection get-line-number @verbatim [procedure] (get-line-number EXPR) @end verbatim If @code{EXPR} is a pair with the car being a symbol, and line-number information is available for this expression, then this procedure returns the associated line number. If line-number information is not available, then @code{#f} is returned. Note that line-number information for expressions is only available in the compiler. @node Unit eval - Macros - macro?, Unit eval - Macros - macroexpand, Unit eval - Macros - get-line-number, Unit eval - Macros @subsection macro? @verbatim [procedure] (macro? SYMBOL) @end verbatim Returns @code{#t} if there exists a macro-definition for @code{SYMBOL}. @node Unit eval - Macros - macroexpand, Unit eval - Macros - macroexpand-1, Unit eval - Macros - macro?, Unit eval - Macros @subsection macroexpand @verbatim [procedure] (macroexpand X) @end verbatim If @code{X} is a macro-form, expand the macro (and repeat expansion until expression is a non-macro form). Returns the resulting expression. @node Unit eval - Macros - macroexpand-1, Unit eval - Macros - undefine-macro!, Unit eval - Macros - macroexpand, Unit eval - Macros @subsection macroexpand-1 @verbatim [procedure] (macroexpand-1 X) @end verbatim If @code{X} is a macro-form, expand the macro. Returns the resulting expression. @node Unit eval - Macros - undefine-macro!, Unit eval - Macros - syntax-error, Unit eval - Macros - macroexpand-1, Unit eval - Macros @subsection undefine-macro! @verbatim [procedure] (undefine-macro! SYMBOL) @end verbatim Remove the current macro-definition of the macro named @code{SYMBOL}. @node Unit eval - Macros - syntax-error, , Unit eval - Macros - undefine-macro!, Unit eval - Macros @subsection syntax-error @verbatim [procedure] (syntax-error [LOCATION] MESSAGE ARGUMENT ...) @end verbatim Signals an exception of the kind @code{(exn syntax)}. Otherwise identical to @code{error}. @node Unit eval - Loading extension libraries, Unit eval - System information, Unit eval - Macros, Unit eval @section Loading extension libraries @menu * Unit eval - Loading extension libraries - repository-path:: * Unit eval - Loading extension libraries - extension-information:: * Unit eval - Loading extension libraries - provide:: * Unit eval - Loading extension libraries - provided?:: * Unit eval - Loading extension libraries - require:: * Unit eval - Loading extension libraries - set-extension-specifier!:: @end menu This functionality is only available on platforms that support dynamic loading of compiled code. Currently Linux, BSD, Solaris, Windows (with Cygwin) and HP/UX are supported. @node Unit eval - Loading extension libraries - repository-path, Unit eval - Loading extension libraries - extension-information, , Unit eval - Loading extension libraries @subsection repository-path @table @b @item [parameter] repository-path @end table Contains a string naming the path to the extension repository, which defaults to either the value of the environment variable @code{CHICKEN_REPOSITORY}, the value of the environment variable @code{CHICKEN_HOME} or the default library path (usually @code{/usr/local/lib/chicken} on UNIX systems). @node Unit eval - Loading extension libraries - extension-information, Unit eval - Loading extension libraries - provide, Unit eval - Loading extension libraries - repository-path, Unit eval - Loading extension libraries @subsection extension-information @verbatim [procedure] (extension-information ID) @end verbatim If an extension with the name @code{ID} is installed and if it has a setup-information list registered in the extension repository, then the info-list is returned. Otherwise @code{extension-information} returns @code{#f}. @node Unit eval - Loading extension libraries - provide, Unit eval - Loading extension libraries - provided?, Unit eval - Loading extension libraries - extension-information, Unit eval - Loading extension libraries @subsection provide @verbatim [procedure] (provide ID ...) @end verbatim Registers the extension IDs @code{ID ...} as loaded. This is mainly intended to provide aliases for certain extension identifiers. @node Unit eval - Loading extension libraries - provided?, Unit eval - Loading extension libraries - require, Unit eval - Loading extension libraries - provide, Unit eval - Loading extension libraries @subsection provided? @verbatim [procedure] (provided? ID ...) @end verbatim Returns @code{#t} if the extension with the IDs @code{ID ...} are currently loaded, or @code{#f} otherwise. @node Unit eval - Loading extension libraries - require, Unit eval - Loading extension libraries - set-extension-specifier!, Unit eval - Loading extension libraries - provided?, Unit eval - Loading extension libraries @subsection require @verbatim [procedure] (require ID ...) [procedure] (require-for-syntax ID ...) @end verbatim If the extension library @code{ID} is not already loaded into the system, then @code{require} will lookup the location of the shared extension library and load it. If @code{ID} names a library-unit of the base system, then it is loaded via @code{load-library}. If no extension library is available for the given ID, then an attempt is made to load the file @code{ID.so} or @code{ID.scm} (in that order) from one of the following locations: @itemize @item the current include path, which defaults to the pathnames given in @code{CHICKEN_INCLUDE_PATH} and @code{CHICKEN_HOME}. @item the current directory @end itemize @code{ID} should be a string or a symbol. The difference between @code{require} and @code{require-for-syntax} is the the latter loads the extension library at compile-time (the argument is still evaluated), while the former loads it at run-time. @node Unit eval - Loading extension libraries - set-extension-specifier!, , Unit eval - Loading extension libraries - require, Unit eval - Loading extension libraries @subsection set-extension-specifier! @verbatim [procedure] (set-extension-specifier! SYMBOL PROC) @end verbatim Registers the handler-procedure @code{PROC} as a extension-specifier with the name @code{SYMBOL}. This facility allows extending the set of valid extension specifiers to be used with @code{require-extension}. When @code{register-extension} is called with an extension specifier of the form @code{(SPEC ...)} and @code{SPEC} has been registered with @code{set-extension-specifier!}, then @code{PROC} will be called with two arguments: the specifier and the previously installed handler (or @code{#f} if no such handler was defined). The handler should return a new specifier that will be processed recursively. If the handler returns a vector, then each element of the vector will be processed recursively. Alternatively the handler may return a string which specifies a file to be loaded: (eval-when (compile eval) @verbatim (set-extension-specifier! 'my-package (lambda (spec old) (make-pathname my-package-directory (->string (cadr spec))) ) ) ) @end verbatim (require-extension (my-package stuff)) ; --> expands into '(load "my-package-dir/stuff") Note that the handler has to be registered at compile time, if it is to be visible in compiled code. @node Unit eval - System information, Unit eval - Eval, Unit eval - Loading extension libraries, Unit eval @section System information @menu * Unit eval - System information - chicken-home:: @end menu @node Unit eval - System information - chicken-home, , , Unit eval - System information @subsection chicken-home @verbatim [procedure] (chicken-home) @end verbatim Returns a string given the installation directory (usually @code{/usr/local/share/chicken} on UNIX-like systems). If the environment variable @code{CHICKEN_HOME} is set, then its value will be returned. As a last option, if the environment variable @code{CHICKEN_PREFIX} is set, then @code{chicken-home} will return @code{$CHICKEN_PREFIX/share}. @node Unit eval - Eval, , Unit eval - System information, Unit eval @section Eval @menu * Unit eval - Eval - eval:: @end menu @node Unit eval - Eval - eval, , , Unit eval - Eval @subsection eval @verbatim [procedure] (eval EXP [ENVIRONMENT]) @end verbatim Evaluates @code{EXP} and returns the result of the evaluation. The second argument is optional and defaults to the value of @code{(interaction-environment)}. Previous: @ref{Unit library, Unit library} Next: @ref{Unit extras, Unit extras} @node Unit extras, Unit srfi-1, Unit eval, Top @chapter Unit extras @menu * Unit extras - Lists:: * Unit extras - String-port extensions:: * Unit extras - Formatted output:: * Unit extras - Hash tables:: * Unit extras - Queues:: * Unit extras - Sorting:: * Unit extras - Random numbers:: * Unit extras - Input/Output extensions:: * Unit extras - Strings:: * Unit extras - Combinators:: * Unit extras - Binary searching:: @end menu This unit contains a collection of useful utility definitions. This unit is used by default, unless the program is compiled with the @code{-explicit-use} option. @node Unit extras - Lists, Unit extras - String-port extensions, , Unit extras @section Lists @menu * Unit extras - Lists - alist-ref:: * Unit extras - Lists - alist-update!:: * Unit extras - Lists - atom?:: * Unit extras - Lists - rassoc:: * Unit extras - Lists - butlast:: * Unit extras - Lists - chop:: * Unit extras - Lists - compress:: * Unit extras - Lists - flatten:: * Unit extras - Lists - intersperse:: * Unit extras - Lists - join:: * Unit extras - Lists - shuffle:: * Unit extras - Lists - tail?:: @end menu @node Unit extras - Lists - alist-ref, Unit extras - Lists - alist-update!, , Unit extras - Lists @subsection alist-ref @verbatim [procedure] (alist-ref KEY ALIST [TEST [DEFAULT]]) @end verbatim Looks up @code{KEY} in @code{ALIST} using @code{TEST} as the comparison function (or @code{eqv?} if no test was given) and returns the cdr of the found pair, or @code{DEFAULT} (which defaults to @code{#f}). @node Unit extras - Lists - alist-update!, Unit extras - Lists - atom?, Unit extras - Lists - alist-ref, Unit extras - Lists @subsection alist-update! @verbatim [procedure] (alist-update! KEY VALUE ALIST [TEST]) @end verbatim If the list @code{ALIST} contains a pair of the form @code{(KEY . X)}, then this procedure replaces @code{X} with @code{VALUE} and returns @code{ALIST}. If @code{ALIST} contains no such item, then @code{alist-update!} returns @code{((KEY . VALUE) . ALIST)}. The optional argument @code{TEST} specifies the comparison procedure to search a matching pair in @code{ALIST} and defaults to @code{eqv?}. @node Unit extras - Lists - atom?, Unit extras - Lists - rassoc, Unit extras - Lists - alist-update!, Unit extras - Lists @subsection atom? @verbatim [procedure] (atom? X) @end verbatim Returns @code{#t} if @code{X} is not a pair. This is identical to @code{not-pair?} from @ref{Unit srfi-1, Unit srfi-1} but kept for historical reasons. @node Unit extras - Lists - rassoc, Unit extras - Lists - butlast, Unit extras - Lists - atom?, Unit extras - Lists @subsection rassoc @verbatim [procedure] (rassoc KEY LIST [TEST]) @end verbatim Similar to @code{assoc}, but compares @code{KEY} with the @code{cdr} of each pair in @code{LIST} using @code{TEST} as the comparison procedures (which defaults to @code{eqv?}. @node Unit extras - Lists - butlast, Unit extras - Lists - chop, Unit extras - Lists - rassoc, Unit extras - Lists @subsection butlast @verbatim [procedure] (butlast LIST) @end verbatim Returns a fresh list with all elements but the last of @code{LIST}. @node Unit extras - Lists - chop, Unit extras - Lists - compress, Unit extras - Lists - butlast, Unit extras - Lists @subsection chop @verbatim [procedure] (chop LIST N) @end verbatim Returns a new list of sublists, where each sublist contains @code{N} elements of @code{LIST}. If @code{LIST} has a length that is not a multiple of @code{N}, then the last sublist contains the remaining elements. (chop '(1 2 3 4 5 6) 2) ==> ((1 2) (3 4) (5 6)) (chop '(a b c d) 3) ==> ((a b c) (d)) @node Unit extras - Lists - compress, Unit extras - Lists - flatten, Unit extras - Lists - chop, Unit extras - Lists @subsection compress @verbatim [procedure] (compress BLIST LIST) @end verbatim Returns a new list with elements taken from @code{LIST} with corresponding true values in the list @code{BLIST}. (define nums '(99 100 110 401 1234)) (compress (map odd? nums) nums) ==> (99 401) @node Unit extras - Lists - flatten, Unit extras - Lists - intersperse, Unit extras - Lists - compress, Unit extras - Lists @subsection flatten @verbatim [procedure] (flatten LIST1 ...) @end verbatim Returns @code{LIST1 ...} concatenated together, with nested lists removed (flattened). @node Unit extras - Lists - intersperse, Unit extras - Lists - join, Unit extras - Lists - flatten, Unit extras - Lists @subsection intersperse @verbatim [procedure] (intersperse LIST X) @end verbatim Returns a new list with @code{X} placed between each element. @node Unit extras - Lists - join, Unit extras - Lists - shuffle, Unit extras - Lists - intersperse, Unit extras - Lists @subsection join @verbatim [procedure] (join LISTOFLISTS [LIST]) @end verbatim Concatenates the lists in @code{LISTOFLISTS} with @code{LIST} placed between each sublist. @code{LIST} defaults to the empty list. (join '((a b) (c d) (e)) '(x y)) ==> (a b x y c d x y e) (join '((p q) () (r (s) t)) '(-)) ==> (p q - - r (s) t) @code{join} could be implemented as follows: (define (join lstoflsts #!optional (lst '())) @verbatim (apply append (intersperse lstoflists lst)) ) @end verbatim @node Unit extras - Lists - shuffle, Unit extras - Lists - tail?, Unit extras - Lists - join, Unit extras - Lists @subsection shuffle @verbatim [procedure] (shuffle LIST) @end verbatim Returns @code{LIST} with its elements sorted in a random order. @node Unit extras - Lists - tail?, , Unit extras - Lists - shuffle, Unit extras - Lists @subsection tail? @verbatim [procedure] (tail? X LIST) @end verbatim Returns true if @code{X} is one of the tails (cdr's) of @code{LIST}. @node Unit extras - String-port extensions, Unit extras - Formatted output, Unit extras - Lists, Unit extras @section String-port extensions @menu * Unit extras - String-port extensions - call-with-input-string:: * Unit extras - String-port extensions - call-with-output-string:: * Unit extras - String-port extensions - with-input-from-string:: * Unit extras - String-port extensions - with-output-to-string:: @end menu @node Unit extras - String-port extensions - call-with-input-string, Unit extras - String-port extensions - call-with-output-string, , Unit extras - String-port extensions @subsection call-with-input-string @verbatim [procedure] (call-with-input-string STRING PROC) @end verbatim Calls the procedure @code{PROC} with a single argument that is a string-input-port with the contents of @code{STRING}. @node Unit extras - String-port extensions - call-with-output-string, Unit extras - String-port extensions - with-input-from-string, Unit extras - String-port extensions - call-with-input-string, Unit extras - String-port extensions @subsection call-with-output-string @verbatim [procedure] (call-with-output-string PROC) @end verbatim Calls the procedure @code{PROC} with a single argument that is a string-output-port. Returns the accumulated output-string. @node Unit extras - String-port extensions - with-input-from-string, Unit extras - String-port extensions - with-output-to-string, Unit extras - String-port extensions - call-with-output-string, Unit extras - String-port extensions @subsection with-input-from-string @verbatim [procedure] (with-input-from-string STRING THUNK) @end verbatim Call procedure @code{THUNK} with the current input-port temporarily bound to an input-string-port with the contents of @code{STRING}. @node Unit extras - String-port extensions - with-output-to-string, , Unit extras - String-port extensions - with-input-from-string, Unit extras - String-port extensions @subsection with-output-to-string @verbatim [procedure] (with-output-to-string THUNK) @end verbatim Call procedure @code{THUNK} with the current output-port temporarily bound to a string-output-port and return the accumulated output string. @node Unit extras - Formatted output, Unit extras - Hash tables, Unit extras - String-port extensions, Unit extras @section Formatted output @menu * Unit extras - Formatted output - printf:: * Unit extras - Formatted output - fprintf:: * Unit extras - Formatted output - sprintf:: * Unit extras - Formatted output - format:: @end menu @node Unit extras - Formatted output - printf, Unit extras - Formatted output - fprintf, , Unit extras - Formatted output @subsection printf @node Unit extras - Formatted output - fprintf, Unit extras - Formatted output - sprintf, Unit extras - Formatted output - printf, Unit extras - Formatted output @subsection fprintf @node Unit extras - Formatted output - sprintf, Unit extras - Formatted output - format, Unit extras - Formatted output - fprintf, Unit extras - Formatted output @subsection sprintf @verbatim [procedure] (fprintf PORT FORMATSTRING ARG ...) [procedure] (printf FORMATSTRING ARG) [procedure] (sprintf FORMATSTRING ARG ...) @end verbatim Simple formatted output to a given port (@code{fprintf}), the value of @code{(current-output-port)} (@code{printf}) or a string (@code{sprintf}). The @code{FORMATSTRING} can contain any sequence of characters. The character `~' prefixes special formatting directives:
~% write newline character
~N the same as @code{~%}
~S write the next argument
~A display the next argument
~\n skip all whitespace in the format-string until the next non-whitespace character
~B write the next argument as a binary number
~O write the next argument as an octal number
~X write the next argument as a hexadecimal number
~C write the next argument as a character
~~ display `~'
~! flush all pending output
~? invoke formatted output routine recursively with the next two arguments as format-string and list of parameters
@node Unit extras - Formatted output - format, , Unit extras - Formatted output - sprintf, Unit extras - Formatted output @subsection format @verbatim [procedure] (format [DESTINATION] FORMATSTRING ARG ...) @end verbatim The parameters @code{FORMATSTRING} and @code{ARG ...} are as for (@code{printf}/@code{sprintf}/@code{fprintf}). The optional @code{DESTINATION}, when supplied, performs a (@code{sprintf}) for a @code{#f}, a (@code{printf}) for a @code{#t}, and a (@code{fprintf}) for an output-port. When missing a (@code{sprintf}) is performed. @node Unit extras - Hash tables, Unit extras - Queues, Unit extras - Formatted output, Unit extras @section Hash tables @menu * Unit extras - Hash tables - hash-table-remove!:: @end menu CHICKEN implements SRFI-69. For more information, see @uref{http://srfi.schemers.org/srfi-69/srfi-69.html, SRFI-69}. A setter for @code{hash-table-ref} is defined, so (set! (hash-table-ref HT KEY) VAL) is equivalent to (hash-table-set! HT KEY VAL) As an extension to SRFI-69, @code{hash-table-update!} and @code{hash-table-update!/default} return the new value (after applying the update procedure). @node Unit extras - Hash tables - hash-table-remove!, , , Unit extras - Hash tables @subsection hash-table-remove! @verbatim [procedure] (hash-table-remove! HASHTABLE PROC) @end verbatim Calls @code{PROC} for all entries in @code{HASHTABLE} with the key and value of each entry. If @code{PROC} returns true, then that entry is removed. @node Unit extras - Queues, Unit extras - Sorting, Unit extras - Hash tables, Unit extras @section Queues @menu * Unit extras - Queues - list->queue:: * Unit extras - Queues - make-queue:: * Unit extras - Queues - queue?:: * Unit extras - Queues - queue->list:: * Unit extras - Queues - queue-add!:: * Unit extras - Queues - queue-empty?:: * Unit extras - Queues - queue-first:: * Unit extras - Queues - queue-last:: * Unit extras - Queues - queue-remove!:: * Unit extras - Queues - queue-push-back!:: * Unit extras - Queues - queue-push-back-list!:: @end menu @node Unit extras - Queues - list->queue, Unit extras - Queues - make-queue, , Unit extras - Queues @subsection list->queue @verbatim [procedure] (list->queue LIST) @end verbatim Returns @code{LIST} converted into a queue, where the first element of the list is the same as the first element of the queue. The resulting queue may share memory with the list and the list should not be modified after this operation. @node Unit extras - Queues - make-queue, Unit extras - Queues - queue?, Unit extras - Queues - list->queue, Unit extras - Queues @subsection make-queue @verbatim [procedure] (make-queue) @end verbatim Returns a newly created queue. @node Unit extras - Queues - queue?, Unit extras - Queues - queue->list, Unit extras - Queues - make-queue, Unit extras - Queues @subsection queue? @verbatim [procedure] (queue? X) @end verbatim Returns @code{#t} if @code{X} is a queue, or @code{#f} otherwise. @node Unit extras - Queues - queue->list, Unit extras - Queues - queue-add!, Unit extras - Queues - queue?, Unit extras - Queues @subsection queue->list @verbatim [procedure] (queue->list QUEUE) @end verbatim Returns @code{QUEUE} converted into a list, where the first element of the list is the same as the first element of the queue. The resulting list may share memory with the queue object and should not be modified. @node Unit extras - Queues - queue-add!, Unit extras - Queues - queue-empty?, Unit extras - Queues - queue->list, Unit extras - Queues @subsection queue-add! @verbatim [procedure] (queue-add! QUEUE X) @end verbatim Adds @code{X} to the rear of @code{QUEUE}. @node Unit extras - Queues - queue-empty?, Unit extras - Queues - queue-first, Unit extras - Queues - queue-add!, Unit extras - Queues @subsection queue-empty? @verbatim [procedure] (queue-empty? QUEUE) @end verbatim Returns @code{#t} if @code{QUEUE} is empty, or @code{#f} otherwise. @node Unit extras - Queues - queue-first, Unit extras - Queues - queue-last, Unit extras - Queues - queue-empty?, Unit extras - Queues @subsection queue-first @verbatim [procedure] (queue-first QUEUE) @end verbatim Returns the first element of @code{QUEUE}. If @code{QUEUE} is empty an error is signaled @node Unit extras - Queues - queue-last, Unit extras - Queues - queue-remove!, Unit extras - Queues - queue-first, Unit extras - Queues @subsection queue-last @verbatim [procedure] (queue-last QUEUE) @end verbatim Returns the last element of @code{QUEUE}. If @code{QUEUE} is empty an error is signaled @node Unit extras - Queues - queue-remove!, Unit extras - Queues - queue-push-back!, Unit extras - Queues - queue-last, Unit extras - Queues @subsection queue-remove! @verbatim [procedure] (queue-remove! QUEUE) @end verbatim Removes and returns the first element of @code{QUEUE}. If @code{QUEUE} is empty an error is signaled @node Unit extras - Queues - queue-push-back!, Unit extras - Queues - queue-push-back-list!, Unit extras - Queues - queue-remove!, Unit extras - Queues @subsection queue-push-back! @verbatim [procedure] (queue-push-back! QUEUE ITEM) @end verbatim Pushes an item into the first position of a queue, i.e. the next @code{queue-remove!} will return @code{ITEM}. @node Unit extras - Queues - queue-push-back-list!, , Unit extras - Queues - queue-push-back!, Unit extras - Queues @subsection queue-push-back-list! @verbatim [procedure] (queue-push-back-list! QUEUE LIST) @end verbatim Pushes the items in item-list back onto the queue, so that @code{(car LIST)} becomes the next removable item. @node Unit extras - Sorting, Unit extras - Random numbers, Unit extras - Queues, Unit extras @section Sorting @menu * Unit extras - Sorting - merge:: * Unit extras - Sorting - sort:: * Unit extras - Sorting - sorted?:: @end menu @node Unit extras - Sorting - merge, Unit extras - Sorting - sort, , Unit extras - Sorting @subsection merge @verbatim [procedure] (merge LIST1 LIST2 LESS?) [procedure] (merge! LIST1 LIST2 LESS?) @end verbatim Joins two lists in sorted order. @code{merge!} is the destructive version of merge. @code{LESS? } should be a procedure of two arguments, that returns true if the first argument is to be ordered before the second argument. @node Unit extras - Sorting - sort, Unit extras - Sorting - sorted?, Unit extras - Sorting - merge, Unit extras - Sorting @subsection sort @verbatim [procedure] (sort SEQUENCE LESS?) [procedure] (sort! SEQUENCE LESS?) @end verbatim Sort @code{SEQUENCE}, which should be a list or a vector. @code{sort!} is the destructive version of sort. @node Unit extras - Sorting - sorted?, , Unit extras - Sorting - sort, Unit extras - Sorting @subsection sorted? @verbatim [procedure] (sorted? SEQUENCE LESS?) @end verbatim Returns true if the list or vector @code{SEQUENCE} is already sorted. @node Unit extras - Random numbers, Unit extras - Input/Output extensions, Unit extras - Sorting, Unit extras @section Random numbers @menu * Unit extras - Random numbers - random:: * Unit extras - Random numbers - randomize:: @end menu @node Unit extras - Random numbers - random, Unit extras - Random numbers - randomize, , Unit extras - Random numbers @subsection random @verbatim [procedure] (random N) @end verbatim Returns an exact random integer from 0 to @code{N}-1. @node Unit extras - Random numbers - randomize, , Unit extras - Random numbers - random, Unit extras - Random numbers @subsection randomize @verbatim [procedure] (randomize [X]) @end verbatim Set random-number seed. If @code{X} is not supplied, the current time is used. On startup (when the @code{extras} unit is initialized), the random number generator is initialized with the current time. @node Unit extras - Input/Output extensions, Unit extras - Strings, Unit extras - Random numbers, Unit extras @section Input/Output extensions @menu * Unit extras - Input/Output extensions - make-input-port:: * Unit extras - Input/Output extensions - make-output-port:: * Unit extras - Input/Output extensions - pretty-print:: * Unit extras - Input/Output extensions - pretty-print-width:: * Unit extras - Input/Output extensions - read-byte:: * Unit extras - Input/Output extensions - write-byte:: * Unit extras - Input/Output extensions - read-file:: * Unit extras - Input/Output extensions - read-line:: * Unit extras - Input/Output extensions - write-line:: * Unit extras - Input/Output extensions - read-lines:: * Unit extras - Input/Output extensions - read-string:: * Unit extras - Input/Output extensions - read-string!:: * Unit extras - Input/Output extensions - write-string:: * Unit extras - Input/Output extensions - read-token:: * Unit extras - Input/Output extensions - with-error-output-to-port:: * Unit extras - Input/Output extensions - with-input-from-port:: * Unit extras - Input/Output extensions - with-output-to-port:: @end menu @node Unit extras - Input/Output extensions - make-input-port, Unit extras - Input/Output extensions - make-output-port, , Unit extras - Input/Output extensions @subsection make-input-port @verbatim [procedure] (make-input-port READ READY? CLOSE [PEEK]) @end verbatim Returns a custom input port. Common operations on this port are handled by the given parameters, which should be procedures of no arguments. @code{READ} is called when the next character is to be read and should return a character or @code{#!eof}. @code{READY?} is called when @code{char-ready?} is called on this port and should return @code{#t} or @code{#f}. @code{CLOSE} is called when the port is closed. @code{PEEK} is called when @code{peek-char} is called on this port and should return a character or @code{#!eof}. if the argument @code{PEEK} is not given, then @code{READ} is used instead and the created port object handles peeking automatically (by calling @code{READ} and buffering the character). @node Unit extras - Input/Output extensions - make-output-port, Unit extras - Input/Output extensions - pretty-print, Unit extras - Input/Output extensions - make-input-port, Unit extras - Input/Output extensions @subsection make-output-port @verbatim [procedure] (make-output-port WRITE CLOSE [FLUSH]) @end verbatim Returns a custom output port. Common operations on this port are handled by the given parameters, which should be procedures. @code{WRITE} is called when output is sent to the port and receives a single argument, a string. @code{CLOSE} is called when the port is closed and should be a procedure of no arguments. @code{FLUSH} (if provided) is called for flushing the output port. @node Unit extras - Input/Output extensions - pretty-print, Unit extras - Input/Output extensions - pretty-print-width, Unit extras - Input/Output extensions - make-output-port, Unit extras - Input/Output extensions @subsection pretty-print @verbatim [procedure] (pretty-print EXP [PORT]) [procedure] (pp EXP [PORT]) @end verbatim Print expression nicely formatted. @code{PORT} defaults to the value of @code{(current-output-port)}. @node Unit extras - Input/Output extensions - pretty-print-width, Unit extras - Input/Output extensions - read-byte, Unit extras - Input/Output extensions - pretty-print, Unit extras - Input/Output extensions @subsection pretty-print-width (Parameter) Specifies the maximal line-width for pretty printing, after which line wrap will occur. @node Unit extras - Input/Output extensions - read-byte, Unit extras - Input/Output extensions - write-byte, Unit extras - Input/Output extensions - pretty-print-width, Unit extras - Input/Output extensions @subsection read-byte @node Unit extras - Input/Output extensions - write-byte, Unit extras - Input/Output extensions - read-file, Unit extras - Input/Output extensions - read-byte, Unit extras - Input/Output extensions @subsection write-byte @verbatim [procedure] (read-byte [PORT]) [procedure] (write-byte BYTE [PORT]) @end verbatim Read/write a byte to the port given in @code{PORT}, which default to the values of @code{(current-input-port)} and @code{(current-output-port)}, respectively. @node Unit extras - Input/Output extensions - read-file, Unit extras - Input/Output extensions - read-line, Unit extras - Input/Output extensions - write-byte, Unit extras - Input/Output extensions @subsection read-file @verbatim [procedure] (read-file [FILE-OR-PORT [READER [MAXCOUNT]]]) @end verbatim Returns a list containing all toplevel expressions read from the file or port @code{FILE-OR-PORT}. If no argument is given, input is read from the port that is the current value of @code{(current-input-port)}. After all expressions are read, and if the argument is a port, then the port will not be closed. The @code{READER} argument specifies the procedure used to read expressions from the given file or port and defaults to @code{read}. The reader procedure will be called with a single argument (an input port). If @code{MAXCOUNT} is given then only up to @code{MAXCOUNT} expressions will be read in. @node Unit extras - Input/Output extensions - read-line, Unit extras - Input/Output extensions - write-line, Unit extras - Input/Output extensions - read-file, Unit extras - Input/Output extensions @subsection read-line @node Unit extras - Input/Output extensions - write-line, Unit extras - Input/Output extensions - read-lines, Unit extras - Input/Output extensions - read-line, Unit extras - Input/Output extensions @subsection write-line @verbatim [procedure] (read-line [PORT [LIMIT]]) [procedure] (write-line STRING [PORT]) @end verbatim Line-input and -output. @code{PORT} defaults to the value of @code{(current-input-port)} and @code{(current-output-port)}, respectively. if the optional argument @code{LIMIT} is given and not @code{#f}, then @code{read-line} reads at most @code{LIMIT} characters per line. @node Unit extras - Input/Output extensions - read-lines, Unit extras - Input/Output extensions - read-string, Unit extras - Input/Output extensions - write-line, Unit extras - Input/Output extensions @subsection read-lines @verbatim [procedure] (read-lines [PORT [MAX]]) @end verbatim Read @code{MAX} or fewer lines from @code{PORT}. @code{PORT} defaults to the value of @code{(current-input-port)}. @code{PORT} may optionally be a string naming a file. @node Unit extras - Input/Output extensions - read-string, Unit extras - Input/Output extensions - read-string!, Unit extras - Input/Output extensions - read-lines, Unit extras - Input/Output extensions @subsection read-string @node Unit extras - Input/Output extensions - read-string!, Unit extras - Input/Output extensions - write-string, Unit extras - Input/Output extensions - read-string, Unit extras - Input/Output extensions @subsection read-string! @node Unit extras - Input/Output extensions - write-string, Unit extras - Input/Output extensions - read-token, Unit extras - Input/Output extensions - read-string!, Unit extras - Input/Output extensions @subsection write-string @verbatim [procedure] (read-string [NUM [PORT]]) [procedure] (read-string! NUM STRING [PORT [START]]) [procedure] (write-string STRING [NUM [PORT]] @end verbatim Read or write @code{NUM} characters from/to @code{PORT}, which defaults to the value of @code{(current-input-port)} or @code{(current-output-port)}, respectively. If @code{NUM} is @code{#f} or not given, then all data up to the end-of-file is read, or, in the case of @code{write-string} the whole string is written. If no more input is available, @code{read-string} returns the empty string. @code{read-string!} reads destructively into the given @code{STRING} argument, but never more characters that would fit into @code{STRING}. If @code{START} is given, then the read characters are stored starting at that position. @code{read-string!} returns the actual number of characters read. @node Unit extras - Input/Output extensions - read-token, Unit extras - Input/Output extensions - with-error-output-to-port, Unit extras - Input/Output extensions - write-string, Unit extras - Input/Output extensions @subsection read-token @verbatim [procedure] (read-token PREDICATE [PORT]) @end verbatim Reads characters from @code{PORT} (which defaults to the value of @code{(current-input-port)}) and calls the procedure @code{PREDICATE} with each character until @code{PREDICATE} returns false. Returns a string with the accumulated characters. @node Unit extras - Input/Output extensions - with-error-output-to-port, Unit extras - Input/Output extensions - with-input-from-port, Unit extras - Input/Output extensions - read-token, Unit extras - Input/Output extensions @subsection with-error-output-to-port @verbatim [procedure] (with-error-output-to-port PORT THUNK) @end verbatim Call procedure @code{THUNK} with the current error output-port temporarily bound to @code{PORT}. @node Unit extras - Input/Output extensions - with-input-from-port, Unit extras - Input/Output extensions - with-output-to-port, Unit extras - Input/Output extensions - with-error-output-to-port, Unit extras - Input/Output extensions @subsection with-input-from-port @verbatim [procedure] (with-input-from-port PORT THUNK) @end verbatim Call procedure @code{THUNK} with the current input-port temporarily bound to @code{PORT}. @node Unit extras - Input/Output extensions - with-output-to-port, , Unit extras - Input/Output extensions - with-input-from-port, Unit extras - Input/Output extensions @subsection with-output-to-port @verbatim [procedure] (with-output-to-port PORT THUNK) @end verbatim Call procedure @code{THUNK} with the current output-port temporarily bound to @code{PORT}. @node Unit extras - Strings, Unit extras - Combinators, Unit extras - Input/Output extensions, Unit extras @section Strings @menu * Unit extras - Strings - conc:: * Unit extras - Strings - ->string:: * Unit extras - Strings - string-chop:: * Unit extras - Strings - string-chomp:: * Unit extras - Strings - string-compare3:: * Unit extras - Strings - string-intersperse:: * Unit extras - Strings - string-split:: * Unit extras - Strings - string-translate:: * Unit extras - Strings - string-translate*:: * Unit extras - Strings - substring=?:: * Unit extras - Strings - substring-index:: @end menu @node Unit extras - Strings - conc, Unit extras - Strings - ->string, , Unit extras - Strings @subsection conc @verbatim [procedure] (conc X ...) @end verbatim Returns a string with the string-represenation of all arguments concatenated together. @code{conc} could be implemented as (define (conc . args) @verbatim (apply string-append (map ->string args)) ) @end verbatim @node Unit extras - Strings - ->string, Unit extras - Strings - string-chop, Unit extras - Strings - conc, Unit extras - Strings @subsection ->string @verbatim [procedure] (->string X) @end verbatim Returns a string-representation of @code{X}. @node Unit extras - Strings - string-chop, Unit extras - Strings - string-chomp, Unit extras - Strings - ->string, Unit extras - Strings @subsection string-chop @verbatim [procedure] (string-chop STRING LENGTH) @end verbatim Returns a list of substrings taken by @emph{chopping} @code{STRING} every @code{LENGTH} characters: (string-chop "one two three" 4) ==> ("one " "two " "thre" "e") @node Unit extras - Strings - string-chomp, Unit extras - Strings - string-compare3, Unit extras - Strings - string-chop, Unit extras - Strings @subsection string-chomp @verbatim [procedure] (string-chomp STRING [SUFFIX]) @end verbatim If @code{STRING} ends with @code{SUFFIX}, then this procedure returns a copy of its first argument with the suffix removed, otherwise returns @code{STRING} unchanged. @code{SUFFIX} defaults to @code{"\n"}. @node Unit extras - Strings - string-compare3, Unit extras - Strings - string-intersperse, Unit extras - Strings - string-chomp, Unit extras - Strings @subsection string-compare3 @verbatim [procedure] (string-compare3 STRING1 STRING2) [procedure] (string-compare3-ci STRING1 STRING2) @end verbatim Perform a three-way comparison between the @code{STRING1} and @code{STRING2}, returning either @code{-1} if @code{STRING1} is lexicographically less than @code{STRING2}, @code{0} if it is equal, or @code{1} if it s greater. @code{string-compare3-ci} performs a case-insensitive comparison. @node Unit extras - Strings - string-intersperse, Unit extras - Strings - string-split, Unit extras - Strings - string-compare3, Unit extras - Strings @subsection string-intersperse @verbatim [procedure] (string-intersperse LIST [STRING]) @end verbatim Returns a string that contains all strings in @code{LIST} concatenated together. @code{STRING} is placed between each concatenated string and defaults to @code{" "}. (string-intersperse '("one" "two") "three") is equivalent to (apply string-append (intersperse '("one" "two") "three")) @node Unit extras - Strings - string-split, Unit extras - Strings - string-translate, Unit extras - Strings - string-intersperse, Unit extras - Strings @subsection string-split @verbatim [procedure] (string-split STRING [DELIMITER-STRING [KEEPEMPTY]]) @end verbatim Split string into substrings separated by the given delimiters. If no delimiters are specified, a string comprising the tab, newline and space characters is assumed. If the parameter @code{KEEPEMPTY} is given and not @code{#f}, then empty substrings are retained: (string-split "one two three") ==> ("one" "two" "three") (string-split "foo:bar::baz:" ":" #t) ==> ("foo" "bar" "" "baz" "") @node Unit extras - Strings - string-translate, Unit extras - Strings - string-translate*, Unit extras - Strings - string-split, Unit extras - Strings @subsection string-translate @verbatim [procedure] (string-translate STRING FROM [TO]) @end verbatim Returns a fresh copy of @code{STRING} with characters matching @code{FROM} translated to @code{TO}. If @code{TO} is omitted, then matching characters are removed. @code{FROM} and @code{TO} may be a character, a string or a list. If both @code{FROM} and @code{TO} are strings, then the character at the same position in @code{TO} as the matching character in @code{FROM} is substituted. @node Unit extras - Strings - string-translate*, Unit extras - Strings - substring=?, Unit extras - Strings - string-translate, Unit extras - Strings @subsection string-translate* @verbatim [procedure] (string-translate* STRING SMAP) @end verbatim Substitutes elements of @code{STRING} according to @code{SMAP}. @code{SMAP} should be an association-list where each element of the list is a pair of the form @code{(MATCH \. REPLACEMENT)}. Every occurrence of the string @code{MATCH} in @code{STRING} will be replaced by the string @code{REPLACEMENT}: (string-translate* @verbatim "

this is a \"string\"

" '(("<" . "<") (">" . ">") ("\"" . """)) ) @end verbatim => "<h1>this is a "string"</ht>"
@node Unit extras - Strings - substring=?, Unit extras - Strings - substring-index, Unit extras - Strings - string-translate*, Unit extras - Strings @subsection substring=? @verbatim [procedure] (substring=? STRING1 STRING2 [START1 [START2 [LENGTH]]]) [procedure] (substring-ci=? STRING1 STRING2 [START1 [START2 [LENGTH]]]) @end verbatim Returns @code{#t} if the strings @code{STRING1} and @code{STRING2} are equal, or @code{#f} otherwise. The comparison starts at the positions @code{START1} and @code{START2} (which default to 0), comparing @code{LENGTH} characters (which defaults to the minimum of the remaining length of both strings). @node Unit extras - Strings - substring-index, , Unit extras - Strings - substring=?, Unit extras - Strings @subsection substring-index @verbatim [procedure] (substring-index WHICH WHERE [START]) [procedure] (substring-index-ci WHICH WHERE [START]) @end verbatim Searches for first index in string @code{WHERE} where string @code{WHICH} occurs. If the optional argument @code{START} is given, then the search starts at that index. @code{substring-index-ci} is a case-insensitive version of @code{substring-index}. @node Unit extras - Combinators, Unit extras - Binary searching, Unit extras - Strings, Unit extras @section Combinators @menu * Unit extras - Combinators - any?:: * Unit extras - Combinators - constantly:: * Unit extras - Combinators - complement:: * Unit extras - Combinators - compose:: * Unit extras - Combinators - conjoin:: * Unit extras - Combinators - disjoin:: * Unit extras - Combinators - each:: * Unit extras - Combinators - flip:: * Unit extras - Combinators - identity:: * Unit extras - Combinators - project:: * Unit extras - Combinators - list-of:: * Unit extras - Combinators - noop:: * Unit extras - Combinators - o:: @end menu @node Unit extras - Combinators - any?, Unit extras - Combinators - constantly, , Unit extras - Combinators @subsection any? @verbatim [procedure] (any? X) @end verbatim Ignores its argument and always returns @code{#t}. This is actually useful sometimes. @node Unit extras - Combinators - constantly, Unit extras - Combinators - complement, Unit extras - Combinators - any?, Unit extras - Combinators @subsection constantly @verbatim [procedure] (constantly X ...) @end verbatim Returns a procedure that always returns the values @code{X ...} regardless of the number and value of its arguments. (constantly X) <=> (lambda args X) @node Unit extras - Combinators - complement, Unit extras - Combinators - compose, Unit extras - Combinators - constantly, Unit extras - Combinators @subsection complement @verbatim [procedure] (complement PROC) @end verbatim Returns a procedure that returns the boolean inverse of @code{PROC}. (complement PROC) <=> (lambda (x) (not (PROC x))) @node Unit extras - Combinators - compose, Unit extras - Combinators - conjoin, Unit extras - Combinators - complement, Unit extras - Combinators @subsection compose @verbatim [procedure] (compose PROC1 PROC2 ...) @end verbatim Returns a procedure that represents the composition of the argument-procedures @code{PROC1 PROC2 ...}. (compose F G) <=> (lambda args @verbatim (call-with-values (lambda () (apply G args)) F)) @end verbatim @code{(compose)} is equivalent to @code{values}. @node Unit extras - Combinators - conjoin, Unit extras - Combinators - disjoin, Unit extras - Combinators - compose, Unit extras - Combinators @subsection conjoin @verbatim [procedure] (conjoin PRED ...) @end verbatim Returns a procedure that returns @code{#t} if its argument satisfies the predicates @code{PRED ...}. ((conjoin odd? positive?) 33) ==> #t ((conjoin odd? positive?) -33) ==> #f @node Unit extras - Combinators - disjoin, Unit extras - Combinators - each, Unit extras - Combinators - conjoin, Unit extras - Combinators @subsection disjoin @verbatim [procedure] (disjoin PRED ...) @end verbatim Returns a procedure that returns @code{#t} if its argument satisfies any predicate @code{PRED ...}. ((disjoin odd? positive?) 32) ==> #t ((disjoin odd? positive?) -32) ==> #f @node Unit extras - Combinators - each, Unit extras - Combinators - flip, Unit extras - Combinators - disjoin, Unit extras - Combinators @subsection each @verbatim [procedure] (each PROC ...) @end verbatim Returns a procedure that applies @code{PROC ...} to its arguments, and returns the result(s) of the last procedure application. For example (each pp eval) is equivalent to (lambda args @verbatim (apply pp args) (apply eval args) ) @end verbatim @code{(each PROC)} is equivalent to @code{PROC} and @code{(each)} is equivalent to @code{noop}. @node Unit extras - Combinators - flip, Unit extras - Combinators - identity, Unit extras - Combinators - each, Unit extras - Combinators @subsection flip @verbatim [procedure] (flip PROC) @end verbatim Returns a two-argument procedure that calls @code{PROC} with its arguments swapped: (flip PROC) <=> (lambda (x y) (PROC y x)) @node Unit extras - Combinators - identity, Unit extras - Combinators - project, Unit extras - Combinators - flip, Unit extras - Combinators @subsection identity @verbatim [procedure] (identity X) @end verbatim Returns its sole argument @code{X}. @node Unit extras - Combinators - project, Unit extras - Combinators - list-of, Unit extras - Combinators - identity, Unit extras - Combinators @subsection project @verbatim [procedure] (project N) @end verbatim Returns a procedure that returns its @code{N}th argument (starting from 0). @node Unit extras - Combinators - list-of, Unit extras - Combinators - noop, Unit extras - Combinators - project, Unit extras - Combinators @subsection list-of @verbatim [procedure] (list-of PRED) @end verbatim Returns a procedure of one argument that returns @code{#t} when applied to a list of elements that all satisfy the predicate procedure @code{PRED}, or @code{#f} otherwise. ((list-of even?) '(1 2 3)) ==> #f ((list-of number?) '(1 2 3)) ==> #t @node Unit extras - Combinators - noop, Unit extras - Combinators - o, Unit extras - Combinators - list-of, Unit extras - Combinators @subsection noop @verbatim [procedure] (noop X ...) @end verbatim Ignores it's arguments, does nothing and returns an unspecified value. @node Unit extras - Combinators - o, , Unit extras - Combinators - noop, Unit extras - Combinators @subsection o @verbatim [procedure] (o PROC ...) @end verbatim A single value version of @code{compose} (slightly faster). @code{(o)} is equivalent to @code{identity}. @node Unit extras - Binary searching, , Unit extras - Combinators, Unit extras @section Binary searching @menu * Unit extras - Binary searching - binary-search:: @end menu @node Unit extras - Binary searching - binary-search, , , Unit extras - Binary searching @subsection binary-search @verbatim [procedure] (binary-search SEQUENCE PROC) @end verbatim Performs a binary search in @code{SEQUENCE}, which should be a sorted list or vector. @code{PROC} is called to compare items in the sequence, should accept a single argument and return an exact integer: zero if the searched value is equal to the current item, negative if the searched value is @emph{less} than the current item, and positive otherwise. Returns the index of the found value or @code{#f} otherwise. Previous: @ref{Unit eval, Unit eval} Next: @ref{Unit srfi-1, Unit srfi-1} @node Unit srfi-1, Unit srfi-4, Unit extras, Top @chapter Unit srfi-1 List library, see the documentation for @uref{http://srfi.schemers.org/srfi-1/srfi-1.html, SRFI-1} Previous: @ref{Unit extras, Unit extras} Next: @ref{Unit srfi-4, Unit srfi-4} @node Unit srfi-4, Unit srfi-13, Unit srfi-1, Top @chapter Unit srfi-4 @menu * Unit srfi-4 - make-XXXvector:: * Unit srfi-4 - u8vector->blob:: * Unit srfi-4 - s8vector->blob:: * Unit srfi-4 - u16vector->blob:: * Unit srfi-4 - s16vector->blob:: * Unit srfi-4 - u32vector->blob:: * Unit srfi-4 - s32vector->blob:: * Unit srfi-4 - f32vector->blob:: * Unit srfi-4 - f64vector->blob:: * Unit srfi-4 - u8vector->blob/shared:: * Unit srfi-4 - s8vector->blob/shared:: * Unit srfi-4 - u16vector->blob/shared:: * Unit srfi-4 - s16vector->blob/shared:: * Unit srfi-4 - u32vector->blob/shared:: * Unit srfi-4 - s32vector->blob/shared:: * Unit srfi-4 - f32vector->blob/shared:: * Unit srfi-4 - f64vector->blob/shared:: * Unit srfi-4 - blob->u8vector:: * Unit srfi-4 - blob->s8vector:: * Unit srfi-4 - blob->u16vector:: * Unit srfi-4 - blob->s16vector:: * Unit srfi-4 - blob->u32vector:: * Unit srfi-4 - blob->s32vector:: * Unit srfi-4 - blob->f32vector:: * Unit srfi-4 - blob->f64vector:: * Unit srfi-4 - blob->u8vector/shared:: * Unit srfi-4 - blob->s8vector/shared:: * Unit srfi-4 - blob->u16vector/shared:: * Unit srfi-4 - blob->s16vector/shared:: * Unit srfi-4 - blob->u32vector/shared:: * Unit srfi-4 - blob->s32vector/shared:: * Unit srfi-4 - blob->f32vector/shared:: * Unit srfi-4 - blob->f64vector/shared:: * Unit srfi-4 - subu8vector:: * Unit srfi-4 - subu16vector:: * Unit srfi-4 - subu32vector:: * Unit srfi-4 - subs8vector:: * Unit srfi-4 - subs16vector:: * Unit srfi-4 - subs32vector:: * Unit srfi-4 - subf32vector:: * Unit srfi-4 - subf64vector:: * Unit srfi-4 - read-u8vector:: * Unit srfi-4 - read-u8vector!:: * Unit srfi-4 - write-u8vector:: @end menu Homogeneous numeric vectors, see the documentation for @uref{http://srfi.schemers.org/srfi-4/srfi-4.html, SRFI-4} 64-bit integer vectors (@code{u64vector} and @code{s64vector} are not supported. The basic constructor procedures for number vectors are extended to allow allocating the storage in non garbage collected memory: @node Unit srfi-4 - make-XXXvector, Unit srfi-4 - u8vector->blob, , Unit srfi-4 @section make-XXXvector @verbatim [procedure] (make-XXXvector SIZE [INIT NONGC FINALIZE]) @end verbatim Creates a SRFI-4 homogenous number vector of length @code{SIZE}. If @code{INIT} is given, it specifies the initial value for each slot in the vector. The optional arguments @code{NONGC} and @code{FINALIZE} define whether the vector should be allocated in a memory area not subject to garbage collection and whether the associated storage should be automatically freed (using finalization) when there are no references from Scheme variables and data. @code{NONGC} defaults to @code{#f} (the vector will be located in normal garbage collected memory) and @code{FINALIZE} defaults to @code{#t}. Note that the @code{FINALIZE} argument is only used when @code{NONGC} is true. Additionally, the following procedures are provided: @node Unit srfi-4 - u8vector->blob, Unit srfi-4 - s8vector->blob, Unit srfi-4 - make-XXXvector, Unit srfi-4 @section u8vector->blob @node Unit srfi-4 - s8vector->blob, Unit srfi-4 - u16vector->blob, Unit srfi-4 - u8vector->blob, Unit srfi-4 @section s8vector->blob @node Unit srfi-4 - u16vector->blob, Unit srfi-4 - s16vector->blob, Unit srfi-4 - s8vector->blob, Unit srfi-4 @section u16vector->blob @node Unit srfi-4 - s16vector->blob, Unit srfi-4 - u32vector->blob, Unit srfi-4 - u16vector->blob, Unit srfi-4 @section s16vector->blob @node Unit srfi-4 - u32vector->blob, Unit srfi-4 - s32vector->blob, Unit srfi-4 - s16vector->blob, Unit srfi-4 @section u32vector->blob @node Unit srfi-4 - s32vector->blob, Unit srfi-4 - f32vector->blob, Unit srfi-4 - u32vector->blob, Unit srfi-4 @section s32vector->blob @node Unit srfi-4 - f32vector->blob, Unit srfi-4 - f64vector->blob, Unit srfi-4 - s32vector->blob, Unit srfi-4 @section f32vector->blob @node Unit srfi-4 - f64vector->blob, Unit srfi-4 - u8vector->blob/shared, Unit srfi-4 - f32vector->blob, Unit srfi-4 @section f64vector->blob @node Unit srfi-4 - u8vector->blob/shared, Unit srfi-4 - s8vector->blob/shared, Unit srfi-4 - f64vector->blob, Unit srfi-4 @section u8vector->blob/shared @node Unit srfi-4 - s8vector->blob/shared, Unit srfi-4 - u16vector->blob/shared, Unit srfi-4 - u8vector->blob/shared, Unit srfi-4 @section s8vector->blob/shared @node Unit srfi-4 - u16vector->blob/shared, Unit srfi-4 - s16vector->blob/shared, Unit srfi-4 - s8vector->blob/shared, Unit srfi-4 @section u16vector->blob/shared @node Unit srfi-4 - s16vector->blob/shared, Unit srfi-4 - u32vector->blob/shared, Unit srfi-4 - u16vector->blob/shared, Unit srfi-4 @section s16vector->blob/shared @node Unit srfi-4 - u32vector->blob/shared, Unit srfi-4 - s32vector->blob/shared, Unit srfi-4 - s16vector->blob/shared, Unit srfi-4 @section u32vector->blob/shared @node Unit srfi-4 - s32vector->blob/shared, Unit srfi-4 - f32vector->blob/shared, Unit srfi-4 - u32vector->blob/shared, Unit srfi-4 @section s32vector->blob/shared @node Unit srfi-4 - f32vector->blob/shared, Unit srfi-4 - f64vector->blob/shared, Unit srfi-4 - s32vector->blob/shared, Unit srfi-4 @section f32vector->blob/shared @node Unit srfi-4 - f64vector->blob/shared, Unit srfi-4 - blob->u8vector, Unit srfi-4 - f32vector->blob/shared, Unit srfi-4 @section f64vector->blob/shared @verbatim [procedure] (u8vector->blob U8VECTOR) [procedure] (s8vector->blob S8VECTOR) [procedure] (u16vector->blob U16VECTOR) [procedure] (s16vector->blob S16VECTOR) [procedure] (u32vector->blob U32VECTOR) [procedure] (s32vector->blob S32VECTOR) [procedure] (f32vector->blob F32VECTOR) [procedure] (f64vector->blob F64VECTOR) [procedure] (u8vector->blob/shared U8VECTOR) [procedure] (s8vector->blob/shared S8VECTOR) [procedure] (u16vector->blob/shared U16VECTOR) [procedure] (s16vector->blob/shared S16VECTOR) [procedure] (u32vector->blob/shared U32VECTOR) [procedure] (s32vector->blob/shared S32VECTOR) [procedure] (f32vector->blob/shared F32VECTOR) [procedure] (f64vector->blob/shared F64VECTOR) @end verbatim Each of these procedures return the contents of the given vector as a 'packed' blob. The byte order in that vector is platform-dependent (for example little-endian on an @b{Intel} processor). The @code{/shared} variants return a blob that shares memory with the contents of the vector. @node Unit srfi-4 - blob->u8vector, Unit srfi-4 - blob->s8vector, Unit srfi-4 - f64vector->blob/shared, Unit srfi-4 @section blob->u8vector @node Unit srfi-4 - blob->s8vector, Unit srfi-4 - blob->u16vector, Unit srfi-4 - blob->u8vector, Unit srfi-4 @section blob->s8vector @node Unit srfi-4 - blob->u16vector, Unit srfi-4 - blob->s16vector, Unit srfi-4 - blob->s8vector, Unit srfi-4 @section blob->u16vector @node Unit srfi-4 - blob->s16vector, Unit srfi-4 - blob->u32vector, Unit srfi-4 - blob->u16vector, Unit srfi-4 @section blob->s16vector @node Unit srfi-4 - blob->u32vector, Unit srfi-4 - blob->s32vector, Unit srfi-4 - blob->s16vector, Unit srfi-4 @section blob->u32vector @node Unit srfi-4 - blob->s32vector, Unit srfi-4 - blob->f32vector, Unit srfi-4 - blob->u32vector, Unit srfi-4 @section blob->s32vector @node Unit srfi-4 - blob->f32vector, Unit srfi-4 - blob->f64vector, Unit srfi-4 - blob->s32vector, Unit srfi-4 @section blob->f32vector @node Unit srfi-4 - blob->f64vector, Unit srfi-4 - blob->u8vector/shared, Unit srfi-4 - blob->f32vector, Unit srfi-4 @section blob->f64vector @node Unit srfi-4 - blob->u8vector/shared, Unit srfi-4 - blob->s8vector/shared, Unit srfi-4 - blob->f64vector, Unit srfi-4 @section blob->u8vector/shared @node Unit srfi-4 - blob->s8vector/shared, Unit srfi-4 - blob->u16vector/shared, Unit srfi-4 - blob->u8vector/shared, Unit srfi-4 @section blob->s8vector/shared @node Unit srfi-4 - blob->u16vector/shared, Unit srfi-4 - blob->s16vector/shared, Unit srfi-4 - blob->s8vector/shared, Unit srfi-4 @section blob->u16vector/shared @node Unit srfi-4 - blob->s16vector/shared, Unit srfi-4 - blob->u32vector/shared, Unit srfi-4 - blob->u16vector/shared, Unit srfi-4 @section blob->s16vector/shared @node Unit srfi-4 - blob->u32vector/shared, Unit srfi-4 - blob->s32vector/shared, Unit srfi-4 - blob->s16vector/shared, Unit srfi-4 @section blob->u32vector/shared @node Unit srfi-4 - blob->s32vector/shared, Unit srfi-4 - blob->f32vector/shared, Unit srfi-4 - blob->u32vector/shared, Unit srfi-4 @section blob->s32vector/shared @node Unit srfi-4 - blob->f32vector/shared, Unit srfi-4 - blob->f64vector/shared, Unit srfi-4 - blob->s32vector/shared, Unit srfi-4 @section blob->f32vector/shared @node Unit srfi-4 - blob->f64vector/shared, Unit srfi-4 - subu8vector, Unit srfi-4 - blob->f32vector/shared, Unit srfi-4 @section blob->f64vector/shared @verbatim [procedure] (blob->u8vector BLOB) [procedure] (blob->s8vector BLOB) [procedure] (blob->u16vector BLOB) [procedure] (blob->s16vector BLOB) [procedure] (blob->u32vector BLOB) [procedure] (blob->s32vector BLOB) [procedure] (blob->f32vector BLOB) [procedure] (blob->f64vector BLOB) [procedure] (blob->u8vector/shared BLOB) [procedure] (blob->s8vector/shared BLOB) [procedure] (blob->u16vector/shared BLOB) [procedure] (blob->s16vector/shared BLOB) [procedure] (blob->u32vector/shared BLOB) [procedure] (blob->s32vector/shared BLOB) [procedure] (blob->f32vector/shared BLOB) [procedure] (blob->f64vector/shared BLOB) @end verbatim Each of these procedures return a vector where the argument @code{BLOB} is taken as a 'packed' representation of the contents of the vector. The @code{/shared} variants return a vector that shares memory with the contents of the blob. @node Unit srfi-4 - subu8vector, Unit srfi-4 - subu16vector, Unit srfi-4 - blob->f64vector/shared, Unit srfi-4 @section subu8vector @node Unit srfi-4 - subu16vector, Unit srfi-4 - subu32vector, Unit srfi-4 - subu8vector, Unit srfi-4 @section subu16vector @node Unit srfi-4 - subu32vector, Unit srfi-4 - subs8vector, Unit srfi-4 - subu16vector, Unit srfi-4 @section subu32vector @node Unit srfi-4 - subs8vector, Unit srfi-4 - subs16vector, Unit srfi-4 - subu32vector, Unit srfi-4 @section subs8vector @node Unit srfi-4 - subs16vector, Unit srfi-4 - subs32vector, Unit srfi-4 - subs8vector, Unit srfi-4 @section subs16vector @node Unit srfi-4 - subs32vector, Unit srfi-4 - subf32vector, Unit srfi-4 - subs16vector, Unit srfi-4 @section subs32vector @node Unit srfi-4 - subf32vector, Unit srfi-4 - subf64vector, Unit srfi-4 - subs32vector, Unit srfi-4 @section subf32vector @node Unit srfi-4 - subf64vector, Unit srfi-4 - read-u8vector, Unit srfi-4 - subf32vector, Unit srfi-4 @section subf64vector @verbatim [procedure] (subu8vector U8VECTOR FROM TO) [procedure] (subu16vector U16VECTOR FROM TO) [procedure] (subu32vector U32VECTOR FROM TO) [procedure] (subs8vector S8VECTOR FROM TO) [procedure] (subs16vector S16VECTOR FROM TO) [procedure] (subs32vector S32VECTOR FROM TO) [procedure] (subf32vector F32VECTOR FROM TO) [procedure] (subf64vector F64VECTOR FROM TO) @end verbatim Creates a number vector of the same type as the argument vector with the elements at the positions @code{FROM} up to but not including @code{TO}. SRFI-17 Setters for @code{XXXvector-ref} are defined. @node Unit srfi-4 - read-u8vector, Unit srfi-4 - read-u8vector!, Unit srfi-4 - subf64vector, Unit srfi-4 @section read-u8vector @verbatim [procedure] (read-u8vector LENGTH [PORT]) @end verbatim Reads @code{LENGTH} bytes from the @code{PORT} and returns a fresh @code{u8vector} or less of end-of-file is encountered. @code{PORT} defaults to the value of @code{(current-input-port)}. If @code{LENGTH} is @code{#f}, the vector will be filled completely until end-of-file is reached. @node Unit srfi-4 - read-u8vector!, Unit srfi-4 - write-u8vector, Unit srfi-4 - read-u8vector, Unit srfi-4 @section read-u8vector! @verbatim [procedure] (read-u8vector! LENGTH U8VECTOR [PORT [START]]) @end verbatim Reads @code{LENGTH} bytes from the @code{PORT} writing the read input into @code{U8VECTOR} beginning at @code{START} (or 0 if not given). @code{PORT} defaults to the value of @code{(current-input-port)}. If @code{LENGTH} is @code{#f}, the vector will be filled completely until end-of-file is reached. This procedure returns the number of bytes read. @node Unit srfi-4 - write-u8vector, , Unit srfi-4 - read-u8vector!, Unit srfi-4 @section write-u8vector @verbatim [procedure] (write-u8vector U8VECTOR [PORT [START [END]]]) @end verbatim Writes the bytes @code{U8VECTOR} between the indices @code{START} (inclusive) and @code{END} (exclusive) to @code{PORT}. @code{PORT} defaults to the value of @code{(current-output-port)}. Previous: @ref{Unit srfi-1, Unit srfi-1} Next: @ref{Unit srfi-13, Unit srfi-13} @node Unit srfi-13, Unit srfi-14, Unit srfi-4, Top @chapter Unit srfi-13 String library, see the documentation for @uref{http://srfi.schemers.org/srfi-13/srfi-13.html, SRFI-13} On systems that support dynamic loading, the @code{srfi-13} unit can be made available in the interpreter (@code{csi}) by entering (require-extension srfi-13) Previous: @ref{Unit srfi-4, Unit srfi-4} Next: @ref{Unit srfi-14, Unit srfi-14} @node Unit srfi-14, Unit match, Unit srfi-13, Top @chapter Unit srfi-14 Character set library, see the documentation for @uref{http://srfi.schemers.org/srfi-14/srfi-14.html, SRFI-14} On systems that support dynamic loading, the @code{srfi-14} unit can be made available in the interpreter (@code{csi}) by entering (require-extension srfi-14) This library provides only the Latin-1 character set. Previous: @ref{Unit srfi-13, Unit srfi-13} Next: @ref{Unit match, Unit match} @node Unit match, Unit regex, Unit srfi-14, Top @chapter Unit match The runtime-support code for the @uref{http://chicken.wiki.br/Pattern%20matching, Pattern Matching} extensions. Note that to use the macros in normal compiled code it is not required to declare this unit as used. It is only necessary to do so if forms containing these macros are to be expanded at runtime. Previous: @ref{Unit srfi-14, Unit srfi-14} Next: @ref{Unit regex, Unit regex} @node Unit regex, Unit srfi-18, Unit match, Top @chapter Unit regex @menu * Unit regex - grep:: * Unit regex - glob->regexp:: * Unit regex - glob?:: * Unit regex - regexp:: * Unit regex - regexp?:: * Unit regex - string-match:: * Unit regex - string-match-positions:: * Unit regex - string-search:: * Unit regex - string-search-positions:: * Unit regex - string-split-fields:: * Unit regex - string-substitute:: * Unit regex - string-substitute*:: * Unit regex - regexp-escape:: @end menu This library unit provides support for regular expressions. The regular expression package used is @code{PCRE} (@emph{Perl Compatible Regular Expressions}) written by Philip Hazel. See @uref{http://www.pcre.org, http://www.pcre.org} for information about the particular regexp flavor and extensions provided by this library. To test that PCRE support has been built into Chicken properly, try: (require 'regex) (test-feature? 'pcre) => t @node Unit regex - grep, Unit regex - glob->regexp, , Unit regex @section grep @verbatim [procedure] (grep REGEX LIST) @end verbatim Returns all items of @code{LIST} that match the regular expression @code{REGEX}. This procedure could be defined as follows: (define (grep regex lst) @verbatim (filter (lambda (x) (string-search regex x)) lst) ) @end verbatim @node Unit regex - glob->regexp, Unit regex - glob?, Unit regex - grep, Unit regex @section glob->regexp @verbatim [procedure] (glob->regexp PATTERN) @end verbatim Converts the file-pattern @code{PATTERN} into a regular expression. (glob->regexp "foo.*") => "foo\..*" @code{PATTERN} should follow "glob" syntax. Allowed wildcards are @verbatim * [C...] [C1-C2] [-C...] ? @end verbatim @node Unit regex - glob?, Unit regex - regexp, Unit regex - glob->regexp, Unit regex @section glob? @verbatim [procedure] (glob? STRING) @end verbatim Does the @code{STRING} have any "glob" wildcards? A string without any "glob" wildcards does not meet the criteria, even though it technically is a valid "glob" file-pattern. @node Unit regex - regexp, Unit regex - regexp?, Unit regex - glob?, Unit regex @section regexp @verbatim [procedure] (regexp STRING [IGNORECASE [IGNORESPACE [UTF8]]]) @end verbatim Returns a precompiled regular expression object for @code{string}. The optional arguments @code{IGNORECASE}, @code{IGNORESPACE} and @code{UTF8} specify whether the regular expression should be matched with case- or whitespace-differences ignored, or whether the string should be treated as containing UTF-8 encoded characters, respectively. @node Unit regex - regexp?, Unit regex - string-match, Unit regex - regexp, Unit regex @section regexp? @verbatim [procedure] (regexp? X) @end verbatim Returns @code{#t} if @code{X} is a precompiled regular expression, or @code{#f} otherwise. @node Unit regex - string-match, Unit regex - string-match-positions, Unit regex - regexp?, Unit regex @section string-match @node Unit regex - string-match-positions, Unit regex - string-search, Unit regex - string-match, Unit regex @section string-match-positions @verbatim [procedure] (string-match REGEXP STRING [START]) [procedure] (string-match-positions REGEXP STRING [START]) @end verbatim Matches the regular expression in @code{REGEXP} (a string or a precompiled regular expression) with @code{STRING} and returns either @code{#f} if the match failed, or a list of matching groups, where the first element is the complete match. If the optional argument @code{START} is supplied, it specifies the starting position in @code{STRING}. For each matching group the result-list contains either: @code{#f} for a non-matching but optional group; a list of start- and end-position of the match in @code{STRING} (in the case of @code{string-match-positions}); or the matching substring (in the case of @code{string-match}). Note that the exact string is matched. For searching a pattern inside a string, see below. Note also that @code{string-match} is implemented by calling @code{string-search} with the regular expression wrapped in @code{^ ... $}. If invoked with a precompiled regular expression argument (by using @code{regexp}), @code{string-match} is identical to @code{string-search}. @node Unit regex - string-search, Unit regex - string-search-positions, Unit regex - string-match-positions, Unit regex @section string-search @node Unit regex - string-search-positions, Unit regex - string-split-fields, Unit regex - string-search, Unit regex @section string-search-positions @verbatim [procedure] (string-search REGEXP STRING [START [RANGE]]) [procedure] (string-search-positions REGEXP STRING [START [RANGE]]) @end verbatim Searches for the first match of the regular expression in @code{REGEXP} with @code{STRING}. The search can be limited to @code{RANGE} characters. @node Unit regex - string-split-fields, Unit regex - string-substitute, Unit regex - string-search-positions, Unit regex @section string-split-fields @verbatim [procedure] (string-split-fields REGEXP STRING [MODE [START]]) @end verbatim Splits @code{STRING} into a list of fields according to @code{MODE}, where @code{MODE} can be the keyword @code{#:infix} (@code{REGEXP} matches field separator), the keyword @code{#:suffix} (@code{REGEXP} matches field terminator) or @code{#t} (@code{REGEXP} matches field), which is the default. (define s "this is a string 1, 2, 3,") (string-split-fields "[^ ]+" s) @verbatim => ("this" "is" "a" "string" "1," "2," "3,") @end verbatim (string-split-fields " " s #:infix) @verbatim => ("this" "is" "a" "string" "1," "2," "3,") @end verbatim (string-split-fields "," s #:suffix)) @verbatim => ("this is a string 1" " 2" " 3") @end verbatim @node Unit regex - string-substitute, Unit regex - string-substitute*, Unit regex - string-split-fields, Unit regex @section string-substitute @verbatim [procedure] (string-substitute REGEXP SUBST STRING [MODE]) @end verbatim Searches substrings in @code{STRING} that match @code{REGEXP} and substitutes them with the string @code{SUBST}. The substitution can contain references to subexpressions in @code{REGEXP} with the @code{\NUM} notation, where @code{NUM} refers to the NUMth parenthesized expression. The optional argument @code{MODE} defaults to 1 and specifies the number of the match to be substituted. Any non-numeric index specifies that all matches are to be substituted. (string-substitute "([0-9]+) (eggs|chicks)" @verbatim "\\2 (\\1)" "99 eggs or 99 chicks" 2) @end verbatim => "99 eggs or chicks (99)" Note that a regular expression that matches an empty string will signal an error. @node Unit regex - string-substitute*, Unit regex - regexp-escape, Unit regex - string-substitute, Unit regex @section string-substitute* @verbatim [procedure] (string-substitute* STRING SMAP [MODE]) @end verbatim Substitutes elements of @code{STRING} with @code{string-substitute} according to @code{SMAP}. @code{SMAP} should be an association-list where each element of the list is a pair of the form @code{(MATCH . REPLACEMENT)}. Every occurrence of the regular expression @code{MATCH} in @code{STRING} will be replaced by the string @code{REPLACEMENT} (string-substitute* "

Hello, world!

" @verbatim '(("<[/A-Za-z0-9]+>" . "")))) @end verbatim => "Hello, world!"
@node Unit regex - regexp-escape, , Unit regex - string-substitute*, Unit regex @section regexp-escape @verbatim [procedure] (regexp-escape STRING) @end verbatim Escapes all special characters in @code{STRING} with @code{\}, so that the string can be embedded into a regular expression. (regexp-escape "^[0-9]+:.*$") => "\\^\\[0-9\\]\\+:.\n.\\*\\$" Previous: @ref{Unit match, Unit match} Next: @ref{Unit srfi-18, Unit srfi-18} @node Unit srfi-18, Unit posix, Unit regex, Top @chapter Unit srfi-18 @menu * Unit srfi-18 - thread-signal!:: * Unit srfi-18 - thread-quantum:: * Unit srfi-18 - thread-quantum-set!:: * Unit srfi-18 - thread-suspend!:: * Unit srfi-18 - thread-resume!:: * Unit srfi-18 - time->milliseconds:: @end menu A simple multithreading package. This threading package follows largely the specification of SRFI-18. For more information see the documentation for @uref{http://srfi.schemers.org/srfi-18/srfi-18.html, SRFI-18}. @b{Notes:} @itemize @item @code{thread-start!} accepts a thunk (a zero argument procedure) as argument, which is equivalent to @code{(thread-start! (make-thread THUNK))}. @item @code{thread-sleep!} accepts a seconds real number value in addition to a time object. @item When an uncaught exception (i.e. an error) is signalled in a thread other than the primordial thread and warnings are enabled (see: @code{enable-warnings}, then a warning message is written to the port that is the value of @code{(current-error-port)}. @item Blocking I/O will block all threads, except for some socket operations (see the section about the @code{tcp} unit). An exception is the read-eval-print loop on UNIX platforms: waiting for input will not block other threads, provided the current input port reads input from a console. @item It is generally not a good idea for one thread to call a continuation created by another thread, if @code{dynamic-wind} is involved. @item When more than one thread compete for the current time-slice, the thread that was waiting first will become the next runnable thread. @item The dynamic environment of a thread consists of the following state:@itemize @item The current input-, output- and error-port @item The current exception handler @item The values of all current parameters (created by @code{make-parameter}) @item Any pending @code{dynamic-wind} thunks. @end itemize @end itemize The following procedures are provided, in addition to the procedures defined in SRFI-18: @node Unit srfi-18 - thread-signal!, Unit srfi-18 - thread-quantum, , Unit srfi-18 @section thread-signal! @verbatim [procedure] (thread-signal! THREAD X) @end verbatim This will cause @code{THREAD} to signal the condition @code{X} once it is scheduled for execution. After signalling the condition, the thread continues with its normal execution. @node Unit srfi-18 - thread-quantum, Unit srfi-18 - thread-quantum-set!, Unit srfi-18 - thread-signal!, Unit srfi-18 @section thread-quantum @verbatim [procedure] (thread-quantum THREAD) @end verbatim Returns the quantum of @code{THREAD}, which is an exact integer specifying the approximate time-slice of the thread in milliseconds. @node Unit srfi-18 - thread-quantum-set!, Unit srfi-18 - thread-suspend!, Unit srfi-18 - thread-quantum, Unit srfi-18 @section thread-quantum-set! @verbatim [procedure] (thread-quantum-set! THREAD QUANTUM) @end verbatim Sets the quantum of @code{THREAD} to @code{QUANTUM}. @node Unit srfi-18 - thread-suspend!, Unit srfi-18 - thread-resume!, Unit srfi-18 - thread-quantum-set!, Unit srfi-18 @section thread-suspend! @verbatim [procedure] (thread-suspend! THREAD) @end verbatim Suspends the execution of @code{THREAD} until resumed. @node Unit srfi-18 - thread-resume!, Unit srfi-18 - time->milliseconds, Unit srfi-18 - thread-suspend!, Unit srfi-18 @section thread-resume! @verbatim [procedure] (thread-resume! THREAD) @end verbatim Readies the suspended thread @code{THREAD}. @node Unit srfi-18 - time->milliseconds, , Unit srfi-18 - thread-resume!, Unit srfi-18 @section time->milliseconds @verbatim [procedure] (time->milliseconds TIME) @end verbatim Converts a time object (as created via @code{current-time}) into an exact integer representing the number of milliseconds since process startup. Previous: @ref{Unit regex, Unit regex} Next: @ref{Unit posix, Unit posix} @node Unit posix, Unit utils, Unit srfi-18, Top @chapter Unit posix @menu * Unit posix - Directories:: * Unit posix - Pipes:: * Unit posix - Fifos:: * Unit posix - File descriptors and low-level I/O:: * Unit posix - Retrieving file attributes:: * Unit posix - Changing file attributes:: * Unit posix - Processes:: * Unit posix - Hard and symbolic links:: * Unit posix - Permissions:: * Unit posix - Record locking:: * Unit posix - Signal handling:: * Unit posix - Environment access:: * Unit posix - Memory mapped I/O:: * Unit posix - Date and time routines:: * Unit posix - Raw exit:: * Unit posix - ERRNO values:: * Unit posix - Finding files:: * Unit posix - Getting the hostname and system information:: * Unit posix - Setting the file buffering mode:: * Unit posix - Terminal ports:: * Unit posix - How Scheme procedures relate to UNIX C functions:: * Unit posix - Windows specific notes:: @end menu This unit provides services as used on many UNIX-like systems. Note that the following definitions are not all available on non-UNIX systems like Windows. See below for Windows specific notes. This unit uses the @code{regex}, @code{scheduler}, @code{extras} and @code{utils} units. All errors related to failing file-operations will signal a condition of kind @code{(exn i/o file)}. @node Unit posix - Directories, Unit posix - Pipes, , Unit posix @section Directories @menu * Unit posix - Directories - change-directory:: * Unit posix - Directories - current-directory:: * Unit posix - Directories - create-directory:: * Unit posix - Directories - delete-directory:: * Unit posix - Directories - directory:: * Unit posix - Directories - directory?:: * Unit posix - Directories - glob:: * Unit posix - Directories - set-root-directory!:: @end menu @node Unit posix - Directories - change-directory, Unit posix - Directories - current-directory, , Unit posix - Directories @subsection change-directory @verbatim [procedure] (change-directory NAME) @end verbatim Changes the current working directory to @code{NAME}. @node Unit posix - Directories - current-directory, Unit posix - Directories - create-directory, Unit posix - Directories - change-directory, Unit posix - Directories @subsection current-directory @verbatim [procedure] (current-directory [DIR]) @end verbatim Returns the name of the current working directory. If the optional argument @code{DIR} is given, then @code{(current-directory DIR)} is equivalent to @code{(change-directory DIR)}. @node Unit posix - Directories - create-directory, Unit posix - Directories - delete-directory, Unit posix - Directories - current-directory, Unit posix - Directories @subsection create-directory @verbatim [procedure] (create-directory NAME) @end verbatim Creates a directory with the pathname @code{NAME}. @node Unit posix - Directories - delete-directory, Unit posix - Directories - directory, Unit posix - Directories - create-directory, Unit posix - Directories @subsection delete-directory @verbatim [procedure] (delete-directory NAME) @end verbatim Deletes the directory with the pathname @code{NAME}. The directory has to be empty. @node Unit posix - Directories - directory, Unit posix - Directories - directory?, Unit posix - Directories - delete-directory, Unit posix - Directories @subsection directory @verbatim [procedure] (directory [PATHNAME [SHOW-DOTFILES?]]) @end verbatim Returns a list with all files that are contained in the directory with the name @code{PATHNAME} (which defaults to the value of @code{(current-directory)}). Files beginning with @code{.} are included only if @code{SHOW-DOTFILES?} is given and not @code{#f}. @node Unit posix - Directories - directory?, Unit posix - Directories - glob, Unit posix - Directories - directory, Unit posix - Directories @subsection directory? @verbatim [procedure] (directory? NAME) @end verbatim Returns @code{#t} if there exists a file with the name @code{NAME} and if that file is a directory, or @code{#f} otherwise. @node Unit posix - Directories - glob, Unit posix - Directories - set-root-directory!, Unit posix - Directories - directory?, Unit posix - Directories @subsection glob @verbatim [procedure] (glob PATTERN1 ...) @end verbatim Returns a list of the pathnames of all existing files matching @code{PATTERN1 ...}, which should be strings containing the usual file-patterns (with @code{*} matching zero or more characters and @code{?} matching zero or one character). @node Unit posix - Directories - set-root-directory!, , Unit posix - Directories - glob, Unit posix - Directories @subsection set-root-directory! @verbatim [procedure] (set-root-directory! STRING) @end verbatim Sets the root directory for the current process to the path given in @code{STRING} (using the @code{chroot} function). If the current process has no root permissions, the operation will fail. @node Unit posix - Pipes, Unit posix - Fifos, Unit posix - Directories, Unit posix @section Pipes @menu * Unit posix - Pipes - call-with-input-pipe:: * Unit posix - Pipes - call-with-output-pipe:: * Unit posix - Pipes - close-input-pipe:: * Unit posix - Pipes - close-output-pipe:: * Unit posix - Pipes - create-pipe:: * Unit posix - Pipes - open-input-pipe:: * Unit posix - Pipes - open-output-pipe:: * Unit posix - Pipes - pipe/buf:: * Unit posix - Pipes - with-input-from-pipe:: * Unit posix - Pipes - with-output-to-pipe:: @end menu @node Unit posix - Pipes - call-with-input-pipe, Unit posix - Pipes - call-with-output-pipe, , Unit posix - Pipes @subsection call-with-input-pipe @node Unit posix - Pipes - call-with-output-pipe, Unit posix - Pipes - close-input-pipe, Unit posix - Pipes - call-with-input-pipe, Unit posix - Pipes @subsection call-with-output-pipe @verbatim [procedure] (call-with-input-pipe CMDLINE PROC [MODE]) [procedure] (call-with-output-pipe CMDLINE PROC [MODE]) @end verbatim Call @code{PROC} with a single argument: a input- or output port for a pipe connected to the subprocess named in @code{CMDLINE}. If @code{PROC} returns normally, the pipe is closed and any result values are returned. @node Unit posix - Pipes - close-input-pipe, Unit posix - Pipes - close-output-pipe, Unit posix - Pipes - call-with-output-pipe, Unit posix - Pipes @subsection close-input-pipe @node Unit posix - Pipes - close-output-pipe, Unit posix - Pipes - create-pipe, Unit posix - Pipes - close-input-pipe, Unit posix - Pipes @subsection close-output-pipe @verbatim [procedure] (close-input-pipe PORT) [procedure] (close-output-pipe PORT) @end verbatim Closes the pipe given in @code{PORT} and waits until the connected subprocess finishes. The exit-status code of the invoked process is returned. @node Unit posix - Pipes - create-pipe, Unit posix - Pipes - open-input-pipe, Unit posix - Pipes - close-output-pipe, Unit posix - Pipes @subsection create-pipe @verbatim [procedure] (create-pipe) @end verbatim The fundamental pipe-creation operator. Calls the C function @code{pipe()} and returns 2 values: the file-descriptors of the input- and output-ends of the pipe. @node Unit posix - Pipes - open-input-pipe, Unit posix - Pipes - open-output-pipe, Unit posix - Pipes - create-pipe, Unit posix - Pipes @subsection open-input-pipe @verbatim [procedure] (open-input-pipe CMDLINE [MODE]) @end verbatim Spawns a subprocess with the command-line string @code{CMDLINE} and returns a port, from which the output of the process can be read. If @code{MODE} is specified, it should be the keyword @code{#:text} (the default) or @code{#:binary}. @node Unit posix - Pipes - open-output-pipe, Unit posix - Pipes - pipe/buf, Unit posix - Pipes - open-input-pipe, Unit posix - Pipes @subsection open-output-pipe @verbatim [procedure] (open-output-pipe CMDLINE [MODE]) @end verbatim Spawns a subprocess with the command-line string @code{CMDLINE} and returns a port. Anything written to that port is treated as the input for the process. If @code{MODE} is specified, it should be the keyword @code{#:text} (the default) or @code{#:binary}. @node Unit posix - Pipes - pipe/buf, Unit posix - Pipes - with-input-from-pipe, Unit posix - Pipes - open-output-pipe, Unit posix - Pipes @subsection pipe/buf This variable contains the maximal number of bytes that can be written atomically into a pipe or FIFO. @node Unit posix - Pipes - with-input-from-pipe, Unit posix - Pipes - with-output-to-pipe, Unit posix - Pipes - pipe/buf, Unit posix - Pipes @subsection with-input-from-pipe @node Unit posix - Pipes - with-output-to-pipe, , Unit posix - Pipes - with-input-from-pipe, Unit posix - Pipes @subsection with-output-to-pipe @verbatim [procedure] (with-input-from-pipe CMDLINE THUNK [MODE]) [procedure] (with-output-to-pipe CMDLINE THUNK [MODE]) @end verbatim Temporarily set the value of @code{current-input-port/current-output-port} to a port for a pipe connected to the subprocess named in @code{CMDLINE} and call the procedure @code{THUNK} with no arguments. After @code{THUNK} returns normally the pipe is closed and the standard input-/output port is restored to its previous value and any result values are returned. (with-output-to-pipe @verbatim "gs -dNOPAUSE -sDEVICE=jpeg -dBATCH -sOutputFile=signballs.jpg -g600x600 -q -" (lambda () (print #< /C/neg/d/mul/R/rlineto/E/exp/H@{@{cvx def@}repeat@}def/T/dup/g/gt/r/roll/J/ifelse 8 H/A/copy(z&v4QX&93r9AxYQOZomQalxS2w!!O&vMYa43d6r93rMYvx2dca!D&cjSnjSnjjS3o!v&6A X&55SAxM1CD7AjYxTTd62rmxCnTdSST0g&12wECST!&!J0g&D1!&xM0!J0g!l&544dC2Ac96ra!m&3A F&&vGoGSnCT0g&wDmlvGoS8wpn6wpS2wTCpS1Sd7ov7Uk7o4Qkdw!&Mvlx1S7oZES3w!J!J!Q&7185d Z&lx1CS9d9nE4!k&X&MY7!&1!J!x&jdnjdS3odS!N&mmx1C2wEc!G&150Nx4!n&2o!j&43r!U&0777d ]&2AY2A776ddT4oS3oSnMVC00VV0RRR45E42063rNz&v7UX&UOzF!F!J![&44ETCnVn!a&1CDN!Y&0M V1c&j2AYdjmMdjjd!o&1r!M)@{( )T 0 4 3 r put T(/)g@{T(9)g@{cvn@}@{cvi@}J@}@{($)g[]J@}J cvx@}forall/moveto/p/floor/w/div/S/add 29 H[@{[@{]setgray fill@}for Y@}for showpage EOF ) ) ) @end verbatim @node Unit posix - Fifos, Unit posix - File descriptors and low-level I/O, Unit posix - Pipes, Unit posix @section Fifos @menu * Unit posix - Fifos - create-fifo:: * Unit posix - Fifos - fifo?:: @end menu @node Unit posix - Fifos - create-fifo, Unit posix - Fifos - fifo?, , Unit posix - Fifos @subsection create-fifo @verbatim [procedure] (create-fifo FILENAME [MODE]) @end verbatim Creates a FIFO with the name @code{FILENAME} and the permission bits @code{MODE}, which defaults to @verbatim [procedure] (+ perm/irwxu perm/irwxg perm/irwxo) @end verbatim @node Unit posix - Fifos - fifo?, , Unit posix - Fifos - create-fifo, Unit posix - Fifos @subsection fifo? @verbatim [procedure] (fifo? FILENAME) @end verbatim Returns @code{#t} if the file with the name @code{FILENAME} names a FIFO. @node Unit posix - File descriptors and low-level I/O, Unit posix - Retrieving file attributes, Unit posix - Fifos, Unit posix @section File descriptors and low-level I/O @menu * Unit posix - File descriptors and low-level I/O - duplicate-fileno:: * Unit posix - File descriptors and low-level I/O - file-close:: * Unit posix - File descriptors and low-level I/O - file-open:: * Unit posix - File descriptors and low-level I/O - file-mkstemp:: * Unit posix - File descriptors and low-level I/O - file-read:: * Unit posix - File descriptors and low-level I/O - file-select:: * Unit posix - File descriptors and low-level I/O - file-write:: * Unit posix - File descriptors and low-level I/O - file-control:: * Unit posix - File descriptors and low-level I/O - fcntl/dupfd:: * Unit posix - File descriptors and low-level I/O - fcntl/getfd:: * Unit posix - File descriptors and low-level I/O - fcntl/setfd:: * Unit posix - File descriptors and low-level I/O - fcntl/getfl:: * Unit posix - File descriptors and low-level I/O - fcntl/setfl:: * Unit posix - File descriptors and low-level I/O - fileno/stdin:: * Unit posix - File descriptors and low-level I/O - fileno/stdout:: * Unit posix - File descriptors and low-level I/O - fileno/stderr:: * Unit posix - File descriptors and low-level I/O - open/rdonly:: * Unit posix - File descriptors and low-level I/O - open/wronly:: * Unit posix - File descriptors and low-level I/O - open/rdwr:: * Unit posix - File descriptors and low-level I/O - open/read:: * Unit posix - File descriptors and low-level I/O - open/write:: * Unit posix - File descriptors and low-level I/O - open/creat:: * Unit posix - File descriptors and low-level I/O - open/append:: * Unit posix - File descriptors and low-level I/O - open/excl:: * Unit posix - File descriptors and low-level I/O - open/noctty:: * Unit posix - File descriptors and low-level I/O - open/nonblock:: * Unit posix - File descriptors and low-level I/O - open/trunc:: * Unit posix - File descriptors and low-level I/O - open/sync:: * Unit posix - File descriptors and low-level I/O - open/fsync:: * Unit posix - File descriptors and low-level I/O - open/binary:: * Unit posix - File descriptors and low-level I/O - open/text:: * Unit posix - File descriptors and low-level I/O - open-input-file*:: * Unit posix - File descriptors and low-level I/O - open-output-file*:: * Unit posix - File descriptors and low-level I/O - port->fileno:: @end menu @node Unit posix - File descriptors and low-level I/O - duplicate-fileno, Unit posix - File descriptors and low-level I/O - file-close, , Unit posix - File descriptors and low-level I/O @subsection duplicate-fileno @verbatim [procedure] (duplicate-fileno OLD [NEW]) @end verbatim If @code{NEW} is given, then the file-descriptor @code{NEW} is opened to access the file with the file-descriptor @code{OLD}. Otherwise a fresh file-descriptor accessing the same file as @code{OLD} is returned. @node Unit posix - File descriptors and low-level I/O - file-close, Unit posix - File descriptors and low-level I/O - file-open, Unit posix - File descriptors and low-level I/O - duplicate-fileno, Unit posix - File descriptors and low-level I/O @subsection file-close @verbatim [procedure] (file-close FILENO) @end verbatim Closes the input/output file with the file-descriptor @code{FILENO}. @node Unit posix - File descriptors and low-level I/O - file-open, Unit posix - File descriptors and low-level I/O - file-mkstemp, Unit posix - File descriptors and low-level I/O - file-close, Unit posix - File descriptors and low-level I/O @subsection file-open @verbatim [procedure] (file-open FILENAME FLAGS [MODE]) @end verbatim Opens the file specified with the string @code{FILENAME} and open-flags @code{FLAGS} using the C function @code{open()}. On success a file-descriptor for the opened file is returned. @code{FLAGS} should be a bitmask containing one or more of the @code{open/...} values @b{or}ed together using @code{bitwise-ior} (or simply added together). The optional @code{MODE} should be a bitmask composed of one or more permission values like @code{perm/irusr} and is only relevant when a new file is created. The default mode is @code{perm/irwxu | perm/irgrp | perm/iroth}. @node Unit posix - File descriptors and low-level I/O - file-mkstemp, Unit posix - File descriptors and low-level I/O - file-read, Unit posix - File descriptors and low-level I/O - file-open, Unit posix - File descriptors and low-level I/O @subsection file-mkstemp @verbatim [procedure] (file-mkstemp TEMPLATE-FILENAME) @end verbatim Create a file based on the given @code{TEMPLATE-FILENAME}, in which the six last characters must be @emph{XXXXXX}. These will be replaced with a string that makes the filename unique. The file descriptor of the created file and the generated filename is returned. See the @code{mkstemp(3)} manual page for details on how this function works. The template string given is not modified. Example usage: @verbatim (let-values (((fd temp-path) (file-mkstemp "/tmp/mytemporary.XXXXXX"))) (let ((temp-port (open-output-file* fd))) (format temp-port "This file is ~A.~%" temp-path) (close-output-port temp-port))) @end verbatim @node Unit posix - File descriptors and low-level I/O - file-read, Unit posix - File descriptors and low-level I/O - file-select, Unit posix - File descriptors and low-level I/O - file-mkstemp, Unit posix - File descriptors and low-level I/O @subsection file-read @verbatim [procedure] (file-read FILENO SIZE [BUFFER]) @end verbatim Reads @code{SIZE} bytes from the file with the file-descriptor @code{FILENO}. If a string or bytevector is passed in the optional argument @code{BUFFER}, then this string will be destructively modified to contain the read data. This procedure returns a list with two values: the buffer containing the data and the number of bytes read. @node Unit posix - File descriptors and low-level I/O - file-select, Unit posix - File descriptors and low-level I/O - file-write, Unit posix - File descriptors and low-level I/O - file-read, Unit posix - File descriptors and low-level I/O @subsection file-select @verbatim [procedure] (file-select READFDLIST WRITEFDLIST [TIMEOUT]) @end verbatim Waits until any of the file-descriptors given in the lists @code{READFDLIST} and @code{WRITEFDLIST} is ready for input or output, respectively. If the optional argument @code{TIMEOUT} is given and not false, then it should specify the number of seconds after which the wait is to be aborted (the value may be a floating point number). This procedure returns two values: the lists of file-descriptors ready for input and output, respectively. @code{READFDLIST} and @b{WRITEFDLIST} may also by file-descriptors instead of lists. In this case the returned values are booleans indicating whether input/output is ready by @code{#t} or @code{#f} otherwise. You can also pass @code{#f} as @code{READFDLIST} or @code{WRITEFDLIST} argument, which is equivalent to @code{()}. @node Unit posix - File descriptors and low-level I/O - file-write, Unit posix - File descriptors and low-level I/O - file-control, Unit posix - File descriptors and low-level I/O - file-select, Unit posix - File descriptors and low-level I/O @subsection file-write @verbatim [procedure] (file-write FILENO BUFFER [SIZE]) @end verbatim Writes the contents of the string or bytevector @code{BUFFER} into the file with the file-descriptor @code{FILENO}. If the optional argument @code{SIZE} is given, then only the specified number of bytes are written. @node Unit posix - File descriptors and low-level I/O - file-control, Unit posix - File descriptors and low-level I/O - fcntl/dupfd, Unit posix - File descriptors and low-level I/O - file-write, Unit posix - File descriptors and low-level I/O @subsection file-control @verbatim [procedure] (file-control FILENO COMMAND [ARGUMENT]) @end verbatim Performs the fcntl operation @code{COMMAND} with the given @code{FILENO} and optional @code{ARGUMENT}. The return value is meaningful depending on the @code{COMMAND}. @node Unit posix - File descriptors and low-level I/O - fcntl/dupfd, Unit posix - File descriptors and low-level I/O - fcntl/getfd, Unit posix - File descriptors and low-level I/O - file-control, Unit posix - File descriptors and low-level I/O @subsection fcntl/dupfd @node Unit posix - File descriptors and low-level I/O - fcntl/getfd, Unit posix - File descriptors and low-level I/O - fcntl/setfd, Unit posix - File descriptors and low-level I/O - fcntl/dupfd, Unit posix - File descriptors and low-level I/O @subsection fcntl/getfd @node Unit posix - File descriptors and low-level I/O - fcntl/setfd, Unit posix - File descriptors and low-level I/O - fcntl/getfl, Unit posix - File descriptors and low-level I/O - fcntl/getfd, Unit posix - File descriptors and low-level I/O @subsection fcntl/setfd @node Unit posix - File descriptors and low-level I/O - fcntl/getfl, Unit posix - File descriptors and low-level I/O - fcntl/setfl, Unit posix - File descriptors and low-level I/O - fcntl/setfd, Unit posix - File descriptors and low-level I/O @subsection fcntl/getfl @node Unit posix - File descriptors and low-level I/O - fcntl/setfl, Unit posix - File descriptors and low-level I/O - fileno/stdin, Unit posix - File descriptors and low-level I/O - fcntl/getfl, Unit posix - File descriptors and low-level I/O @subsection fcntl/setfl These variables contain commands for @code{file-control}. @node Unit posix - File descriptors and low-level I/O - fileno/stdin, Unit posix - File descriptors and low-level I/O - fileno/stdout, Unit posix - File descriptors and low-level I/O - fcntl/setfl, Unit posix - File descriptors and low-level I/O @subsection fileno/stdin @node Unit posix - File descriptors and low-level I/O - fileno/stdout, Unit posix - File descriptors and low-level I/O - fileno/stderr, Unit posix - File descriptors and low-level I/O - fileno/stdin, Unit posix - File descriptors and low-level I/O @subsection fileno/stdout @node Unit posix - File descriptors and low-level I/O - fileno/stderr, Unit posix - File descriptors and low-level I/O - open/rdonly, Unit posix - File descriptors and low-level I/O - fileno/stdout, Unit posix - File descriptors and low-level I/O @subsection fileno/stderr These variables contain file-descriptors for the standard I/O files. @node Unit posix - File descriptors and low-level I/O - open/rdonly, Unit posix - File descriptors and low-level I/O - open/wronly, Unit posix - File descriptors and low-level I/O - fileno/stderr, Unit posix - File descriptors and low-level I/O @subsection open/rdonly @node Unit posix - File descriptors and low-level I/O - open/wronly, Unit posix - File descriptors and low-level I/O - open/rdwr, Unit posix - File descriptors and low-level I/O - open/rdonly, Unit posix - File descriptors and low-level I/O @subsection open/wronly @node Unit posix - File descriptors and low-level I/O - open/rdwr, Unit posix - File descriptors and low-level I/O - open/read, Unit posix - File descriptors and low-level I/O - open/wronly, Unit posix - File descriptors and low-level I/O @subsection open/rdwr @node Unit posix - File descriptors and low-level I/O - open/read, Unit posix - File descriptors and low-level I/O - open/write, Unit posix - File descriptors and low-level I/O - open/rdwr, Unit posix - File descriptors and low-level I/O @subsection open/read @node Unit posix - File descriptors and low-level I/O - open/write, Unit posix - File descriptors and low-level I/O - open/creat, Unit posix - File descriptors and low-level I/O - open/read, Unit posix - File descriptors and low-level I/O @subsection open/write @node Unit posix - File descriptors and low-level I/O - open/creat, Unit posix - File descriptors and low-level I/O - open/append, Unit posix - File descriptors and low-level I/O - open/write, Unit posix - File descriptors and low-level I/O @subsection open/creat @node Unit posix - File descriptors and low-level I/O - open/append, Unit posix - File descriptors and low-level I/O - open/excl, Unit posix - File descriptors and low-level I/O - open/creat, Unit posix - File descriptors and low-level I/O @subsection open/append @node Unit posix - File descriptors and low-level I/O - open/excl, Unit posix - File descriptors and low-level I/O - open/noctty, Unit posix - File descriptors and low-level I/O - open/append, Unit posix - File descriptors and low-level I/O @subsection open/excl @node Unit posix - File descriptors and low-level I/O - open/noctty, Unit posix - File descriptors and low-level I/O - open/nonblock, Unit posix - File descriptors and low-level I/O - open/excl, Unit posix - File descriptors and low-level I/O @subsection open/noctty @node Unit posix - File descriptors and low-level I/O - open/nonblock, Unit posix - File descriptors and low-level I/O - open/trunc, Unit posix - File descriptors and low-level I/O - open/noctty, Unit posix - File descriptors and low-level I/O @subsection open/nonblock @node Unit posix - File descriptors and low-level I/O - open/trunc, Unit posix - File descriptors and low-level I/O - open/sync, Unit posix - File descriptors and low-level I/O - open/nonblock, Unit posix - File descriptors and low-level I/O @subsection open/trunc @node Unit posix - File descriptors and low-level I/O - open/sync, Unit posix - File descriptors and low-level I/O - open/fsync, Unit posix - File descriptors and low-level I/O - open/trunc, Unit posix - File descriptors and low-level I/O @subsection open/sync @node Unit posix - File descriptors and low-level I/O - open/fsync, Unit posix - File descriptors and low-level I/O - open/binary, Unit posix - File descriptors and low-level I/O - open/sync, Unit posix - File descriptors and low-level I/O @subsection open/fsync @node Unit posix - File descriptors and low-level I/O - open/binary, Unit posix - File descriptors and low-level I/O - open/text, Unit posix - File descriptors and low-level I/O - open/fsync, Unit posix - File descriptors and low-level I/O @subsection open/binary @node Unit posix - File descriptors and low-level I/O - open/text, Unit posix - File descriptors and low-level I/O - open-input-file*, Unit posix - File descriptors and low-level I/O - open/binary, Unit posix - File descriptors and low-level I/O @subsection open/text Flags for use with @code{file-open}. @node Unit posix - File descriptors and low-level I/O - open-input-file*, Unit posix - File descriptors and low-level I/O - open-output-file*, Unit posix - File descriptors and low-level I/O - open/text, Unit posix - File descriptors and low-level I/O @subsection open-input-file* @node Unit posix - File descriptors and low-level I/O - open-output-file*, Unit posix - File descriptors and low-level I/O - port->fileno, Unit posix - File descriptors and low-level I/O - open-input-file*, Unit posix - File descriptors and low-level I/O @subsection open-output-file* @verbatim [procedure] (open-input-file* FILENO [OPENMODE]) [procedure] (open-output-file* FILENO [OPENMODE]) @end verbatim Opens file for the file-descriptor @code{FILENO} for input or output and returns a port. @code{FILENO} should be a positive exact integer. @code{OPENMODE} specifies an additional mode for opening the file (currently only the keyword @code{#:append} is supported, which opens an output-file for appending). @node Unit posix - File descriptors and low-level I/O - port->fileno, , Unit posix - File descriptors and low-level I/O - open-output-file*, Unit posix - File descriptors and low-level I/O @subsection port->fileno @verbatim [procedure] (port->fileno PORT) @end verbatim If @code{PORT} is a file- or tcp-port, then a file-descriptor is returned for this port. Otherwise an error is signaled. @node Unit posix - Retrieving file attributes, Unit posix - Changing file attributes, Unit posix - File descriptors and low-level I/O, Unit posix @section Retrieving file attributes @menu * Unit posix - Retrieving file attributes - file-access-time:: * Unit posix - Retrieving file attributes - file-change-time:: * Unit posix - Retrieving file attributes - file-modification-time:: * Unit posix - Retrieving file attributes - file-stat:: * Unit posix - Retrieving file attributes - file-position:: * Unit posix - Retrieving file attributes - file-size:: * Unit posix - Retrieving file attributes - regular-file?:: @end menu @node Unit posix - Retrieving file attributes - file-access-time, Unit posix - Retrieving file attributes - file-change-time, , Unit posix - Retrieving file attributes @subsection file-access-time @node Unit posix - Retrieving file attributes - file-change-time, Unit posix - Retrieving file attributes - file-modification-time, Unit posix - Retrieving file attributes - file-access-time, Unit posix - Retrieving file attributes @subsection file-change-time @node Unit posix - Retrieving file attributes - file-modification-time, Unit posix - Retrieving file attributes - file-stat, Unit posix - Retrieving file attributes - file-change-time, Unit posix - Retrieving file attributes @subsection file-modification-time @verbatim [procedure] (file-access-time FILE) [procedure] (file-change-time FILE) [procedure] (file-modification-time FILE) @end verbatim Returns time (in seconds) of the last access, modification or change of @code{FILE}. @code{FILE} may be a filename or a file-descriptor. If the file does not exist, an error is signaled. @node Unit posix - Retrieving file attributes - file-stat, Unit posix - Retrieving file attributes - file-position, Unit posix - Retrieving file attributes - file-modification-time, Unit posix - Retrieving file attributes @subsection file-stat @verbatim [procedure] (file-stat FILE [LINK]) @end verbatim Returns a 13-element vector with the following contents: inode-number, mode (as with @code{file-permissions}), number of hard links, uid of owner (as with @code{file-owner}), gid of owner, size (as with @code{file-size}) and access-, change- and modification-time (as with @code{file-access-time}, @code{file-change-time} and @code{file-modification-time}, device id, device type (for special file inode, blocksize and blocks allocated. On Windows systems the last 4 values are undefined. If the optional argument @code{LINK} is given and not @code{#f}, then the file-statistics vector will be resolved for symbolic links (otherwise symbolic links are not resolved). @node Unit posix - Retrieving file attributes - file-position, Unit posix - Retrieving file attributes - file-size, Unit posix - Retrieving file attributes - file-stat, Unit posix - Retrieving file attributes @subsection file-position @verbatim [procedure] (file-position FILE) @end verbatim Returns the current file position of @code{FILE}, which should be a port or a file-descriptor. @node Unit posix - Retrieving file attributes - file-size, Unit posix - Retrieving file attributes - regular-file?, Unit posix - Retrieving file attributes - file-position, Unit posix - Retrieving file attributes @subsection file-size @verbatim [procedure] (file-size FILENAME) @end verbatim Returns the size of the file designated by @code{FILE}. @code{FILE} may be a filename or a file-descriptor. If the file does not exist, an error is signaled. @node Unit posix - Retrieving file attributes - regular-file?, , Unit posix - Retrieving file attributes - file-size, Unit posix - Retrieving file attributes @subsection regular-file? @verbatim [procedure] (regular-file? FILENAME) @end verbatim Returns true, if @code{FILENAME} names a regular file (not a directory or symbolic link). @node Unit posix - Changing file attributes, Unit posix - Processes, Unit posix - Retrieving file attributes, Unit posix @section Changing file attributes @menu * Unit posix - Changing file attributes - file-truncate:: * Unit posix - Changing file attributes - set-file-position!:: @end menu @node Unit posix - Changing file attributes - file-truncate, Unit posix - Changing file attributes - set-file-position!, , Unit posix - Changing file attributes @subsection file-truncate @verbatim [procedure] (file-truncate FILE OFFSET) @end verbatim Truncates the file @code{FILE} to the length @code{OFFSET}, which should be an integer. If the file-size is smaller or equal to @code{OFFSET} then nothing is done. @code{FILE} should be a filename or a file-descriptor. @node Unit posix - Changing file attributes - set-file-position!, , Unit posix - Changing file attributes - file-truncate, Unit posix - Changing file attributes @subsection set-file-position! @verbatim [procedure] (set-file-position! FILE POSITION [WHENCE]) [procedure] (set! (file-position FILE) POSITION) @end verbatim Sets the current read/write position of @code{FILE} to @code{POSITION}, which should be an exact integer. @code{FILE} should be a port or a file-descriptor. @code{WHENCE} specifies how the position is to interpreted and should be one of the values @code{seek/set, seek/cur} and @code{seek/end}. It defaults to @code{seek/set}. Exceptions: @code{(exn bounds)}, @code{(exn i/o file)} @node Unit posix - Processes, Unit posix - Hard and symbolic links, Unit posix - Changing file attributes, Unit posix @section Processes @menu * Unit posix - Processes - current-process-id:: * Unit posix - Processes - parent-process-id:: * Unit posix - Processes - process-execute:: * Unit posix - Processes - process-fork:: * Unit posix - Processes - process-run:: * Unit posix - Processes - process-signal:: * Unit posix - Processes - process-wait:: * Unit posix - Processes - process:: * Unit posix - Processes - process*:: * Unit posix - Processes - sleep:: @end menu @node Unit posix - Processes - current-process-id, Unit posix - Processes - parent-process-id, , Unit posix - Processes @subsection current-process-id @verbatim [procedure] (current-process-id) @end verbatim Returns the process ID of the current process. @node Unit posix - Processes - parent-process-id, Unit posix - Processes - process-execute, Unit posix - Processes - current-process-id, Unit posix - Processes @subsection parent-process-id @verbatim [procedure] (parent-process-id) @end verbatim Returns the process ID of the parent of the current process. @node Unit posix - Processes - process-execute, Unit posix - Processes - process-fork, Unit posix - Processes - parent-process-id, Unit posix - Processes @subsection process-execute @verbatim [procedure] (process-execute PATHNAME [ARGUMENT-LIST [ENVIRONMENT-LIST]]) @end verbatim Creates a new child process and replaces the running process with it using the C library function @code{execvp(3)}. If the optional argument @code{ARGUMENT-LIST} is given, then it should contain a list of strings which are passed as arguments to the subprocess. If the optional argument @code{ENVIRONMENT-LIST} is supplied, then the library function @code{execve(2)} is used, and the environment passed in @code{ENVIRONMENT-LIST} (which should be of the form @code{("=" ...)} is given to the invoked process. Note that @code{execvp(3)} respects the current setting of the @code{PATH} environment variable while @code{execve(3)} does not. @node Unit posix - Processes - process-fork, Unit posix - Processes - process-run, Unit posix - Processes - process-execute, Unit posix - Processes @subsection process-fork @verbatim [procedure] (process-fork [THUNK]) @end verbatim Creates a new child process with the UNIX system call @code{fork()}. Returns either the PID of the child process or 0. If @code{THUNK} is given, then the child process calls it as a procedure with no arguments and terminates. @node Unit posix - Processes - process-run, Unit posix - Processes - process-signal, Unit posix - Processes - process-fork, Unit posix - Processes @subsection process-run @verbatim [procedure] (process-run COMMANDLINE]) [procedure] (process-run COMMAND ARGUMENT-LIST) @end verbatim Creates a new child process. The PID of the new process is returned. @itemize @item The single parameter version passes the @code{COMMANDLINE} to the system shell, so usual argument expansion can take place. @item The multiple parameter version directly invokes the @code{COMMAND} with the @code{ARGUMENT-LIST}. @end itemize @node Unit posix - Processes - process-signal, Unit posix - Processes - process-wait, Unit posix - Processes - process-run, Unit posix - Processes @subsection process-signal @verbatim [procedure] (process-signal PID [SIGNAL]) @end verbatim Sends @code{SIGNAL} to the process with the id @code{PID} using the UNIX system call @code{kill()}. @code{SIGNAL} defaults to the value of the variable @code{signal/term}. @node Unit posix - Processes - process-wait, Unit posix - Processes - process, Unit posix - Processes - process-signal, Unit posix - Processes @subsection process-wait @verbatim [procedure] (process-wait [PID [NOHANG]]) @end verbatim Suspends the current process until the child process with the id @code{PID} has terminated using the UNIX system call @code{waitpid()}. If @code{PID} is not given, then this procedure waits for any child process. If @code{NOHANG} is given and not @code{#f} then the current process is not suspended. This procedure returns three values: @itemize @item @code{PID} or 0, if @code{NOHANG} is true and the child process has not terminated yet. @item @code{#t} if the process exited normally or @code{#f} otherwise. @item either the exit status, if the process terminated normally or the signal number that terminated/stopped the process. @end itemize @node Unit posix - Processes - process, Unit posix - Processes - process*, Unit posix - Processes - process-wait, Unit posix - Processes @subsection process @verbatim [procedure] (process COMMANDLINE) [procedure] (process COMMAND ARGUMENT-LIST [ENVIRONMENT-LIST]) @end verbatim Creates a subprocess and returns three values: an input port from which data written by the sub-process can be read, an output port from which any data written to will be received as input in the sub-process and the process-id of the started sub-process. Blocking reads and writes to or from the ports returned by @code{process} only block the current thread, not other threads executing concurrently. @itemize @item The single parameter version passes the string @code{COMMANDLINE} to the host-system's shell that is invoked as a subprocess. @item The multiple parameter version directly invokes the @code{COMMAND} as a subprocess. The @code{ARGUMENT-LIST} is directly passed, as is @code{ENVIRONMENT-LIST}. @end itemize Not using the shell may be preferrable for security reasons. @node Unit posix - Processes - process*, Unit posix - Processes - sleep, Unit posix - Processes - process, Unit posix - Processes @subsection process* @verbatim [procedure] (process* COMMANDLINE) [procedure] (process* COMMAND ARGUMENT-LIST [ENVIRONMENT-LIST]) @end verbatim Like @code{process} but returns 4 values: an input port from which data written by the sub-process can be read, an output port from which any data written to will be received as input in the sub-process, the process-id of the started sub-process, and an input port from which data written by the sub-process to @code{stderr} can be read. @node Unit posix - Processes - sleep, , Unit posix - Processes - process*, Unit posix - Processes @subsection sleep @verbatim [procedure] (sleep SECONDS) @end verbatim Puts the process to sleep for @code{SECONDS}. Returns either 0 if the time has completely elapsed, or the number of remaining seconds, if a signal occurred. @node Unit posix - Hard and symbolic links, Unit posix - Permissions, Unit posix - Processes, Unit posix @section Hard and symbolic links @menu * Unit posix - Hard and symbolic links - symbolic-link?:: * Unit posix - Hard and symbolic links - create-symbolic-link:: * Unit posix - Hard and symbolic links - read-symbolic-link:: * Unit posix - Hard and symbolic links - file-link:: @end menu @node Unit posix - Hard and symbolic links - symbolic-link?, Unit posix - Hard and symbolic links - create-symbolic-link, , Unit posix - Hard and symbolic links @subsection symbolic-link? @verbatim [procedure] (symbolic-link? FILENAME) @end verbatim Returns true, if @code{FILENAME} names a symbolic link. @node Unit posix - Hard and symbolic links - create-symbolic-link, Unit posix - Hard and symbolic links - read-symbolic-link, Unit posix - Hard and symbolic links - symbolic-link?, Unit posix - Hard and symbolic links @subsection create-symbolic-link @verbatim [procedure] (create-symbolic-link OLDNAME NEWNAME) @end verbatim Creates a symbolic link with the filename @code{NEWNAME} that points to the file named @code{OLDNAME}. @node Unit posix - Hard and symbolic links - read-symbolic-link, Unit posix - Hard and symbolic links - file-link, Unit posix - Hard and symbolic links - create-symbolic-link, Unit posix - Hard and symbolic links @subsection read-symbolic-link @verbatim [procedure] (read-symbolic-link FILENAME) @end verbatim Returns the filename to which the symbolic link @code{FILENAME} points. @node Unit posix - Hard and symbolic links - file-link, , Unit posix - Hard and symbolic links - read-symbolic-link, Unit posix - Hard and symbolic links @subsection file-link @verbatim [procedure] (file-link OLDNAME NEWNAME) @end verbatim Creates a hard link from @code{OLDNAME} to @code{NEWNAME} (both strings). @node Unit posix - Permissions, Unit posix - Record locking, Unit posix - Hard and symbolic links, Unit posix @section Permissions @menu * Unit posix - Permissions - file-owner:: * Unit posix - Permissions - file-permissions:: * Unit posix - Permissions - file-read-access?:: * Unit posix - Permissions - file-write-access?:: * Unit posix - Permissions - file-execute-access?:: * Unit posix - Permissions - change-file-mode:: * Unit posix - Permissions - change-file-owner:: * Unit posix - Permissions - current-user-id:: * Unit posix - Permissions - current-group-id:: * Unit posix - Permissions - current-effective-user-id:: * Unit posix - Permissions - current-effective-group-id:: * Unit posix - Permissions - process-group-id:: * Unit posix - Permissions - group-information:: * Unit posix - Permissions - get-groups:: * Unit posix - Permissions - set-groups!:: * Unit posix - Permissions - initialize-groups:: * Unit posix - Permissions - perm/irusr:: * Unit posix - Permissions - perm/iwusr:: * Unit posix - Permissions - perm/ixusr:: * Unit posix - Permissions - perm/irgrp:: * Unit posix - Permissions - perm/iwgrp:: * Unit posix - Permissions - perm/ixgrp:: * Unit posix - Permissions - perm/iroth:: * Unit posix - Permissions - perm/iwoth:: * Unit posix - Permissions - perm/ixoth:: * Unit posix - Permissions - perm/irwxu:: * Unit posix - Permissions - perm/irwxg:: * Unit posix - Permissions - perm/irwxo:: * Unit posix - Permissions - perm/isvtx:: * Unit posix - Permissions - perm/isuid:: * Unit posix - Permissions - perm/isgid:: * Unit posix - Permissions - set-process-group-id!:: * Unit posix - Permissions - user-information:: * Unit posix - Permissions - create-session:: @end menu @node Unit posix - Permissions - file-owner, Unit posix - Permissions - file-permissions, , Unit posix - Permissions @subsection file-owner @verbatim [procedure] (file-owner FILE) @end verbatim Returns the user-id of @code{FILE}. @code{FILE} may be a filename or a file-descriptor. @node Unit posix - Permissions - file-permissions, Unit posix - Permissions - file-read-access?, Unit posix - Permissions - file-owner, Unit posix - Permissions @subsection file-permissions @verbatim [procedure] (file-permissions FILE) @end verbatim Returns the permission bits for @code{FILE}. You can test this value by performing bitwise operations on the result and the @code{perm/...} values. @code{FILE} may be a filename or a file-descriptor. @node Unit posix - Permissions - file-read-access?, Unit posix - Permissions - file-write-access?, Unit posix - Permissions - file-permissions, Unit posix - Permissions @subsection file-read-access? @node Unit posix - Permissions - file-write-access?, Unit posix - Permissions - file-execute-access?, Unit posix - Permissions - file-read-access?, Unit posix - Permissions @subsection file-write-access? @node Unit posix - Permissions - file-execute-access?, Unit posix - Permissions - change-file-mode, Unit posix - Permissions - file-write-access?, Unit posix - Permissions @subsection file-execute-access? @verbatim [procedure] (file-read-access? FILENAME) [procedure] (file-write-access? FILENAME) [procedure] (file-execute-access? FILENAME) @end verbatim These procedures return @code{#t} if the current user has read, write or execute permissions on the file named @code{FILENAME}. @node Unit posix - Permissions - change-file-mode, Unit posix - Permissions - change-file-owner, Unit posix - Permissions - file-execute-access?, Unit posix - Permissions @subsection change-file-mode @verbatim [procedure] (change-file-mode FILENAME MODE) @end verbatim Changes the current file mode of the file named @code{FILENAME} to @code{MODE} using the @code{chmod()} system call. The @code{perm/...} variables contain the various permission bits and can be combinded with the @code{bitwise-ior} procedure. @node Unit posix - Permissions - change-file-owner, Unit posix - Permissions - current-user-id, Unit posix - Permissions - change-file-mode, Unit posix - Permissions @subsection change-file-owner @verbatim [procedure] (change-file-owner FILENAME UID GID) @end verbatim Changes the owner information of the file named @code{FILENAME} to the user- and group-ids @code{UID} and @code{GID} (which should be exact integers) using the @code{chown()} system call. @node Unit posix - Permissions - current-user-id, Unit posix - Permissions - current-group-id, Unit posix - Permissions - change-file-owner, Unit posix - Permissions @subsection current-user-id @node Unit posix - Permissions - current-group-id, Unit posix - Permissions - current-effective-user-id, Unit posix - Permissions - current-user-id, Unit posix - Permissions @subsection current-group-id @node Unit posix - Permissions - current-effective-user-id, Unit posix - Permissions - current-effective-group-id, Unit posix - Permissions - current-group-id, Unit posix - Permissions @subsection current-effective-user-id @node Unit posix - Permissions - current-effective-group-id, Unit posix - Permissions - process-group-id, Unit posix - Permissions - current-effective-user-id, Unit posix - Permissions @subsection current-effective-group-id @verbatim [procedure] (current-user-id) [setter] (set! (current-user-id) UID) [procedure] (current-group-id) [setter] (set! (current-group-id) GID) [procedure] (current-effective-user-id) [setter] (set! (current-effective-user-id) UID) [procedure] (current-effective-group-id) [setter] (set! (current-effective-group-id) GID) @end verbatim Get or set the real/effective user- and group-ids of the current process. @node Unit posix - Permissions - process-group-id, Unit posix - Permissions - group-information, Unit posix - Permissions - current-effective-group-id, Unit posix - Permissions @subsection process-group-id @verbatim [procedure] (process-group-id PID) @end verbatim Returns the process group ID of the process specified by @code{PID}. @node Unit posix - Permissions - group-information, Unit posix - Permissions - get-groups, Unit posix - Permissions - process-group-id, Unit posix - Permissions @subsection group-information @verbatim [procedure] (group-information GROUP) @end verbatim If @code{GROUP} specifies a valid group-name or group-id, then this procedure returns a list of four values: the group-name, the encrypted group password, the group ID and a list of the names of all group members. If no group with the given name or ID exists, then @code{#f} is returned. @node Unit posix - Permissions - get-groups, Unit posix - Permissions - set-groups!, Unit posix - Permissions - group-information, Unit posix - Permissions @subsection get-groups @verbatim [procedure] (get-groups) @end verbatim Returns a list with the supplementary group IDs of the current user. @node Unit posix - Permissions - set-groups!, Unit posix - Permissions - initialize-groups, Unit posix - Permissions - get-groups, Unit posix - Permissions @subsection set-groups! @verbatim [procedure] (set-groups! GIDLIST) @end verbatim Sets the supplementrary group IDs of the current user to the IDs given in the list @code{GIDLIST}. Only the superuser may invoke this procedure. @node Unit posix - Permissions - initialize-groups, Unit posix - Permissions - perm/irusr, Unit posix - Permissions - set-groups!, Unit posix - Permissions @subsection initialize-groups @verbatim [procedure] (initialize-groups USERNAME BASEGID) @end verbatim Sets the supplementrary group IDs of the current user to the IDs from the user with name @code{USERNAME} (a string), including @code{BASEGID}. Only the superuser may invoke this procedure. @node Unit posix - Permissions - perm/irusr, Unit posix - Permissions - perm/iwusr, Unit posix - Permissions - initialize-groups, Unit posix - Permissions @subsection perm/irusr @node Unit posix - Permissions - perm/iwusr, Unit posix - Permissions - perm/ixusr, Unit posix - Permissions - perm/irusr, Unit posix - Permissions @subsection perm/iwusr @node Unit posix - Permissions - perm/ixusr, Unit posix - Permissions - perm/irgrp, Unit posix - Permissions - perm/iwusr, Unit posix - Permissions @subsection perm/ixusr @node Unit posix - Permissions - perm/irgrp, Unit posix - Permissions - perm/iwgrp, Unit posix - Permissions - perm/ixusr, Unit posix - Permissions @subsection perm/irgrp @node Unit posix - Permissions - perm/iwgrp, Unit posix - Permissions - perm/ixgrp, Unit posix - Permissions - perm/irgrp, Unit posix - Permissions @subsection perm/iwgrp @node Unit posix - Permissions - perm/ixgrp, Unit posix - Permissions - perm/iroth, Unit posix - Permissions - perm/iwgrp, Unit posix - Permissions @subsection perm/ixgrp @node Unit posix - Permissions - perm/iroth, Unit posix - Permissions - perm/iwoth, Unit posix - Permissions - perm/ixgrp, Unit posix - Permissions @subsection perm/iroth @node Unit posix - Permissions - perm/iwoth, Unit posix - Permissions - perm/ixoth, Unit posix - Permissions - perm/iroth, Unit posix - Permissions @subsection perm/iwoth @node Unit posix - Permissions - perm/ixoth, Unit posix - Permissions - perm/irwxu, Unit posix - Permissions - perm/iwoth, Unit posix - Permissions @subsection perm/ixoth @node Unit posix - Permissions - perm/irwxu, Unit posix - Permissions - perm/irwxg, Unit posix - Permissions - perm/ixoth, Unit posix - Permissions @subsection perm/irwxu @node Unit posix - Permissions - perm/irwxg, Unit posix - Permissions - perm/irwxo, Unit posix - Permissions - perm/irwxu, Unit posix - Permissions @subsection perm/irwxg @node Unit posix - Permissions - perm/irwxo, Unit posix - Permissions - perm/isvtx, Unit posix - Permissions - perm/irwxg, Unit posix - Permissions @subsection perm/irwxo @node Unit posix - Permissions - perm/isvtx, Unit posix - Permissions - perm/isuid, Unit posix - Permissions - perm/irwxo, Unit posix - Permissions @subsection perm/isvtx @node Unit posix - Permissions - perm/isuid, Unit posix - Permissions - perm/isgid, Unit posix - Permissions - perm/isvtx, Unit posix - Permissions @subsection perm/isuid @node Unit posix - Permissions - perm/isgid, Unit posix - Permissions - set-process-group-id!, Unit posix - Permissions - perm/isuid, Unit posix - Permissions @subsection perm/isgid These variables contain permission bits as used in @code{change-file-mode}. @node Unit posix - Permissions - set-process-group-id!, Unit posix - Permissions - user-information, Unit posix - Permissions - perm/isgid, Unit posix - Permissions @subsection set-process-group-id! @verbatim [procedure] (set-process-group-id! PID PGID) [setter] (set! (process-group-id PID) PGID) @end verbatim Sets the process group ID of the process specifed by @code{PID} to @code{PGID}. @node Unit posix - Permissions - user-information, Unit posix - Permissions - create-session, Unit posix - Permissions - set-process-group-id!, Unit posix - Permissions @subsection user-information @verbatim [procedure] (user-information USER) @end verbatim If @code{USER} specifes a valid username (as a string) or user ID, then the user database is consulted and a list of 7 values are returned: the user-name, the encrypted password, the user ID, the group ID, a user-specific string, the home directory and the default shell. If no user with this name or ID can be found, then @code{#f} is returned. @node Unit posix - Permissions - create-session, , Unit posix - Permissions - user-information, Unit posix - Permissions @subsection create-session @verbatim [procedure] (create-session) @end verbatim Creates a new session if the calling process is not a process group leader and returns the session ID. @node Unit posix - Record locking, Unit posix - Signal handling, Unit posix - Permissions, Unit posix @section Record locking @menu * Unit posix - Record locking - file-lock:: * Unit posix - Record locking - file-lock/blocking:: * Unit posix - Record locking - file-test-lock:: * Unit posix - Record locking - file-unlock:: @end menu @node Unit posix - Record locking - file-lock, Unit posix - Record locking - file-lock/blocking, , Unit posix - Record locking @subsection file-lock @verbatim [procedure] (file-lock PORT [START [LEN]]) @end verbatim Locks the file associated with @code{PORT} for reading or writing (according to whether @code{PORT} is an input- or output-port). @code{START} specifies the starting position in the file to be locked and defaults to 0. @code{LEN} specifies the length of the portion to be locked and defaults to @code{#t}, which means the complete file. @code{file-lock} returns a @emph{lock}-object. @node Unit posix - Record locking - file-lock/blocking, Unit posix - Record locking - file-test-lock, Unit posix - Record locking - file-lock, Unit posix - Record locking @subsection file-lock/blocking @verbatim [procedure] (file-lock/blocking PORT [START [LEN]]) @end verbatim Similar to @code{file-lock}, but if a lock is held on the file, the current process blocks (including all threads) until the lock is released. @node Unit posix - Record locking - file-test-lock, Unit posix - Record locking - file-unlock, Unit posix - Record locking - file-lock/blocking, Unit posix - Record locking @subsection file-test-lock @verbatim [procedure] (file-test-lock PORT [START [LEN]]) @end verbatim Tests whether the file associated with @code{PORT} is locked for reading or writing (according to whether @code{PORT} is an input- or output-port) and returns either @code{#f} or the process-id of the locking process. @node Unit posix - Record locking - file-unlock, , Unit posix - Record locking - file-test-lock, Unit posix - Record locking @subsection file-unlock @verbatim [procedure] (file-unlock LOCK) @end verbatim Unlocks the previously locked portion of a file given in @code{LOCK}. @node Unit posix - Signal handling, Unit posix - Environment access, Unit posix - Record locking, Unit posix @section Signal handling @menu * Unit posix - Signal handling - set-alarm!:: * Unit posix - Signal handling - set-signal-handler!:: * Unit posix - Signal handling - signal-handler:: * Unit posix - Signal handling - set-signal-mask!:: * Unit posix - Signal handling - signal-mask:: * Unit posix - Signal handling - signal-masked?:: * Unit posix - Signal handling - signal-mask!:: * Unit posix - Signal handling - signal-unmask!:: * Unit posix - Signal handling - signal/term:: * Unit posix - Signal handling - signal/kill:: * Unit posix - Signal handling - signal/int:: * Unit posix - Signal handling - signal/hup:: * Unit posix - Signal handling - signal/fpe:: * Unit posix - Signal handling - signal/ill:: * Unit posix - Signal handling - signal/segv:: * Unit posix - Signal handling - signal/abrt:: * Unit posix - Signal handling - signal/trap:: * Unit posix - Signal handling - signal/quit:: * Unit posix - Signal handling - signal/alrm:: * Unit posix - Signal handling - signal/vtalrm:: * Unit posix - Signal handling - signal/prof:: * Unit posix - Signal handling - signal/io:: * Unit posix - Signal handling - signal/urg:: * Unit posix - Signal handling - signal/chld:: * Unit posix - Signal handling - signal/cont:: * Unit posix - Signal handling - signal/stop:: * Unit posix - Signal handling - signal/tstp:: * Unit posix - Signal handling - signal/pipe:: * Unit posix - Signal handling - signal/xcpu:: * Unit posix - Signal handling - signal/xfsz:: * Unit posix - Signal handling - signal/usr1:: * Unit posix - Signal handling - signal/usr2:: * Unit posix - Signal handling - signal/winch:: @end menu @node Unit posix - Signal handling - set-alarm!, Unit posix - Signal handling - set-signal-handler!, , Unit posix - Signal handling @subsection set-alarm! @verbatim [procedure] (set-alarm! SECONDS) @end verbatim Sets an internal timer to raise the @code{signal/alrm} after @code{SECONDS} are elapsed. You can use the @code{set-signal-handler!} procedure to write a handler for this signal. @node Unit posix - Signal handling - set-signal-handler!, Unit posix - Signal handling - signal-handler, Unit posix - Signal handling - set-alarm!, Unit posix - Signal handling @subsection set-signal-handler! @verbatim [procedure] (set-signal-handler! SIGNUM PROC) @end verbatim Establishes the procedure of one argument @code{PROC} as the handler for the signal with the code @code{SIGNUM}. @code{PROC} is called with the signal number as its sole argument. If the argument @code{PROC} is @code{#f} then any signal handler will be removed. Note that is is unspecified in which thread of execution the signal handler will be invoked. @node Unit posix - Signal handling - signal-handler, Unit posix - Signal handling - set-signal-mask!, Unit posix - Signal handling - set-signal-handler!, Unit posix - Signal handling @subsection signal-handler @verbatim [procedure] (signal-handler SIGNUM) @end verbatim Returns the signal handler for the code @code{SIGNUM} or @code{#f}. @node Unit posix - Signal handling - set-signal-mask!, Unit posix - Signal handling - signal-mask, Unit posix - Signal handling - signal-handler, Unit posix - Signal handling @subsection set-signal-mask! @verbatim [procedure] (set-signal-mask! SIGLIST) @end verbatim Sets the signal mask of the current process to block all signals given in the list @code{SIGLIST}. Signals masked in that way will not be delivered to the current process. @node Unit posix - Signal handling - signal-mask, Unit posix - Signal handling - signal-masked?, Unit posix - Signal handling - set-signal-mask!, Unit posix - Signal handling @subsection signal-mask @verbatim [procedure] (signal-mask) @end verbatim Returns the signal mask of the current process. @node Unit posix - Signal handling - signal-masked?, Unit posix - Signal handling - signal-mask!, Unit posix - Signal handling - signal-mask, Unit posix - Signal handling @subsection signal-masked? @verbatim [procedure] (signal-masked? SIGNUM) @end verbatim Returns whether the signal for the code @code{SIGNUM} is currently masked. @node Unit posix - Signal handling - signal-mask!, Unit posix - Signal handling - signal-unmask!, Unit posix - Signal handling - signal-masked?, Unit posix - Signal handling @subsection signal-mask! @verbatim [procedure] (signal-mask! SIGNUM) @end verbatim Masks (blocks) the signal for the code @code{SIGNUM}. @node Unit posix - Signal handling - signal-unmask!, Unit posix - Signal handling - signal/term, Unit posix - Signal handling - signal-mask!, Unit posix - Signal handling @subsection signal-unmask! @verbatim [procedure] (signal-unmask! SIGNUM) @end verbatim Unmasks (unblocks) the signal for the code @code{SIGNUM}. @node Unit posix - Signal handling - signal/term, Unit posix - Signal handling - signal/kill, Unit posix - Signal handling - signal-unmask!, Unit posix - Signal handling @subsection signal/term @node Unit posix - Signal handling - signal/kill, Unit posix - Signal handling - signal/int, Unit posix - Signal handling - signal/term, Unit posix - Signal handling @subsection signal/kill @node Unit posix - Signal handling - signal/int, Unit posix - Signal handling - signal/hup, Unit posix - Signal handling - signal/kill, Unit posix - Signal handling @subsection signal/int @node Unit posix - Signal handling - signal/hup, Unit posix - Signal handling - signal/fpe, Unit posix - Signal handling - signal/int, Unit posix - Signal handling @subsection signal/hup @node Unit posix - Signal handling - signal/fpe, Unit posix - Signal handling - signal/ill, Unit posix - Signal handling - signal/hup, Unit posix - Signal handling @subsection signal/fpe @node Unit posix - Signal handling - signal/ill, Unit posix - Signal handling - signal/segv, Unit posix - Signal handling - signal/fpe, Unit posix - Signal handling @subsection signal/ill @node Unit posix - Signal handling - signal/segv, Unit posix - Signal handling - signal/abrt, Unit posix - Signal handling - signal/ill, Unit posix - Signal handling @subsection signal/segv @node Unit posix - Signal handling - signal/abrt, Unit posix - Signal handling - signal/trap, Unit posix - Signal handling - signal/segv, Unit posix - Signal handling @subsection signal/abrt @node Unit posix - Signal handling - signal/trap, Unit posix - Signal handling - signal/quit, Unit posix - Signal handling - signal/abrt, Unit posix - Signal handling @subsection signal/trap @node Unit posix - Signal handling - signal/quit, Unit posix - Signal handling - signal/alrm, Unit posix - Signal handling - signal/trap, Unit posix - Signal handling @subsection signal/quit @node Unit posix - Signal handling - signal/alrm, Unit posix - Signal handling - signal/vtalrm, Unit posix - Signal handling - signal/quit, Unit posix - Signal handling @subsection signal/alrm @node Unit posix - Signal handling - signal/vtalrm, Unit posix - Signal handling - signal/prof, Unit posix - Signal handling - signal/alrm, Unit posix - Signal handling @subsection signal/vtalrm @node Unit posix - Signal handling - signal/prof, Unit posix - Signal handling - signal/io, Unit posix - Signal handling - signal/vtalrm, Unit posix - Signal handling @subsection signal/prof @node Unit posix - Signal handling - signal/io, Unit posix - Signal handling - signal/urg, Unit posix - Signal handling - signal/prof, Unit posix - Signal handling @subsection signal/io @node Unit posix - Signal handling - signal/urg, Unit posix - Signal handling - signal/chld, Unit posix - Signal handling - signal/io, Unit posix - Signal handling @subsection signal/urg @node Unit posix - Signal handling - signal/chld, Unit posix - Signal handling - signal/cont, Unit posix - Signal handling - signal/urg, Unit posix - Signal handling @subsection signal/chld @node Unit posix - Signal handling - signal/cont, Unit posix - Signal handling - signal/stop, Unit posix - Signal handling - signal/chld, Unit posix - Signal handling @subsection signal/cont @node Unit posix - Signal handling - signal/stop, Unit posix - Signal handling - signal/tstp, Unit posix - Signal handling - signal/cont, Unit posix - Signal handling @subsection signal/stop @node Unit posix - Signal handling - signal/tstp, Unit posix - Signal handling - signal/pipe, Unit posix - Signal handling - signal/stop, Unit posix - Signal handling @subsection signal/tstp @node Unit posix - Signal handling - signal/pipe, Unit posix - Signal handling - signal/xcpu, Unit posix - Signal handling - signal/tstp, Unit posix - Signal handling @subsection signal/pipe @node Unit posix - Signal handling - signal/xcpu, Unit posix - Signal handling - signal/xfsz, Unit posix - Signal handling - signal/pipe, Unit posix - Signal handling @subsection signal/xcpu @node Unit posix - Signal handling - signal/xfsz, Unit posix - Signal handling - signal/usr1, Unit posix - Signal handling - signal/xcpu, Unit posix - Signal handling @subsection signal/xfsz @node Unit posix - Signal handling - signal/usr1, Unit posix - Signal handling - signal/usr2, Unit posix - Signal handling - signal/xfsz, Unit posix - Signal handling @subsection signal/usr1 @node Unit posix - Signal handling - signal/usr2, Unit posix - Signal handling - signal/winch, Unit posix - Signal handling - signal/usr1, Unit posix - Signal handling @subsection signal/usr2 @node Unit posix - Signal handling - signal/winch, , Unit posix - Signal handling - signal/usr2, Unit posix - Signal handling @subsection signal/winch These variables contain signal codes for use with @code{process-signal}, @code{set-signal-handler!}, @code{signal-handler}, @code{signal-masked?}, @code{signal-mask!}, or @code{signal-unmask!}. @node Unit posix - Environment access, Unit posix - Memory mapped I/O, Unit posix - Signal handling, Unit posix @section Environment access @menu * Unit posix - Environment access - current-environment:: * Unit posix - Environment access - setenv:: * Unit posix - Environment access - unsetenv:: @end menu @node Unit posix - Environment access - current-environment, Unit posix - Environment access - setenv, , Unit posix - Environment access @subsection current-environment @verbatim [procedure] (current-environment) @end verbatim Returns a association list of the environment variables and their current values. @node Unit posix - Environment access - setenv, Unit posix - Environment access - unsetenv, Unit posix - Environment access - current-environment, Unit posix - Environment access @subsection setenv @verbatim [procedure] (setenv VARIABLE VALUE) @end verbatim Sets the environment variable named @code{VARIABLE} to @code{VALUE}. Both arguments should be strings. If the variable is not defined in the environment, a new definition is created. @node Unit posix - Environment access - unsetenv, , Unit posix - Environment access - setenv, Unit posix - Environment access @subsection unsetenv @verbatim [procedure] (unsetenv VARIABLE) @end verbatim Removes the definition of the environment variable @code{VARIABLE} from the environment of the current process. If the variable is not defined, nothing happens. @node Unit posix - Memory mapped I/O, Unit posix - Date and time routines, Unit posix - Environment access, Unit posix @section Memory mapped I/O @menu * Unit posix - Memory mapped I/O - memory-mapped-file?:: * Unit posix - Memory mapped I/O - map-file-to-memory:: * Unit posix - Memory mapped I/O - memory-mapped-file-pointer:: * Unit posix - Memory mapped I/O - unmap-file-from-memory:: @end menu @node Unit posix - Memory mapped I/O - memory-mapped-file?, Unit posix - Memory mapped I/O - map-file-to-memory, , Unit posix - Memory mapped I/O @subsection memory-mapped-file? @verbatim [pocedure] (memory-mapped-file? X) @end verbatim Returns @code{#t}, if @code{X} is an object representing a memory mapped file, or @code{#f} otherwise. @node Unit posix - Memory mapped I/O - map-file-to-memory, Unit posix - Memory mapped I/O - memory-mapped-file-pointer, Unit posix - Memory mapped I/O - memory-mapped-file?, Unit posix - Memory mapped I/O @subsection map-file-to-memory @verbatim [procedure] (map-file-to-memory ADDRESS LEN PROTECTION FLAG FILENO [OFFSET]) @end verbatim Maps a section of a file to memory using the C function @code{mmap()}. @code{ADDRESS} should be a foreign pointer object or @code{#f}; @code{LEN} specifies the size of the section to be mapped; @code{PROTECTION} should be one or more of the flags @code{prot/read, prot/write, prot/exec} or @code{prot/none} @b{bitwise-ior}ed together; @code{FLAG} should be one or more of the flags @code{map/fixed, map/shared, map/private, map/anonymous} or @code{map/file}; @code{FILENO} should be the file-descriptor of the mapped file. The optional argument @code{OFFSET} gives the offset of the section of the file to be mapped and defaults to 0. This procedure returns an object representing the mapped file section. The procedure @code{move-memory!} can be used to access the mapped memory. @node Unit posix - Memory mapped I/O - memory-mapped-file-pointer, Unit posix - Memory mapped I/O - unmap-file-from-memory, Unit posix - Memory mapped I/O - map-file-to-memory, Unit posix - Memory mapped I/O @subsection memory-mapped-file-pointer @verbatim [procedure] (memory-mapped-file-pointer MMAP) @end verbatim Returns a machine pointer to the start of the memory region to which the file is mapped. @node Unit posix - Memory mapped I/O - unmap-file-from-memory, , Unit posix - Memory mapped I/O - memory-mapped-file-pointer, Unit posix - Memory mapped I/O @subsection unmap-file-from-memory @verbatim [procedure] (unmap-file-from-memory MMAP [LEN]) @end verbatim Unmaps the section of a file mapped to memory using the C function @code{munmap()}. @code{MMAP} should be a mapped file as returned by the procedure @code{map-file-to-memory}. The optional argument @code{LEN} specifies the length of the section to be unmapped and defaults to the complete length given when the file was mapped. @node Unit posix - Date and time routines, Unit posix - Raw exit, Unit posix - Memory mapped I/O, Unit posix @section Date and time routines @menu * Unit posix - Date and time routines - seconds->local-time:: * Unit posix - Date and time routines - local-time->seconds:: * Unit posix - Date and time routines - local-timezone-abbreviation:: * Unit posix - Date and time routines - seconds->string:: * Unit posix - Date and time routines - seconds->utc-time:: * Unit posix - Date and time routines - utc-time->seconds:: * Unit posix - Date and time routines - time->string:: @end menu @node Unit posix - Date and time routines - seconds->local-time, Unit posix - Date and time routines - local-time->seconds, , Unit posix - Date and time routines @subsection seconds->local-time @verbatim [procedure] (seconds->local-time SECONDS) @end verbatim Breaks down the time value represented in @code{SECONDS} into a 10 element vector of the form @code{#(seconds minutes hours mday month year wday yday dstflag timezone)}, in the following format: @table @b @item seconds (0) the number of seconds after the minute (0 - 59) @item minutes (1) the number of minutes after the hour (0 - 59) @item hours (2) the number of hours past midnight (0 - 23) @item mday (3) the day of the month (1 - 31) @item month (4) the number of months since january (0 - 11) @item year (5) the number of years since 1900 @item wday (6) the number of days since Sunday (0 - 6) @item yday (7) the number of days since January 1 (0 - 365) @item dstflag (8) a flag that is true if Daylight Saving Time is in effect at the time described. @item timezone (9) the difference between UTC and the latest local standard time, in seconds west of UTC. @end table @node Unit posix - Date and time routines - local-time->seconds, Unit posix - Date and time routines - local-timezone-abbreviation, Unit posix - Date and time routines - seconds->local-time, Unit posix - Date and time routines @subsection local-time->seconds @verbatim [procedure] (local-time->seconds VECTOR) @end verbatim Converts the ten-element vector @code{VECTOR} representing the time value relative to the current timezone into the number of seconds since the first of January, 1970 UTC. @node Unit posix - Date and time routines - local-timezone-abbreviation, Unit posix - Date and time routines - seconds->string, Unit posix - Date and time routines - local-time->seconds, Unit posix - Date and time routines @subsection local-timezone-abbreviation @verbatim [procedure] (local-timezone-abbreviation) @end verbatim Returns the abbreviation for the local timezone as a string. @node Unit posix - Date and time routines - seconds->string, Unit posix - Date and time routines - seconds->utc-time, Unit posix - Date and time routines - local-timezone-abbreviation, Unit posix - Date and time routines @subsection seconds->string @verbatim [procedure] (seconds->string SECONDS) @end verbatim Converts the local time represented in @code{SECONDS} into a string of the form @code{"Tue May 21 13:46:22 1991\n"}. @node Unit posix - Date and time routines - seconds->utc-time, Unit posix - Date and time routines - utc-time->seconds, Unit posix - Date and time routines - seconds->string, Unit posix - Date and time routines @subsection seconds->utc-time @verbatim [procedure] (seconds->utc-time SECONDS) @end verbatim Similar to @code{seconds->local-time}, but interpretes @code{SECONDS} as UTC time. @node Unit posix - Date and time routines - utc-time->seconds, Unit posix - Date and time routines - time->string, Unit posix - Date and time routines - seconds->utc-time, Unit posix - Date and time routines @subsection utc-time->seconds @verbatim [procedure] (utc-time->seconds VECTOR) @end verbatim Converts the ten-element vector @code{VECTOR} representing the UTC time value into the number of seconds since the first of January, 1970 UTC. @node Unit posix - Date and time routines - time->string, , Unit posix - Date and time routines - utc-time->seconds, Unit posix - Date and time routines @subsection time->string @verbatim [procedure] (time->string VECTOR) @end verbatim Converts the broken down time represented in the 10 element vector @code{VECTOR} into a string of the form @code{"Tue May 21 13:46:22 1991\n"}. @node Unit posix - Raw exit, Unit posix - ERRNO values, Unit posix - Date and time routines, Unit posix @section Raw exit @menu * Unit posix - Raw exit - _exit:: @end menu @node Unit posix - Raw exit - _exit, , , Unit posix - Raw exit @subsection _exit @verbatim [procedure] (_exit [CODE]) @end verbatim Exits the current process without flushing any buffered output (using the C function @code{_exit}). Note that the @code{exit-handler} is not called when this procedure is invoked. The optional return-code @code{CODE} defaults to @code{0}. @node Unit posix - ERRNO values, Unit posix - Finding files, Unit posix - Raw exit, Unit posix @section ERRNO values @menu * Unit posix - ERRNO values - errno/perm:: * Unit posix - ERRNO values - errno/noent:: * Unit posix - ERRNO values - errno/srch:: * Unit posix - ERRNO values - errno/intr:: * Unit posix - ERRNO values - errno/io:: * Unit posix - ERRNO values - errno/noexec:: * Unit posix - ERRNO values - errno/badf:: * Unit posix - ERRNO values - errno/child:: * Unit posix - ERRNO values - errno/nomem:: * Unit posix - ERRNO values - errno/acces:: * Unit posix - ERRNO values - errno/fault:: * Unit posix - ERRNO values - errno/busy:: * Unit posix - ERRNO values - errno/notdir:: * Unit posix - ERRNO values - errno/isdir:: * Unit posix - ERRNO values - errno/inval:: * Unit posix - ERRNO values - errno/mfile:: * Unit posix - ERRNO values - errno/nospc:: * Unit posix - ERRNO values - errno/spipe:: * Unit posix - ERRNO values - errno/pipe:: * Unit posix - ERRNO values - errno/again:: * Unit posix - ERRNO values - errno/rofs:: * Unit posix - ERRNO values - errno/exist:: * Unit posix - ERRNO values - errno/wouldblock:: @end menu @node Unit posix - ERRNO values - errno/perm, Unit posix - ERRNO values - errno/noent, , Unit posix - ERRNO values @subsection errno/perm @node Unit posix - ERRNO values - errno/noent, Unit posix - ERRNO values - errno/srch, Unit posix - ERRNO values - errno/perm, Unit posix - ERRNO values @subsection errno/noent @node Unit posix - ERRNO values - errno/srch, Unit posix - ERRNO values - errno/intr, Unit posix - ERRNO values - errno/noent, Unit posix - ERRNO values @subsection errno/srch @node Unit posix - ERRNO values - errno/intr, Unit posix - ERRNO values - errno/io, Unit posix - ERRNO values - errno/srch, Unit posix - ERRNO values @subsection errno/intr @node Unit posix - ERRNO values - errno/io, Unit posix - ERRNO values - errno/noexec, Unit posix - ERRNO values - errno/intr, Unit posix - ERRNO values @subsection errno/io @node Unit posix - ERRNO values - errno/noexec, Unit posix - ERRNO values - errno/badf, Unit posix - ERRNO values - errno/io, Unit posix - ERRNO values @subsection errno/noexec @node Unit posix - ERRNO values - errno/badf, Unit posix - ERRNO values - errno/child, Unit posix - ERRNO values - errno/noexec, Unit posix - ERRNO values @subsection errno/badf @node Unit posix - ERRNO values - errno/child, Unit posix - ERRNO values - errno/nomem, Unit posix - ERRNO values - errno/badf, Unit posix - ERRNO values @subsection errno/child @node Unit posix - ERRNO values - errno/nomem, Unit posix - ERRNO values - errno/acces, Unit posix - ERRNO values - errno/child, Unit posix - ERRNO values @subsection errno/nomem @node Unit posix - ERRNO values - errno/acces, Unit posix - ERRNO values - errno/fault, Unit posix - ERRNO values - errno/nomem, Unit posix - ERRNO values @subsection errno/acces @node Unit posix - ERRNO values - errno/fault, Unit posix - ERRNO values - errno/busy, Unit posix - ERRNO values - errno/acces, Unit posix - ERRNO values @subsection errno/fault @node Unit posix - ERRNO values - errno/busy, Unit posix - ERRNO values - errno/notdir, Unit posix - ERRNO values - errno/fault, Unit posix - ERRNO values @subsection errno/busy @node Unit posix - ERRNO values - errno/notdir, Unit posix - ERRNO values - errno/isdir, Unit posix - ERRNO values - errno/busy, Unit posix - ERRNO values @subsection errno/notdir @node Unit posix - ERRNO values - errno/isdir, Unit posix - ERRNO values - errno/inval, Unit posix - ERRNO values - errno/notdir, Unit posix - ERRNO values @subsection errno/isdir @node Unit posix - ERRNO values - errno/inval, Unit posix - ERRNO values - errno/mfile, Unit posix - ERRNO values - errno/isdir, Unit posix - ERRNO values @subsection errno/inval @node Unit posix - ERRNO values - errno/mfile, Unit posix - ERRNO values - errno/nospc, Unit posix - ERRNO values - errno/inval, Unit posix - ERRNO values @subsection errno/mfile @node Unit posix - ERRNO values - errno/nospc, Unit posix - ERRNO values - errno/spipe, Unit posix - ERRNO values - errno/mfile, Unit posix - ERRNO values @subsection errno/nospc @node Unit posix - ERRNO values - errno/spipe, Unit posix - ERRNO values - errno/pipe, Unit posix - ERRNO values - errno/nospc, Unit posix - ERRNO values @subsection errno/spipe @node Unit posix - ERRNO values - errno/pipe, Unit posix - ERRNO values - errno/again, Unit posix - ERRNO values - errno/spipe, Unit posix - ERRNO values @subsection errno/pipe @node Unit posix - ERRNO values - errno/again, Unit posix - ERRNO values - errno/rofs, Unit posix - ERRNO values - errno/pipe, Unit posix - ERRNO values @subsection errno/again @node Unit posix - ERRNO values - errno/rofs, Unit posix - ERRNO values - errno/exist, Unit posix - ERRNO values - errno/again, Unit posix - ERRNO values @subsection errno/rofs @node Unit posix - ERRNO values - errno/exist, Unit posix - ERRNO values - errno/wouldblock, Unit posix - ERRNO values - errno/rofs, Unit posix - ERRNO values @subsection errno/exist @node Unit posix - ERRNO values - errno/wouldblock, , Unit posix - ERRNO values - errno/exist, Unit posix - ERRNO values @subsection errno/wouldblock These variables contain error codes as returned by @code{errno}. @node Unit posix - Finding files, Unit posix - Getting the hostname and system information, Unit posix - ERRNO values, Unit posix @section Finding files @menu * Unit posix - Finding files - find-files:: @end menu @node Unit posix - Finding files - find-files, , , Unit posix - Finding files @subsection find-files @verbatim [procedure] (find-files DIRECTORY PREDICATE [ACTION [IDENTITY [LIMIT]]]) @end verbatim Recursively traverses the contents of @code{DIRECTORY} (which should be a string) and invokes the procedure @code{ACTION} for all files for which the procedure @code{PREDICATE} is true. @code{PREDICATE} may me a procedure of one argument or a regular-expression string. @code{ACTION} should be a procedure of two arguments: the currently encountered file and the result of the previous invocation of @code{ACTION}, or, if this is the first invocation, the value of @code{IDENTITY}. @code{ACTION} defaults to @code{cons}, @code{IDENTITY} defaults to @code{()}. @code{LIMIT} should a procedure of one argument that is called for each nested directory and which should return true, if that directory is to be traversed recursively. @code{LIMIT} may also be an exact integer that gives the maximum recursion depth. A depth of @code{0} means the files in the specified directory are traversed but not any nested directories. @code{LIMIT} may also be @code{#f} (the default), which is equivalent to @code{(constantly #t)}. Note that @code{ACTION} is called with the full pathname of each file, including the directory prefix. @node Unit posix - Getting the hostname and system information, Unit posix - Setting the file buffering mode, Unit posix - Finding files, Unit posix @section Getting the hostname and system information @menu * Unit posix - Getting the hostname and system information - get-host-name:: * Unit posix - Getting the hostname and system information - system-information:: @end menu @node Unit posix - Getting the hostname and system information - get-host-name, Unit posix - Getting the hostname and system information - system-information, , Unit posix - Getting the hostname and system information @subsection get-host-name @verbatim [procedure] (get-host-name) @end verbatim Returns the hostname of the machine that this process is running on. @node Unit posix - Getting the hostname and system information - system-information, , Unit posix - Getting the hostname and system information - get-host-name, Unit posix - Getting the hostname and system information @subsection system-information @verbatim [procedure] (system-information) @end verbatim Invokes the UNIX system call @code{uname()} and returns a list of 5 values: system-name, node-name, OS release, OS version and machine. @node Unit posix - Setting the file buffering mode, Unit posix - Terminal ports, Unit posix - Getting the hostname and system information, Unit posix @section Setting the file buffering mode @menu * Unit posix - Setting the file buffering mode - set-buffering-mode!:: @end menu @node Unit posix - Setting the file buffering mode - set-buffering-mode!, , , Unit posix - Setting the file buffering mode @subsection set-buffering-mode! @verbatim [procedure] (set-buffering-mode! PORT MODE [BUFSIZE]) @end verbatim Sets the buffering-mode for the file associated with @code{PORT} to @code{MODE}, which should be one of the keywords @code{#:full}, @code{#:line} or @code{#:none}. If @code{BUFSIZE} is specified it determines the size of the buffer to be used (if any). @node Unit posix - Terminal ports, Unit posix - How Scheme procedures relate to UNIX C functions, Unit posix - Setting the file buffering mode, Unit posix @section Terminal ports @menu * Unit posix - Terminal ports - terminal-name:: * Unit posix - Terminal ports - terminal-port?:: @end menu @node Unit posix - Terminal ports - terminal-name, Unit posix - Terminal ports - terminal-port?, , Unit posix - Terminal ports @subsection terminal-name @verbatim [procedure] (terminal-name PORT) @end verbatim Returns the name of the terminal that is connected to @code{PORT}. @node Unit posix - Terminal ports - terminal-port?, , Unit posix - Terminal ports - terminal-name, Unit posix - Terminal ports @subsection terminal-port? @verbatim [procedure] (terminal-port? PORT) @end verbatim Returns @code{#t} if @code{PORT} is connected to a terminal and @code{#f} otherwise. @node Unit posix - How Scheme procedures relate to UNIX C functions, Unit posix - Windows specific notes, Unit posix - Terminal ports, Unit posix @section How Scheme procedures relate to UNIX C functions
change-directory chdir
change-file-mode chmod
change-file-owner chown
create-directory mkdir
create-fifo mkfifo
create-pipe pipe
create-session setsid
create-symbolic-link link
current-directory curdir
current-effective-groupd-id getegid
current-effective-user-id geteuid
current-group-id getgid
current-parent-id getppid
current-process-id getpid
current-user-id getuid
delete-directory rmdir
duplicate-fileno dup/dup2
_exit _exit
file-close close
file-access-time stat
file-change-time stat
file-modification-time stat
file-execute-access? access
file-open open
file-lock fcntl
file-position ftell/lseek
file-read read
file-read-access? access
file-select select
file-control fcntl
file-stat stat
file-test-lock fcntl
file-truncate truncate/ftruncate
file-unlock fcntl
file-write write
file-write-access? access
get-groups getgroups
get-host-name gethostname
initialize-groups initgroups
local-time->seconds mktime
local-timezone-abbreviation localtime
map-file-to-memory mmap
open-input-file* fdopen
open-output-file* fdopen
open-input-pipe popen
open-output-pipe popen
port->fileno fileno
process-execute execvp
process-fork fork
process-group-id getpgid
process-signal kill
process-wait waitpid
close-input-pipe pclose
close-output-pipe pclose
read-symbolic-link readlink
seconds->local-time localtime
seconds->string ctime
seconds->utc-time gmtime
set-alarm! alarm
set-buffering-mode! setvbuf
set-file-position! fseek/seek
set-groups! setgroups
set-signal-mask! sigprocmask
set-group-id! setgid
set-process-group-id! setpgid
set-user-id! setuid
set-root-directory! chroot
setenv setenv/putenv
sleep sleep
system-information uname
terminal-name ttyname
terminal-port? isatty
time->string asctime
unsetenv putenv
unmap-file-from-memory munmap
user-information getpwnam/getpwuid
utc-time->seconds timegm
@node Unit posix - Windows specific notes, , Unit posix - How Scheme procedures relate to UNIX C functions, Unit posix @section Windows specific notes @menu * Unit posix - Windows specific notes - Procedure Changes:: * Unit posix - Windows specific notes - Unsupported Definitions:: * Unit posix - Windows specific notes - Additional Definitions:: * Unit posix - Windows specific notes - process-spawn:: @end menu Use of UTF8 encoded strings is for pathnames is not supported. Windows uses a 16-bit UNICODE encoding with special system calls for wide-character support. Only single-byte string encoding can be used. @node Unit posix - Windows specific notes - Procedure Changes, Unit posix - Windows specific notes - Unsupported Definitions, , Unit posix - Windows specific notes @subsection Procedure Changes Exceptions to the above procedure definitions. @verbatim [procedure] (create-pipe [MODE]) @end verbatim The optional parameter @code{MODE}, default @code{open/binary | open/noinherit}. This can be @code{open/binary} or @code{open/text}, optionally or'ed with @code{open/noinherit}. @verbatim [procedure] (process-wait [PID [NOHANG]]) @end verbatim @code{process-wait} always returns @code{#t} for a terminated process and only the exit status is available. (Windows does not provide signals as an interprocess communication method.) @verbatim [procedure] (process-execute PATHNAME [ARGUMENT-LIST [ENVIRONMENT-LIST [EXACT-FLAG]]]) [procedure] (process COMMAND ARGUMENT-LIST [ENVIRONMENT-LIST [EXACT-FLAG]]) [procedure] (process* COMMAND ARGUMENT-LIST [ENVIRONMENT-LIST [EXACT-FLAG]]) @end verbatim The optional parameter @code{EXACT-FLAG}, default @code{#f}. When @code{#f} any argument string with embedded whitespace will be wrapped in quotes. When @code{#t} no such wrapping occurs. @node Unit posix - Windows specific notes - Unsupported Definitions, Unit posix - Windows specific notes - Additional Definitions, Unit posix - Windows specific notes - Procedure Changes, Unit posix - Windows specific notes @subsection Unsupported Definitions The following definitions are not supported for native Windows builds (compiled with the Microsoft tools or with MinGW): @verbatim open/noctty open/nonblock open/fsync open/sync perm/isvtx perm/isuid perm/isgid file-select file-control signal/... (except signal/term, signal/int, signal/fpe, signal/ill, signal/segv, signal/abrt, signal/break) set-signal-mask! signal-mask signal-masked? signal-mask! signal-unmask! user-information group-information get-groups set-groups! initialize-groups errno/wouldblock change-file-owner current-user-id current-group-id current-effective-user-id current-effective-groupd-id set-user-id! set-group-id! create-session process-group-id set-process-group-id! create-symbolic-link read-symbolic-link file-truncate file-lock file-lock/blocking file-unlock file-test-lock create-fifo fifo? prot/... map/... map-file-to-memory unmap-file-from-memory memory-mapped-file-pointer memory-mapped-file? set-alarm! terminal-port? terminal-name process-fork process-signal parent-process-id set-root-directory! utc-time->seconds @end verbatim @node Unit posix - Windows specific notes - Additional Definitions, Unit posix - Windows specific notes - process-spawn, Unit posix - Windows specific notes - Unsupported Definitions, Unit posix - Windows specific notes @subsection Additional Definitions Only available for Windows @itemize @item open/noinherit @end itemize This variable is a mode value for @code{create-pipe}. Useful when spawning a child process. @itemize @item spawn/overlay @item spawn/wait @item spawn/nowait @item spawn/nowaito @item spawn/detach @end itemize These variables contains special flags that specify the exact semantics of @code{process-spawn}: @code{spawn/overlay} replaces the current process with the new one. @code{spawn/wait} suspends execution of the current process until the spawned process returns. @code{spawn/nowait} does the opposite (@code{spawn/nowaito} is identical, according to the Microsoft documentation) and runs the process asynchronously. @code{spawn/detach} runs the new process in the background, without being attached to a console. @node Unit posix - Windows specific notes - process-spawn, , Unit posix - Windows specific notes - Additional Definitions, Unit posix - Windows specific notes @subsection process-spawn @verbatim [procedure] (process-spawn MODE COMMAND [ARGUMENT-LIST [ENVIRONMENT-LIST [EXACT-FLAG]]]) @end verbatim Creates and runs a new process with the given @code{COMMAND} filename and the optional @code{ARGUMENT-LIST} and @code{ENVIRONMENT-LIST}. @code{MODE} specifies how exactly the process should be executed and must be one or more of the @code{spawn/...} flags defined above. The @code{EXACT-FLAG}, default @code{#f}, controls quote-wrapping of argument strings. When @code{#t} quote-wrapping is not performed. Returns: @itemize @item the exit status when synchronous @item the PID when asynchronous @item -1 when failure @end itemize Previous: @ref{Unit srfi-18, Unit srfi-18} Next: @ref{Unit utils, Unit utils} @node Unit utils, Unit tcp, Unit posix, Top @chapter Unit utils @menu * Unit utils - Environment Query:: * Unit utils - Pathname operations:: * Unit utils - Temporary files:: * Unit utils - Deleting a file without signalling an error:: * Unit utils - Iterating over input lines and files:: * Unit utils - Executing shell commands with formatstring and error checking:: * Unit utils - Reading a file's contents:: * Unit utils - Funky ports:: * Unit utils - Miscellaneous handy things:: @end menu This unit contains file/pathname oriented procedures, apropos, plus acts as a "grab bag" for procedures without a good home, and which don't have to be available by default (as compared to the @ref{Unit extras, extras} unit). This unit uses the @code{extras} and @code{regex} units. @node Unit utils - Environment Query, Unit utils - Pathname operations, , Unit utils @section Environment Query @menu * Unit utils - Environment Query - apropos:: * Unit utils - Environment Query - apropos-list:: @end menu @node Unit utils - Environment Query - apropos, Unit utils - Environment Query - apropos-list, , Unit utils - Environment Query @subsection apropos @verbatim [procedure] (apropos SYMBOL-PATTERN [ENVIRONMENT] [#:MACROS?]) @end verbatim Displays symbols & type matching @code{SYMBOL-PATTERN} in the @code{ENVIRONMENT} on the @code{(current-output-port)}. @table @b @item @code{SYMBOL-PATTERN} A symbol, string, or regex. When symbol or string substring matching is performed. @item @code{ENVIRONMENT} An environment. When missing the @code{(interaction-environment)} is assumed. @item @code{#:MACROS?} Keyword argument. A boolean. Include macro symbols? When missing @code{#f} is assumed. @end table @node Unit utils - Environment Query - apropos-list, , Unit utils - Environment Query - apropos, Unit utils - Environment Query @subsection apropos-list @verbatim [procedure] (apropos-list SYMBOL-PATTERN [ENVIRONMENT] [#:MACROS?]) @end verbatim Like @code{apropos} but returns a list of matching symbols. @node Unit utils - Pathname operations, Unit utils - Temporary files, Unit utils - Environment Query, Unit utils @section Pathname operations @menu * Unit utils - Pathname operations - absolute-pathname?:: * Unit utils - Pathname operations - decompose-pathname:: * Unit utils - Pathname operations - make-pathname:: * Unit utils - Pathname operations - make-absolute-pathname:: * Unit utils - Pathname operations - pathname-directory:: * Unit utils - Pathname operations - pathname-file:: * Unit utils - Pathname operations - pathname-extension:: * Unit utils - Pathname operations - pathname-replace-directory:: * Unit utils - Pathname operations - pathname-replace-file:: * Unit utils - Pathname operations - pathname-replace-extension:: * Unit utils - Pathname operations - pathname-strip-directory:: * Unit utils - Pathname operations - pathname-strip-extension:: * Unit utils - Pathname operations - directory-null?:: @end menu @node Unit utils - Pathname operations - absolute-pathname?, Unit utils - Pathname operations - decompose-pathname, , Unit utils - Pathname operations @subsection absolute-pathname? @verbatim [procedure] (absolute-pathname? PATHNAME) @end verbatim Returns @code{#t} if the string @code{PATHNAME} names an absolute pathname, and returns @code{#f} otherwise. @node Unit utils - Pathname operations - decompose-pathname, Unit utils - Pathname operations - make-pathname, Unit utils - Pathname operations - absolute-pathname?, Unit utils - Pathname operations @subsection decompose-pathname @verbatim [procedure] (decompose-pathname PATHNAME) @end verbatim Returns three values: the directory-, filename- and extension-components of the file named by the string @code{PATHNAME}. For any component that is not contained in @code{PATHNAME}, @code{#f} is returned. @node Unit utils - Pathname operations - make-pathname, Unit utils - Pathname operations - make-absolute-pathname, Unit utils - Pathname operations - decompose-pathname, Unit utils - Pathname operations @subsection make-pathname @node Unit utils - Pathname operations - make-absolute-pathname, Unit utils - Pathname operations - pathname-directory, Unit utils - Pathname operations - make-pathname, Unit utils - Pathname operations @subsection make-absolute-pathname @verbatim [procedure] (make-pathname DIRECTORY FILENAME [EXTENSION [SEPARATOR]]) [procedure] (make-absolute-pathname DIRECTORY FILENAME [EXTENSION [SEPARATOR]]) @end verbatim Returns a string that names the file with the components @code{DIRECTORY, FILENAME} and (optionally) @code{EXTENSION} with @code{SEPARATOR} being the directory separation indicator (usually @code{/} on UNIX systems and @code{\} on Windows, defaulting to whatever platform this is running on). @code{DIRECTORY} can be @code{#f} (meaning no directory component), a string or a list of strings. @code{FILENAME} and @code{EXTENSION} should be strings or @code{#f}. @code{make-absolute-pathname} returns always an absolute pathname. @node Unit utils - Pathname operations - pathname-directory, Unit utils - Pathname operations - pathname-file, Unit utils - Pathname operations - make-absolute-pathname, Unit utils - Pathname operations @subsection pathname-directory @verbatim [procedure] (pathname-directory PATHNAME) @end verbatim @node Unit utils - Pathname operations - pathname-file, Unit utils - Pathname operations - pathname-extension, Unit utils - Pathname operations - pathname-directory, Unit utils - Pathname operations @subsection pathname-file @verbatim [procedure] (pathname-file PATHNAME) @end verbatim @node Unit utils - Pathname operations - pathname-extension, Unit utils - Pathname operations - pathname-replace-directory, Unit utils - Pathname operations - pathname-file, Unit utils - Pathname operations @subsection pathname-extension @verbatim [procedure] (pathname-extension PATHNAME) @end verbatim Accessors for the components of @code{PATHNAME}. If the pathname does not contain the accessed component, then @code{#f} is returned. @node Unit utils - Pathname operations - pathname-replace-directory, Unit utils - Pathname operations - pathname-replace-file, Unit utils - Pathname operations - pathname-extension, Unit utils - Pathname operations @subsection pathname-replace-directory @verbatim [procedure] (pathname-replace-directory PATHNAME DIRECTORY) @end verbatim @node Unit utils - Pathname operations - pathname-replace-file, Unit utils - Pathname operations - pathname-replace-extension, Unit utils - Pathname operations - pathname-replace-directory, Unit utils - Pathname operations @subsection pathname-replace-file @verbatim [procedure] (pathname-replace-file PATHNAME FILENAME) @end verbatim @node Unit utils - Pathname operations - pathname-replace-extension, Unit utils - Pathname operations - pathname-strip-directory, Unit utils - Pathname operations - pathname-replace-file, Unit utils - Pathname operations @subsection pathname-replace-extension @verbatim [procedure] (pathname-replace-extension PATHNAME EXTENSION) @end verbatim Return a new pathname with the specified component of @code{PATHNAME} replaced by a new value. @node Unit utils - Pathname operations - pathname-strip-directory, Unit utils - Pathname operations - pathname-strip-extension, Unit utils - Pathname operations - pathname-replace-extension, Unit utils - Pathname operations @subsection pathname-strip-directory @verbatim [procedure] (pathname-strip-directory PATHNAME) @end verbatim @node Unit utils - Pathname operations - pathname-strip-extension, Unit utils - Pathname operations - directory-null?, Unit utils - Pathname operations - pathname-strip-directory, Unit utils - Pathname operations @subsection pathname-strip-extension @verbatim [procedure] (pathname-strip-extension PATHNAME) @end verbatim Return a new pathname with the specified component of @code{PATHNAME} stripped. @node Unit utils - Pathname operations - directory-null?, , Unit utils - Pathname operations - pathname-strip-extension, Unit utils - Pathname operations @subsection directory-null? @verbatim [procedure] (directory-null? DIRECTORY) @end verbatim Does the @code{DIRECTORY} consist only of path separators and the period? @code{DIRECTORY} may be a string or a list of strings. @node Unit utils - Temporary files, Unit utils - Deleting a file without signalling an error, Unit utils - Pathname operations, Unit utils @section Temporary files @menu * Unit utils - Temporary files - create-temporary-file:: @end menu @node Unit utils - Temporary files - create-temporary-file, , , Unit utils - Temporary files @subsection create-temporary-file @verbatim [procedure] (create-temporary-file [EXTENSION]) @end verbatim Creates an empty temporary file and returns its pathname. If @code{EXTENSION} is not given, then @code{.tmp} is used. If the environment variable @code{TMPDIR, TEMP} or @code{TMP} is set, then the pathname names a file in that directory. @node Unit utils - Deleting a file without signalling an error, Unit utils - Iterating over input lines and files, Unit utils - Temporary files, Unit utils @section Deleting a file without signalling an error @menu * Unit utils - Deleting a file without signalling an error - delete-file*:: @end menu @node Unit utils - Deleting a file without signalling an error - delete-file*, , , Unit utils - Deleting a file without signalling an error @subsection delete-file* @verbatim [procedure] (delete-file* FILENAME) @end verbatim If the file @code{FILENAME} exists, it is deleted and @code{#t} is returned. If the file does not exist, nothing happens and @code{#f} is returned. @node Unit utils - Iterating over input lines and files, Unit utils - Executing shell commands with formatstring and error checking, Unit utils - Deleting a file without signalling an error, Unit utils @section Iterating over input lines and files @menu * Unit utils - Iterating over input lines and files - for-each-line:: * Unit utils - Iterating over input lines and files - for-each-argv-line:: * Unit utils - Iterating over input lines and files - port-for-each:: * Unit utils - Iterating over input lines and files - port-map:: * Unit utils - Iterating over input lines and files - port-fold:: @end menu @node Unit utils - Iterating over input lines and files - for-each-line, Unit utils - Iterating over input lines and files - for-each-argv-line, , Unit utils - Iterating over input lines and files @subsection for-each-line @verbatim [procedure] (for-each-line PROCEDURE [PORT]) @end verbatim Calls @code{PROCEDURE} for each line read from @code{PORT} (which defaults to the value of @code{(current-input-port)}. The argument passed to @code{PORCEDURE} is a string with the contents of the line, excluding any line-terminators. When all input has been read from the port, @code{for-each-line} returns some unspecified value. @node Unit utils - Iterating over input lines and files - for-each-argv-line, Unit utils - Iterating over input lines and files - port-for-each, Unit utils - Iterating over input lines and files - for-each-line, Unit utils - Iterating over input lines and files @subsection for-each-argv-line @verbatim [procedure] (for-each-argv-line PROCEDURE) @end verbatim Opens each file listed on the command line in order, passing one line at a time into @code{PROCEDURE}. The filename @code{-} is interpreted as @code{(current-input-port)}. If no arguments are given on the command line it again uses the value of @code{(current-input-port)}. During execution of @code{PROCEDURE}, the current input port will be correctly bound to the current input source. This code will act as a simple Unix cat(1) command: (for-each-argv-line print) @node Unit utils - Iterating over input lines and files - port-for-each, Unit utils - Iterating over input lines and files - port-map, Unit utils - Iterating over input lines and files - for-each-argv-line, Unit utils - Iterating over input lines and files @subsection port-for-each @verbatim [procedure] (port-for-each FN THUNK) @end verbatim Apply @code{FN} to successive results of calling the zero argument procedure @code{THUNK} until it returns @code{#!eof}, discarding the results. @node Unit utils - Iterating over input lines and files - port-map, Unit utils - Iterating over input lines and files - port-fold, Unit utils - Iterating over input lines and files - port-for-each, Unit utils - Iterating over input lines and files @subsection port-map @verbatim [procedure] (port-map FN THUNK) @end verbatim Apply @code{FN} to successive results of calling the zero argument procedure @code{THUNK} until it returns @code{#!eof}, returning a list of the collected results. @node Unit utils - Iterating over input lines and files - port-fold, , Unit utils - Iterating over input lines and files - port-map, Unit utils - Iterating over input lines and files @subsection port-fold @verbatim [procedure] (port-map FN ACC THUNK) @end verbatim Apply @code{FN} to successive results of calling the zero argument procedure @code{THUNK}, passing the @code{ACC} value as the second argument. The @code{FN} result becomes the new @code{ACC} value. When @code{THUNK} returns @code{#!eof}, the last @code{FN} result is returned. @node Unit utils - Executing shell commands with formatstring and error checking, Unit utils - Reading a file's contents, Unit utils - Iterating over input lines and files, Unit utils @section Executing shell commands with formatstring and error checking @menu * Unit utils - Executing shell commands with formatstring and error checking - system*:: @end menu @node Unit utils - Executing shell commands with formatstring and error checking - system*, , , Unit utils - Executing shell commands with formatstring and error checking @subsection system* @verbatim [procedure] (system* FORMATSTRING ARGUMENT1 ...) @end verbatim Similar to @code{(system (sprintf FORMATSTRING ARGUMENT1 ...))}, but signals an error if the invoked program should return a nonzero exit status. @node Unit utils - Reading a file's contents, Unit utils - Funky ports, Unit utils - Executing shell commands with formatstring and error checking, Unit utils @section Reading a file's contents @menu * Unit utils - Reading a file's contents - read-all:: @end menu @node Unit utils - Reading a file's contents - read-all, , , Unit utils - Reading a file's contents @subsection read-all @verbatim [procedure] (read-all [FILE-OR-PORT]) @end verbatim If @code{FILE-OR-PORT} is a string, then this procedure returns the contents of the file as a string. If @code{FILE-OR-PORT} is a port, all remaining input is read and returned as a string. The port is not closed. If no argument is provided, input will be read from the port that is the current value of @code{(current-input-port)}. @node Unit utils - Funky ports, Unit utils - Miscellaneous handy things, Unit utils - Reading a file's contents, Unit utils @section Funky ports @menu * Unit utils - Funky ports - make-broadcast-port:: * Unit utils - Funky ports - make-concatenated-port:: @end menu @node Unit utils - Funky ports - make-broadcast-port, Unit utils - Funky ports - make-concatenated-port, , Unit utils - Funky ports @subsection make-broadcast-port @verbatim [procedure] (make-broadcast-port PORT ...) @end verbatim Returns a custom output port that emits everything written into it to the ports given as @code{PORT ...}. Closing the broadcast port does not close any of the argument ports. @node Unit utils - Funky ports - make-concatenated-port, , Unit utils - Funky ports - make-broadcast-port, Unit utils - Funky ports @subsection make-concatenated-port @verbatim [procedure] (make-concatenated-port PORT1 PORT2 ...) @end verbatim Returns a custom input port that reads its input from @code{PORT1}, until it is empty, then from @code{PORT2} and so on. Closing the concatenated port does not close any of the argument ports. @node Unit utils - Miscellaneous handy things, , Unit utils - Funky ports, Unit utils @section Miscellaneous handy things @menu * Unit utils - Miscellaneous handy things - shift!:: * Unit utils - Miscellaneous handy things - unshift!:: @end menu @node Unit utils - Miscellaneous handy things - shift!, Unit utils - Miscellaneous handy things - unshift!, , Unit utils - Miscellaneous handy things @subsection shift! @verbatim [procedure] (shift! LIST [DEFAULT]) @end verbatim Returns the car of @code{LIST} (or @code{DEFAULT} if @code{LIST} is empty) and replaces the car of @code{LIST} with it's cadr and the cdr with the cddr. If @code{DEFAULT} is not given, and the list is empty, @code{#f} is returned. An example might be clearer, here: (define lst '(1 2 3)) (shift! lst) ==> 1, lst is now (2 3) The list must contain at least 2 elements. @node Unit utils - Miscellaneous handy things - unshift!, , Unit utils - Miscellaneous handy things - shift!, Unit utils - Miscellaneous handy things @subsection unshift! @verbatim [procedure] (unshift! X PAIR) @end verbatim Sets the car of @code{PAIR} to @code{X} and the cdr to its cddr. Returns @code{PAIR}: (define lst '(2)) (unshift! 99 lst) ; lst is now (99 2) Previous: @ref{Unit posix, Unit posix} Next: @ref{Unit tcp, Unit tcp} @node Unit tcp, Unit lolevel, Unit utils, Top @chapter Unit tcp @menu * Unit tcp - tcp-listen:: * Unit tcp - tcp-listener?:: * Unit tcp - tcp-close:: * Unit tcp - tcp-accept:: * Unit tcp - tcp-accept-ready?:: * Unit tcp - tcp-listener-port:: * Unit tcp - tcp-listener-fileno:: * Unit tcp - tcp-connect:: * Unit tcp - tcp-addresses:: * Unit tcp - tcp-port-numbers:: * Unit tcp - tcp-abandon-port:: * Unit tcp - tcp-buffer-size:: * Unit tcp - tcp-read-timeout:: * Unit tcp - tcp-write-timeout:: * Unit tcp - tcp-connect-timeout:: * Unit tcp - tcp-accept-timeout:: * Unit tcp - Example:: @end menu This unit provides basic facilities for communicating over TCP sockets. The socket interface should be mostly compatible to the one found in PLT Scheme. This unit uses the @code{extras} unit. All errors related to failing network operations will raise a condition of kind @code{(exn i/o network)}. @node Unit tcp - tcp-listen, Unit tcp - tcp-listener?, , Unit tcp @section tcp-listen @verbatim [procedure] (tcp-listen TCPPORT [BACKLOG [HOST]]) @end verbatim Creates and returns a TCP listener object that listens for connections on @code{TCPPORT}, which should be an exact integer. @code{BACKLOG} specifies the number of maximally pending connections (and defaults to 4). If the optional argument @code{HOST} is given and not @code{#f}, then only incoming connections for the given host (or IP) are accepted. @node Unit tcp - tcp-listener?, Unit tcp - tcp-close, Unit tcp - tcp-listen, Unit tcp @section tcp-listener? @verbatim [procedure] (tcp-listener? X) @end verbatim Returns @code{#t} if @code{X} is a TCP listener object, or @code{#f} otherwise. @node Unit tcp - tcp-close, Unit tcp - tcp-accept, Unit tcp - tcp-listener?, Unit tcp @section tcp-close @verbatim [procedure] (tcp-close LISTENER) @end verbatim Reclaims any resources associated with @code{LISTENER}. @node Unit tcp - tcp-accept, Unit tcp - tcp-accept-ready?, Unit tcp - tcp-close, Unit tcp @section tcp-accept @verbatim [procedure] (tcp-accept LISTENER) @end verbatim Waits until a connection is established on the port on which @code{LISTENER} is listening and returns two values: an input- and output-port that can be used to communicate with the remote process. The current value of @code{tcp-accept-timeout} is used to determine the maximal number of milliseconds (if any) to wait until a connection is established. When a client connects any read- and write-operations on the returned ports will use the current values (at the time of the connection) of @code{tcp-read-timeout} and @code{tcp-write-timeout}, respectively, to determine the maximal number of milliseconds to wait for input/output before a timeout error is signalled. Note: this operation and any I/O on the ports returned will not block other running threads. @node Unit tcp - tcp-accept-ready?, Unit tcp - tcp-listener-port, Unit tcp - tcp-accept, Unit tcp @section tcp-accept-ready? @verbatim [procedure] (tcp-accept-ready? LISTENER) @end verbatim Returns @code{#t} if there are any connections pending on @code{LISTENER}, or @code{#f} otherwise. @node Unit tcp - tcp-listener-port, Unit tcp - tcp-listener-fileno, Unit tcp - tcp-accept-ready?, Unit tcp @section tcp-listener-port @verbatim [procedure] (tcp-listener-port LISTENER) @end verbatim Returns the port number assigned to @code{LISTENER} (If you pass @code{0} to @code{tcp-listen}, then the system will choose a port-number for you). @node Unit tcp - tcp-listener-fileno, Unit tcp - tcp-connect, Unit tcp - tcp-listener-port, Unit tcp @section tcp-listener-fileno @verbatim [procedure] (tcp-listener-fileno LISTENER) @end verbatim Returns the file-descriptor associated with @code{LISTENER}. @node Unit tcp - tcp-connect, Unit tcp - tcp-addresses, Unit tcp - tcp-listener-fileno, Unit tcp @section tcp-connect @verbatim [procedure] (tcp-connect HOSTNAME [TCPPORT]) @end verbatim Establishes a client-side TCP connection to the machine with the name @code{HOSTNAME} (a string) at @code{TCPPORT} (an exact integer) and returns two values: an input- and output-port for communicating with the remote process. The current value of @code{tcp-connect-timeout} is used to determine the maximal number of milliseconds (if any) to wait until the connection is established. When the connection takes place any read- and write-operations on the returned ports will use the current values (at the time of the call to @code{tcp-connect}) of @code{tcp-read-timeout} and @code{tcp-write-timeout}, respectively, to determine the maximal number of milliseconds to wait for input/output before a timeout error is signalled. If the @code{TCPPORT} is omitted, the port is parsed from the @code{HOSTNAME} string. The format expected is @code{HOSTNAME:PORT}. The @code{PORT} can either be a string representation of an integer or a service name which is translated to an integer using the POSIX function @uref{http://www.opengroup.org/onlinepubs/009695399/functions/getservbyname.html, @code{getservbyname}}. Note: any I/O on the ports returned will not block other running threads. @node Unit tcp - tcp-addresses, Unit tcp - tcp-port-numbers, Unit tcp - tcp-connect, Unit tcp @section tcp-addresses @verbatim [procedure] (tcp-addresses PORT) @end verbatim Returns two values for the input- or output-port @code{PORT} (which should be a port returned by either @code{tcp-accept} or @code{tcp-connect}): the IP address of the local and the remote machine that are connected over the socket associated with @code{PORT}. The returned addresses are strings in @code{XXX.XXX.XXX.XXX} notation. @node Unit tcp - tcp-port-numbers, Unit tcp - tcp-abandon-port, Unit tcp - tcp-addresses, Unit tcp @section tcp-port-numbers @verbatim [procedure] (tcp-port-numbers PORT) @end verbatim Returns two values for the input- or output-port @code{PORT} (which should be a port returned by either @code{tcp-accept} or @code{tcp-connect}): the TCP port numbers of the local and the remote machine that are connected over the socket associated with @code{PORT}. @node Unit tcp - tcp-abandon-port, Unit tcp - tcp-buffer-size, Unit tcp - tcp-port-numbers, Unit tcp @section tcp-abandon-port @verbatim [procedure] (tcp-abandon-port PORT) @end verbatim Marks the socket port @code{PORT} as abandoned. This is mainly useful to close down a port without breaking the connection. @node Unit tcp - tcp-buffer-size, Unit tcp - tcp-read-timeout, Unit tcp - tcp-abandon-port, Unit tcp @section tcp-buffer-size @verbatim [parameter] tcp-buffer-size @end verbatim Sets the size of the output buffer. By default no output-buffering for TCP output is done, but to improve performance by minimizing the number of TCP packets, buffering may be turned on by setting this parameter to an exact integer greater zero. A buffer size of zero or @code{#f} turns buffering off. The setting of this parameter takes effect at the time when the I/O ports for a particular socket are created, i.e. when @code{tcp-connect} or @code{tcp-accept} is called. Note that since output is not immediately written to the associated socket, you may need to call @code{flush-output}, once you want the output to be transmitted. Closing the output port will flush automatically. @node Unit tcp - tcp-read-timeout, Unit tcp - tcp-write-timeout, Unit tcp - tcp-buffer-size, Unit tcp @section tcp-read-timeout @verbatim [parameter] tcp-read-timeout @end verbatim Determines the timeout for TCP read operations in milliseconds. A timeout of @code{#f} disables timeout checking and is the default. @node Unit tcp - tcp-write-timeout, Unit tcp - tcp-connect-timeout, Unit tcp - tcp-read-timeout, Unit tcp @section tcp-write-timeout @verbatim [parameter] tcp-write-timeout @end verbatim Determines the timeout for TCP write operations in milliseconds. A timeout of @code{#f} disables timeout checking and is the default. @node Unit tcp - tcp-connect-timeout, Unit tcp - tcp-accept-timeout, Unit tcp - tcp-write-timeout, Unit tcp @section tcp-connect-timeout @verbatim [parameter] tcp-connect-timeout @end verbatim Determines the timeout for @code{tcp-connect} operations in milliseconds. A timeout of @code{#f} disables timeout checking and is the default. @node Unit tcp - tcp-accept-timeout, Unit tcp - Example, Unit tcp - tcp-connect-timeout, Unit tcp @section tcp-accept-timeout @verbatim [parameter] tcp-accept-timeout @end verbatim Determines the timeout for @code{tcp-accept} operations in milliseconds. A timeout of @code{#f} disables timeout checking and is the default. @node Unit tcp - Example, , Unit tcp - tcp-accept-timeout, Unit tcp @section Example A very simple example follows. Say we have the two files @code{client.scm} and @code{server.scm}: ; client.scm (declare (uses tcp)) (define-values (i o) (tcp-connect "localhost" 4242)) (write-line "Good Bye!" o) (print (read-line i)) ; server.scm (declare (uses tcp)) (define l (tcp-listen 4242)) (define-values (i o) (tcp-accept l)) (write-line "Hello!" o) (print (read-line i)) (close-input-port i) (close-output-port o) @verbatim % csc server.scm % csc client.scm % ./server & % ./client Good Bye! Hello! @end verbatim Previous: @ref{Unit utils, Unit utils} Next: @ref{Unit lolevel, Unit lolevel} @node Unit lolevel, Interface to external functions and variables, Unit tcp, Top @chapter Unit lolevel @menu * Unit lolevel - Foreign pointers:: * Unit lolevel - Tagged pointers:: * Unit lolevel - Extending procedures with data:: * Unit lolevel - Blobs:: * Unit lolevel - Data in unmanaged memory:: * Unit lolevel - Locatives:: * Unit lolevel - Accessing toplevel variables:: * Unit lolevel - Low-level data access:: * Unit lolevel - Procedure-call- and variable reference hooks:: * Unit lolevel - Magic:: @end menu This unit provides a number of handy low-level operations. @b{Use at your own risk.} This unit uses the @code{srfi-4} and @code{extras} units. @node Unit lolevel - Foreign pointers, Unit lolevel - Tagged pointers, , Unit lolevel @section Foreign pointers @menu * Unit lolevel - Foreign pointers - address->pointer:: * Unit lolevel - Foreign pointers - allocate:: * Unit lolevel - Foreign pointers - free:: * Unit lolevel - Foreign pointers - null-pointer:: * Unit lolevel - Foreign pointers - null-pointer?:: * Unit lolevel - Foreign pointers - object->pointer:: * Unit lolevel - Foreign pointers - pointer?:: * Unit lolevel - Foreign pointers - pointer=?:: * Unit lolevel - Foreign pointers - pointer->address:: * Unit lolevel - Foreign pointers - pointer->object:: * Unit lolevel - Foreign pointers - pointer-offset:: * Unit lolevel - Foreign pointers - pointer-u8-ref:: * Unit lolevel - Foreign pointers - pointer-s8-ref:: * Unit lolevel - Foreign pointers - pointer-u16-ref:: * Unit lolevel - Foreign pointers - pointer-s16-ref:: * Unit lolevel - Foreign pointers - pointer-u32-ref:: * Unit lolevel - Foreign pointers - pointer-s32-ref:: * Unit lolevel - Foreign pointers - pointer-f32-ref:: * Unit lolevel - Foreign pointers - pointer-f64-ref:: * Unit lolevel - Foreign pointers - pointer-u8-set!:: * Unit lolevel - Foreign pointers - pointer-s8-set!:: * Unit lolevel - Foreign pointers - pointer-u16-set!:: * Unit lolevel - Foreign pointers - pointer-s16-set!:: * Unit lolevel - Foreign pointers - pointer-u32-set!:: * Unit lolevel - Foreign pointers - pointer-s32-set!:: * Unit lolevel - Foreign pointers - pointer-f32-set!:: * Unit lolevel - Foreign pointers - pointer-f64-set!:: * Unit lolevel - Foreign pointers - align-to-word:: @end menu @node Unit lolevel - Foreign pointers - address->pointer, Unit lolevel - Foreign pointers - allocate, , Unit lolevel - Foreign pointers @subsection address->pointer @verbatim [procedure] (address->pointer ADDRESS) @end verbatim Creates a new foreign pointer object initialized to point to the address given in the integer @code{ADDRESS}. @node Unit lolevel - Foreign pointers - allocate, Unit lolevel - Foreign pointers - free, Unit lolevel - Foreign pointers - address->pointer, Unit lolevel - Foreign pointers @subsection allocate @verbatim [procedure] (allocate BYTES) @end verbatim Returns a pointer to a freshly allocated region of static memory. This procedure could be defined as follows: (define allocate (foreign-lambda c-pointer "malloc" integer)) @node Unit lolevel - Foreign pointers - free, Unit lolevel - Foreign pointers - null-pointer, Unit lolevel - Foreign pointers - allocate, Unit lolevel - Foreign pointers @subsection free @verbatim [procedure] (free POINTER) @end verbatim Frees the memory pointed to by @code{POINTER}. This procedure could be defined as follows: (define free (foreign-lambda c-pointer "free" integer)) @node Unit lolevel - Foreign pointers - null-pointer, Unit lolevel - Foreign pointers - null-pointer?, Unit lolevel - Foreign pointers - free, Unit lolevel - Foreign pointers @subsection null-pointer @verbatim [procedure] (null-pointer) @end verbatim Another way to say @code{(address->pointer 0)}. @node Unit lolevel - Foreign pointers - null-pointer?, Unit lolevel - Foreign pointers - object->pointer, Unit lolevel - Foreign pointers - null-pointer, Unit lolevel - Foreign pointers @subsection null-pointer? @verbatim [procedure] (null-pointer? PTR) @end verbatim Returns @code{#t} if @code{PTR} contains a @code{NULL} pointer, or @code{#f} otherwise. @node Unit lolevel - Foreign pointers - object->pointer, Unit lolevel - Foreign pointers - pointer?, Unit lolevel - Foreign pointers - null-pointer?, Unit lolevel - Foreign pointers @subsection object->pointer @verbatim [procedure] (object->pointer X) @end verbatim Returns a pointer pointing to the Scheme object X, which should be a non-immediate object. Note that data in the garbage collected heap moves during garbage collection. @node Unit lolevel - Foreign pointers - pointer?, Unit lolevel - Foreign pointers - pointer=?, Unit lolevel - Foreign pointers - object->pointer, Unit lolevel - Foreign pointers @subsection pointer? @verbatim [procedure] (pointer? X) @end verbatim Returns @code{#t} if @code{X} is a foreign pointer object, and @code{#f} otherwise. @node Unit lolevel - Foreign pointers - pointer=?, Unit lolevel - Foreign pointers - pointer->address, Unit lolevel - Foreign pointers - pointer?, Unit lolevel - Foreign pointers @subsection pointer=? @verbatim [procedure] (pointer=? PTR1 PTR2) @end verbatim Returns @code{#t} if the pointer-like objects @code{PTR1} and @code{PTR2} point to the same address. @node Unit lolevel - Foreign pointers - pointer->address, Unit lolevel - Foreign pointers - pointer->object, Unit lolevel - Foreign pointers - pointer=?, Unit lolevel - Foreign pointers @subsection pointer->address @verbatim [procedure] (pointer->address PTR) @end verbatim Returns the address, to which the pointer @code{PTR} points. @node Unit lolevel - Foreign pointers - pointer->object, Unit lolevel - Foreign pointers - pointer-offset, Unit lolevel - Foreign pointers - pointer->address, Unit lolevel - Foreign pointers @subsection pointer->object @verbatim [procedure] (pointer->object PTR) @end verbatim Returns the Scheme object pointed to by the pointer @code{PTR}. @node Unit lolevel - Foreign pointers - pointer-offset, Unit lolevel - Foreign pointers - pointer-u8-ref, Unit lolevel - Foreign pointers - pointer->object, Unit lolevel - Foreign pointers @subsection pointer-offset @verbatim [procedure] (pointer-offset PTR N) @end verbatim Returns a new pointer representing the pointer @code{PTR} increased by @code{N}. @node Unit lolevel - Foreign pointers - pointer-u8-ref, Unit lolevel - Foreign pointers - pointer-s8-ref, Unit lolevel - Foreign pointers - pointer-offset, Unit lolevel - Foreign pointers @subsection pointer-u8-ref @verbatim [procedure] (pointer-u8-ref PTR) @end verbatim Returns the unsigned byte at the address designated by @code{PTR}. @node Unit lolevel - Foreign pointers - pointer-s8-ref, Unit lolevel - Foreign pointers - pointer-u16-ref, Unit lolevel - Foreign pointers - pointer-u8-ref, Unit lolevel - Foreign pointers @subsection pointer-s8-ref @verbatim [procedure] (pointer-s8-ref PTR) @end verbatim Returns the signed byte at the address designated by @code{PTR}. @node Unit lolevel - Foreign pointers - pointer-u16-ref, Unit lolevel - Foreign pointers - pointer-s16-ref, Unit lolevel - Foreign pointers - pointer-s8-ref, Unit lolevel - Foreign pointers @subsection pointer-u16-ref @verbatim [procedure] (pointer-u16-ref PTR) @end verbatim Returns the unsigned 16-bit integer at the address designated by @code{PTR}. @node Unit lolevel - Foreign pointers - pointer-s16-ref, Unit lolevel - Foreign pointers - pointer-u32-ref, Unit lolevel - Foreign pointers - pointer-u16-ref, Unit lolevel - Foreign pointers @subsection pointer-s16-ref @verbatim [procedure] (pointer-s16-ref PTR) @end verbatim Returns the signed 16-bit integer at the address designated by @code{PTR}. @node Unit lolevel - Foreign pointers - pointer-u32-ref, Unit lolevel - Foreign pointers - pointer-s32-ref, Unit lolevel - Foreign pointers - pointer-s16-ref, Unit lolevel - Foreign pointers @subsection pointer-u32-ref @verbatim [procedure] (pointer-u32-ref PTR) @end verbatim Returns the unsigned 32-bit integer at the address designated by @code{PTR}. @node Unit lolevel - Foreign pointers - pointer-s32-ref, Unit lolevel - Foreign pointers - pointer-f32-ref, Unit lolevel - Foreign pointers - pointer-u32-ref, Unit lolevel - Foreign pointers @subsection pointer-s32-ref @verbatim [procedure] (pointer-s32-ref PTR) @end verbatim Returns the signed 32-bit integer at the address designated by @code{PTR}. @node Unit lolevel - Foreign pointers - pointer-f32-ref, Unit lolevel - Foreign pointers - pointer-f64-ref, Unit lolevel - Foreign pointers - pointer-s32-ref, Unit lolevel - Foreign pointers @subsection pointer-f32-ref @verbatim [procedure] (pointer-f32-ref PTR) @end verbatim Returns the 32-bit float at the address designated by @code{PTR}. @node Unit lolevel - Foreign pointers - pointer-f64-ref, Unit lolevel - Foreign pointers - pointer-u8-set!, Unit lolevel - Foreign pointers - pointer-f32-ref, Unit lolevel - Foreign pointers @subsection pointer-f64-ref @verbatim [procedure] (pointer-f64-ref PTR) @end verbatim Returns the 64-bit double at the address designated by @code{PTR}. @node Unit lolevel - Foreign pointers - pointer-u8-set!, Unit lolevel - Foreign pointers - pointer-s8-set!, Unit lolevel - Foreign pointers - pointer-f64-ref, Unit lolevel - Foreign pointers @subsection pointer-u8-set! @verbatim [procedure] (pointer-u8-set! PTR N) [procedure] (set! (pointer-u8-ref PTR) N) @end verbatim Stores the unsigned byte @code{N} at the address designated by @code{PTR}. @node Unit lolevel - Foreign pointers - pointer-s8-set!, Unit lolevel - Foreign pointers - pointer-u16-set!, Unit lolevel - Foreign pointers - pointer-u8-set!, Unit lolevel - Foreign pointers @subsection pointer-s8-set! @verbatim [procedure] (pointer-s8-set! PTR N) [procedure] (set! (pointer-s8-ref PTR) N) @end verbatim Stores the signed byte @code{N} at the address designated by @code{PTR}. @node Unit lolevel - Foreign pointers - pointer-u16-set!, Unit lolevel - Foreign pointers - pointer-s16-set!, Unit lolevel - Foreign pointers - pointer-s8-set!, Unit lolevel - Foreign pointers @subsection pointer-u16-set! @verbatim [procedure] (pointer-u16-set! PTR N) [procedure] (set! (pointer-u16-ref PTR) N) @end verbatim Stores the unsigned 16-bit integer @code{N} at the address designated by @code{PTR}. @node Unit lolevel - Foreign pointers - pointer-s16-set!, Unit lolevel - Foreign pointers - pointer-u32-set!, Unit lolevel - Foreign pointers - pointer-u16-set!, Unit lolevel - Foreign pointers @subsection pointer-s16-set! @verbatim [procedure] (pointer-s16-set! PTR N) [procedure] (set! (pointer-s16-ref PTR) N) @end verbatim Stores the signed 16-bit integer @code{N} at the address designated by @code{PTR}. @node Unit lolevel - Foreign pointers - pointer-u32-set!, Unit lolevel - Foreign pointers - pointer-s32-set!, Unit lolevel - Foreign pointers - pointer-s16-set!, Unit lolevel - Foreign pointers @subsection pointer-u32-set! @verbatim [procedure] (pointer-u32-set! PTR N) [procedure] (set! (pointer-u32-ref PTR) N) @end verbatim Stores the unsigned 32-bit integer @code{N} at the address designated by @code{PTR}. @node Unit lolevel - Foreign pointers - pointer-s32-set!, Unit lolevel - Foreign pointers - pointer-f32-set!, Unit lolevel - Foreign pointers - pointer-u32-set!, Unit lolevel - Foreign pointers @subsection pointer-s32-set! @verbatim [procedure] (pointer-s32-set! PTR N) [procedure] (set! (pointer-s32-ref PTR) N) @end verbatim Stores the 32-bit integer @code{N} at the address designated by @code{PTR}. @node Unit lolevel - Foreign pointers - pointer-f32-set!, Unit lolevel - Foreign pointers - pointer-f64-set!, Unit lolevel - Foreign pointers - pointer-s32-set!, Unit lolevel - Foreign pointers @subsection pointer-f32-set! @verbatim [procedure] (pointer-f32-set! PTR N) [procedure] (set! (pointer-f32-ref PTR) N) @end verbatim Stores the 32-bit floating-point number @code{N} at the address designated by @code{PTR}. @node Unit lolevel - Foreign pointers - pointer-f64-set!, Unit lolevel - Foreign pointers - align-to-word, Unit lolevel - Foreign pointers - pointer-f32-set!, Unit lolevel - Foreign pointers @subsection pointer-f64-set! @verbatim [procedure] (pointer-f64-set! PTR N) [procedure] (set! (pointer-f64-ref PTR) N) @end verbatim Stores the 64-bit floating-point number @code{N} at the address designated by @code{PTR}. @node Unit lolevel - Foreign pointers - align-to-word, , Unit lolevel - Foreign pointers - pointer-f64-set!, Unit lolevel - Foreign pointers @subsection align-to-word @verbatim [procedure] (align-to-word PTR-OR-INT) @end verbatim Accepts either a machine pointer or an integer as argument and returns a new pointer or integer aligned to the native word size of the host platform. @node Unit lolevel - Tagged pointers, Unit lolevel - Extending procedures with data, Unit lolevel - Foreign pointers, Unit lolevel @section Tagged pointers @menu * Unit lolevel - Tagged pointers - tag-pointer:: * Unit lolevel - Tagged pointers - tagged-pointer?:: * Unit lolevel - Tagged pointers - pointer-tag:: @end menu @emph{Tagged} pointers are foreign pointer objects with an extra tag object. @node Unit lolevel - Tagged pointers - tag-pointer, Unit lolevel - Tagged pointers - tagged-pointer?, , Unit lolevel - Tagged pointers @subsection tag-pointer @verbatim [procedure] (tag-pointer PTR TAG) @end verbatim Creates a new tagged pointer object from the foreign pointer @code{PTR} with the tag @code{TAG}, which may an arbitrary Scheme object. @node Unit lolevel - Tagged pointers - tagged-pointer?, Unit lolevel - Tagged pointers - pointer-tag, Unit lolevel - Tagged pointers - tag-pointer, Unit lolevel - Tagged pointers @subsection tagged-pointer? @verbatim [procedure] (tagged-pointer? X TAG) @end verbatim Returns @code{#t}, if @code{X} is a tagged pointer object with the tag @code{TAG} (using an @code{eq?} comparison), or @code{#f} otherwise. @node Unit lolevel - Tagged pointers - pointer-tag, , Unit lolevel - Tagged pointers - tagged-pointer?, Unit lolevel - Tagged pointers @subsection pointer-tag @verbatim [procedure] (pointer-tag PTR) @end verbatim If @code{PTR} is a tagged pointer object, its tag is returned. If @code{PTR} is a normal, untagged foreign pointer object @code{#f} is returned. Otherwise an error is signalled. @node Unit lolevel - Extending procedures with data, Unit lolevel - Blobs, Unit lolevel - Tagged pointers, Unit lolevel @section Extending procedures with data @menu * Unit lolevel - Extending procedures with data - extend-procedure:: * Unit lolevel - Extending procedures with data - extended-procedure?:: * Unit lolevel - Extending procedures with data - procedure-data:: * Unit lolevel - Extending procedures with data - set-procedure-data!:: @end menu @node Unit lolevel - Extending procedures with data - extend-procedure, Unit lolevel - Extending procedures with data - extended-procedure?, , Unit lolevel - Extending procedures with data @subsection extend-procedure @verbatim [procedure] (extend-procedure PROCEDURE X) @end verbatim Returns a copy of the procedure @code{PROCEDURE} which contains an additional data slot initialized to @code{X}. If @code{PROCEDURE} is already an extended procedure, then its data slot is changed to contain @code{X} and the same procedure is returned. @node Unit lolevel - Extending procedures with data - extended-procedure?, Unit lolevel - Extending procedures with data - procedure-data, Unit lolevel - Extending procedures with data - extend-procedure, Unit lolevel - Extending procedures with data @subsection extended-procedure? @verbatim [procedure] (extended-procedure? PROCEDURE) @end verbatim Returns @code{#t} if @code{PROCEDURE} is an extended procedure, or @code{#f} otherwise. @node Unit lolevel - Extending procedures with data - procedure-data, Unit lolevel - Extending procedures with data - set-procedure-data!, Unit lolevel - Extending procedures with data - extended-procedure?, Unit lolevel - Extending procedures with data @subsection procedure-data @verbatim [procedure] (procedure-data PROCEDURE) @end verbatim Returns the data object contained in the extended procedure @code{PROCEDURE}, or @code{#f} if it is not an extended procedure. @node Unit lolevel - Extending procedures with data - set-procedure-data!, , Unit lolevel - Extending procedures with data - procedure-data, Unit lolevel - Extending procedures with data @subsection set-procedure-data! @verbatim [procedure] (set-procedure-data! PROCEDURE X) @end verbatim Changes the data object contained in the extended procedure @code{PROCEDURE} to @code{X}. (define foo @verbatim (letrec ((f (lambda () (procedure-data x))) (x #f) ) (set! x (extend-procedure f 123)) x) ) @end verbatim (foo) ==> 123 (set-procedure-data! foo 'hello) (foo) ==> hello @node Unit lolevel - Blobs, Unit lolevel - Data in unmanaged memory, Unit lolevel - Extending procedures with data, Unit lolevel @section Blobs @menu * Unit lolevel - Blobs - blob?:: * Unit lolevel - Blobs - blob-size:: * Unit lolevel - Blobs - blob->string:: * Unit lolevel - Blobs - string->blob:: @end menu "blobs" are collections of unstructured bytes. You can't do much with them, but allow conversion to and from SRFI-4 number vectors. @node Unit lolevel - Blobs - blob?, Unit lolevel - Blobs - blob-size, , Unit lolevel - Blobs @subsection blob? @verbatim [procedure] (blob? X) @end verbatim Returns @code{#t} if @code{X} is a blob object, or @code{#f} otherwise. @node Unit lolevel - Blobs - blob-size, Unit lolevel - Blobs - blob->string, Unit lolevel - Blobs - blob?, Unit lolevel - Blobs @subsection blob-size @verbatim [procedure] (blob-size BLOB) @end verbatim Returns the number of bytes in @code{BLOB}. @node Unit lolevel - Blobs - blob->string, Unit lolevel - Blobs - string->blob, Unit lolevel - Blobs - blob-size, Unit lolevel - Blobs @subsection blob->string @verbatim [procedure] (blob->string BLOB) @end verbatim Returns a string with the contents of @code{BLOB}. @node Unit lolevel - Blobs - string->blob, , Unit lolevel - Blobs - blob->string, Unit lolevel - Blobs @subsection string->blob @verbatim [procedure] (string->blob STRING) @end verbatim Returns a blob with the contents of @code{STRING}. @node Unit lolevel - Data in unmanaged memory, Unit lolevel - Locatives, Unit lolevel - Blobs, Unit lolevel @section Data in unmanaged memory @menu * Unit lolevel - Data in unmanaged memory - object-evict:: * Unit lolevel - Data in unmanaged memory - object-evict-to-location:: * Unit lolevel - Data in unmanaged memory - object-evicted?:: * Unit lolevel - Data in unmanaged memory - object-size:: * Unit lolevel - Data in unmanaged memory - object-release:: * Unit lolevel - Data in unmanaged memory - object-unevict:: @end menu @node Unit lolevel - Data in unmanaged memory - object-evict, Unit lolevel - Data in unmanaged memory - object-evict-to-location, , Unit lolevel - Data in unmanaged memory @subsection object-evict @verbatim [procedure] (object-evict X [ALLOCATOR]) @end verbatim Copies the object @code{X} recursively into the memory pointed to by the foreign pointer object returned by @code{ALLOCATOR}, which should be a procedure of a single argument (the number of bytes to allocate). The freshly copied object is returned. This facility allows moving arbitrary objects into static memory, but care should be taken when mutating evicted data: setting slots in evicted vector-like objects to non-evicted data is not allowed. It @b{is} possible to set characters/bytes in evicted strings or byte-vectors, though. It is advisable @b{not} to evict ports, because they might be mutated by certain file-operations. @code{object-evict} is able to handle circular and shared structures, but evicted symbols are no longer unique: a fresh copy of the symbol is created, so (define x 'foo) (define y (object-evict 'foo)) y ==> foo (eq? x y) ==> #f (define z (object-evict '(bar bar))) (eq? (car z) (cadr z)) ==> #t The @code{ALLOCATOR} defaults to @code{allocate}. @node Unit lolevel - Data in unmanaged memory - object-evict-to-location, Unit lolevel - Data in unmanaged memory - object-evicted?, Unit lolevel - Data in unmanaged memory - object-evict, Unit lolevel - Data in unmanaged memory @subsection object-evict-to-location @verbatim [procedure] (object-evict-to-location X PTR [LIMIT]) @end verbatim As @code{object-evict} but moves the object at the address pointed to by the machine pointer @code{PTR}. If the number of copied bytes exceeds the optional @code{LIMIT} then an error is signalled (specifically a composite condition of types @code{exn} and @code{evict}. The latter provides a @code{limit} property which holds the exceeded limit. Two values are returned: the evicted object and a new pointer pointing to the first free address after the evicted object. @node Unit lolevel - Data in unmanaged memory - object-evicted?, Unit lolevel - Data in unmanaged memory - object-size, Unit lolevel - Data in unmanaged memory - object-evict-to-location, Unit lolevel - Data in unmanaged memory @subsection object-evicted? @verbatim [procedure] (object-evicted? X) @end verbatim Returns @code{#t} if @code{X} is a non-immediate evicted data object, or @code{#f} otherwise. @node Unit lolevel - Data in unmanaged memory - object-size, Unit lolevel - Data in unmanaged memory - object-release, Unit lolevel - Data in unmanaged memory - object-evicted?, Unit lolevel - Data in unmanaged memory @subsection object-size @verbatim [procedure] (object-size X) @end verbatim Returns the number of bytes that would be needed to evict the data object @code{X}. @node Unit lolevel - Data in unmanaged memory - object-release, Unit lolevel - Data in unmanaged memory - object-unevict, Unit lolevel - Data in unmanaged memory - object-size, Unit lolevel - Data in unmanaged memory @subsection object-release @verbatim [procedure] (object-release X [RELEASER]) @end verbatim Frees memory occupied by the evicted object @code{X} recursively. @code{RELEASER} should be a procedure of a single argument (a foreign pointer object to the static memory to be freed) and defaults to @code{free}. @node Unit lolevel - Data in unmanaged memory - object-unevict, , Unit lolevel - Data in unmanaged memory - object-release, Unit lolevel - Data in unmanaged memory @subsection object-unevict @verbatim [procedure] (object-unevict X [FULL]) @end verbatim Copies the object @code{X} and nested objects back into the normal Scheme heap. Symbols are re-interned into the symbol table. Strings and byte-vectors are @b{not} copied, unless @code{FULL} is given and not @code{#f}. @node Unit lolevel - Locatives, Unit lolevel - Accessing toplevel variables, Unit lolevel - Data in unmanaged memory, Unit lolevel @section Locatives @menu * Unit lolevel - Locatives - make-locative:: * Unit lolevel - Locatives - make-weak-locative:: * Unit lolevel - Locatives - locative?:: * Unit lolevel - Locatives - locative-ref:: * Unit lolevel - Locatives - locative-set!:: * Unit lolevel - Locatives - locative->object:: @end menu A @emph{locative} is an object that points to an element of a containing object, much like a @emph{pointer} in low-level, imperative programming languages like @emph{C}. The element can be accessed and changed indirectly, by performing access or change operations on the locative. The container object can be computed by calling the @code{location->object} procedure. Locatives may be passed to foreign procedures that expect pointer arguments. The effect of creating locatives for evicted data (see @code{object-evict}) is undefined. @node Unit lolevel - Locatives - make-locative, Unit lolevel - Locatives - make-weak-locative, , Unit lolevel - Locatives @subsection make-locative @verbatim [procedure] (make-locative EXP [INDEX]) @end verbatim Creates a locative that refers to the element of the non-immediate object @code{EXP} at position @code{INDEX}. @code{EXP} may be a vector, pair, string, byte-vector, SRFI-4 number-vector, or record. @code{INDEX} should be a fixnum. @code{INDEX} defaults to 0. @node Unit lolevel - Locatives - make-weak-locative, Unit lolevel - Locatives - locative?, Unit lolevel - Locatives - make-locative, Unit lolevel - Locatives @subsection make-weak-locative @verbatim [procedure] (make-weak-locative EXP [INDEX]) @end verbatim Creates a @emph{weak} locative. Even though the locative refers to an element of a container object, the container object will still be reclaimed by garbage collection if no other references to it exist. @node Unit lolevel - Locatives - locative?, Unit lolevel - Locatives - locative-ref, Unit lolevel - Locatives - make-weak-locative, Unit lolevel - Locatives @subsection locative? @verbatim [procedure] (locative? X) @end verbatim Returns @code{#t} if @code{X} is a locative, or @code{#f} otherwise. @node Unit lolevel - Locatives - locative-ref, Unit lolevel - Locatives - locative-set!, Unit lolevel - Locatives - locative?, Unit lolevel - Locatives @subsection locative-ref @verbatim [procedure] (locative-ref LOC) @end verbatim Returns the element to which the locative @code{LOC} refers. If the containing object has been reclaimed by garbage collection, an error is signalled. @node Unit lolevel - Locatives - locative-set!, Unit lolevel - Locatives - locative->object, Unit lolevel - Locatives - locative-ref, Unit lolevel - Locatives @subsection locative-set! @verbatim [procedure] (locative-set! LOC X) [procedure] (set! (locative-ref LOC) X) @end verbatim Changes the element to which the locative @code{LOC} refers to @code{X}. If the containing object has been reclaimed by garbage collection, an error is signalled. @node Unit lolevel - Locatives - locative->object, , Unit lolevel - Locatives - locative-set!, Unit lolevel - Locatives @subsection locative->object @verbatim [procedure] (locative->object LOC) @end verbatim Returns the object that contains the element referred to by @code{LOC} or @code{#f} if the container has been reclaimed by garbage collection. @node Unit lolevel - Accessing toplevel variables, Unit lolevel - Low-level data access, Unit lolevel - Locatives, Unit lolevel @section Accessing toplevel variables @menu * Unit lolevel - Accessing toplevel variables - global-bound?:: * Unit lolevel - Accessing toplevel variables - global-ref:: * Unit lolevel - Accessing toplevel variables - global-set!:: @end menu @node Unit lolevel - Accessing toplevel variables - global-bound?, Unit lolevel - Accessing toplevel variables - global-ref, , Unit lolevel - Accessing toplevel variables @subsection global-bound? @verbatim [procedure] (global-bound? SYMBOL) @end verbatim Returns @code{#t}, if the global (@emph{toplevel}) variable with the name @code{SYMBOL} is bound to a value, or @code{#f} otherwise. @node Unit lolevel - Accessing toplevel variables - global-ref, Unit lolevel - Accessing toplevel variables - global-set!, Unit lolevel - Accessing toplevel variables - global-bound?, Unit lolevel - Accessing toplevel variables @subsection global-ref @verbatim [procedure] (global-ref SYMBOL) @end verbatim Returns the value of the global variable @code{SYMBOL}. If no variable under that name is bound, an error is signalled. Note that it is not possible to access a toplevel binding with @code{global-ref} or @code{global-set!} if it has been hidden in compiled code via @code{(declare (hide ...))}, or if the code has been compiled in @code{block} mode. @node Unit lolevel - Accessing toplevel variables - global-set!, , Unit lolevel - Accessing toplevel variables - global-ref, Unit lolevel - Accessing toplevel variables @subsection global-set! @verbatim [procedure] (global-set! SYMBOL X) [procedure] (set! (global-ref SYMBOL) X) @end verbatim Sets the global variable named @code{SYMBOL} to the value @code{X}. @node Unit lolevel - Low-level data access, Unit lolevel - Procedure-call- and variable reference hooks, Unit lolevel - Accessing toplevel variables, Unit lolevel @section Low-level data access @menu * Unit lolevel - Low-level data access - block-ref:: * Unit lolevel - Low-level data access - block-set!:: * Unit lolevel - Low-level data access - object-copy:: * Unit lolevel - Low-level data access - make-record-instance:: * Unit lolevel - Low-level data access - move-memory!:: * Unit lolevel - Low-level data access - number-of-bytes:: * Unit lolevel - Low-level data access - number-of-slots:: * Unit lolevel - Low-level data access - record-instance?:: * Unit lolevel - Low-level data access - record->vector:: @end menu @node Unit lolevel - Low-level data access - block-ref, Unit lolevel - Low-level data access - block-set!, , Unit lolevel - Low-level data access @subsection block-ref @verbatim [procedure] (block-ref BLOCK INDEX) @end verbatim Returns the contents of the @code{INDEX}th slot of the object @code{BLOCK}. @code{BLOCK} may be a vector, record structure, pair or symbol. @node Unit lolevel - Low-level data access - block-set!, Unit lolevel - Low-level data access - object-copy, Unit lolevel - Low-level data access - block-ref, Unit lolevel - Low-level data access @subsection block-set! @verbatim [procedure] (block-set! BLOCK INDEX X) [procedure] (set! (block-ref BLOCK INDEX) X) @end verbatim Sets the contents of the @code{INDEX}th slot of the object @code{BLOCK} to the value of @code{X}. @code{BLOCK} may be a vector, record structure, pair or symbol. @node Unit lolevel - Low-level data access - object-copy, Unit lolevel - Low-level data access - make-record-instance, Unit lolevel - Low-level data access - block-set!, Unit lolevel - Low-level data access @subsection object-copy @verbatim [procedure] (object-copy X) @end verbatim Copies @code{X} recursively and returns the fresh copy. Objects allocated in static memory are copied back into garbage collected storage. @node Unit lolevel - Low-level data access - make-record-instance, Unit lolevel - Low-level data access - move-memory!, Unit lolevel - Low-level data access - object-copy, Unit lolevel - Low-level data access @subsection make-record-instance @verbatim [procedure] (make-record-instance SYMBOL ARG1 ...) @end verbatim Returns a new instance of the record type @code{SYMBOL}, with its slots initialized to @code{ARG1 ...}. To illustrate: (define-record point x y) expands into something quite similar to: (begin @verbatim (define (make-point x y) (make-record-instance 'point x y) ) (define (point? x) (and (record-instance? x) (eq? 'point (block-ref x 0)) ) ) (define (point-x p) (block-ref p 1)) (define (point-x-set! p x) (block-set! p 1 x)) (define (point-y p) (block-ref p 2)) (define (point-y-set! p y) (block-set! p 1 y)) ) @end verbatim @node Unit lolevel - Low-level data access - move-memory!, Unit lolevel - Low-level data access - number-of-bytes, Unit lolevel - Low-level data access - make-record-instance, Unit lolevel - Low-level data access @subsection move-memory! @verbatim [procedure] (move-memory! FROM TO [BYTES [FROM-OFFSET [TO-OFFSET]]) @end verbatim Copies @code{BYTES} bytes of memory from @code{FROM} to @code{TO}. @code{FROM} and @code{TO} may be strings, primitive byte-vectors, SRFI-4 byte-vectors (see: @@ref@{Unit srfi-4@}), memory mapped files, foreign pointers (as obtained from a call to @code{foreign-lambda}, for example) or locatives. if @code{BYTES} is not given and the size of the source or destination operand is known then the maximal number of bytes will be copied. Moving memory to the storage returned by locatives will cause havoc, if the locative refers to containers of non-immediate data, like vectors or pairs. The additional fourth and fifth argument specify starting offsets (in bytes) for the source and destination arguments. @node Unit lolevel - Low-level data access - number-of-bytes, Unit lolevel - Low-level data access - number-of-slots, Unit lolevel - Low-level data access - move-memory!, Unit lolevel - Low-level data access @subsection number-of-bytes @verbatim [procedure] (number-of-bytes BLOCK) @end verbatim Returns the number of bytes that the object @code{BLOCK} contains. @code{BLOCK} may be any non-immediate value. @node Unit lolevel - Low-level data access - number-of-slots, Unit lolevel - Low-level data access - record-instance?, Unit lolevel - Low-level data access - number-of-bytes, Unit lolevel - Low-level data access @subsection number-of-slots @verbatim [procedure] (number-of-slots BLOCK) @end verbatim Returns the number of slots that the object @code{BLOCK} contains. @code{BLOCK} may be a vector, record structure, pair or symbol. @node Unit lolevel - Low-level data access - record-instance?, Unit lolevel - Low-level data access - record->vector, Unit lolevel - Low-level data access - number-of-slots, Unit lolevel - Low-level data access @subsection record-instance? @verbatim [procedure] (record-instance? X) @end verbatim Returns @code{#t} if @code{X} is an instance of a record type. See also: @code{make-record-instance}. @node Unit lolevel - Low-level data access - record->vector, , Unit lolevel - Low-level data access - record-instance?, Unit lolevel - Low-level data access @subsection record->vector @verbatim [procedure] (record->vector BLOCK) @end verbatim Returns a new vector with the type and the elements of the record @code{BLOCK}. @node Unit lolevel - Procedure-call- and variable reference hooks, Unit lolevel - Magic, Unit lolevel - Low-level data access, Unit lolevel @section Procedure-call- and variable reference hooks @menu * Unit lolevel - Procedure-call- and variable reference hooks - set-invalid-procedure-call-handler!:: * Unit lolevel - Procedure-call- and variable reference hooks - unbound-variable-value:: @end menu @node Unit lolevel - Procedure-call- and variable reference hooks - set-invalid-procedure-call-handler!, Unit lolevel - Procedure-call- and variable reference hooks - unbound-variable-value, , Unit lolevel - Procedure-call- and variable reference hooks @subsection set-invalid-procedure-call-handler! @verbatim [procedure] (set-invalid-procedure-call-handler! PROC) @end verbatim Sets an internal hook that is invoked when a call to an object other than a procedure is executed at runtime. The procedure @code{PROC} will in that case be called with two arguments: the object being called and a list of the passed arguments. ;;; Access sequence-elements as in ARC: (set-invalid-procedure-call-handler! @verbatim (lambda (proc args) (cond [(string? proc) (apply string-ref proc args)] [(vector? proc) (apply vector-ref proc args)] [else (error "call of non-procedure" proc)] ) ) ) @end verbatim ("hello" 4) ==> #\o This facility does not work in code compiled with the @emph{unsafe} setting. @node Unit lolevel - Procedure-call- and variable reference hooks - unbound-variable-value, , Unit lolevel - Procedure-call- and variable reference hooks - set-invalid-procedure-call-handler!, Unit lolevel - Procedure-call- and variable reference hooks @subsection unbound-variable-value @verbatim [procedure] (unbound-variable-value [X]) @end verbatim Defines the value that is returned for unbound variables. Normally an error is signalled, use this procedure to override the check and return @code{X} instead. To set the default behavior (of signalling an error), call @code{unbound-variable-value} with no arguments. This facility does not work in code compiled with the @emph{unsafe} setting. @node Unit lolevel - Magic, , Unit lolevel - Procedure-call- and variable reference hooks, Unit lolevel @section Magic @menu * Unit lolevel - Magic - object-become!:: * Unit lolevel - Magic - mutate-procedure:: @end menu @node Unit lolevel - Magic - object-become!, Unit lolevel - Magic - mutate-procedure, , Unit lolevel - Magic @subsection object-become! @verbatim [procedure] (object-become! ALIST) @end verbatim Changes the identity of the value of the car of each pair in @code{ALIST} to the value of the cdr. Both values may not be immediate (i.e. exact integers, characters, booleans or the empty list). (define x "i used to be a string") (define y '#(and now i am a vector)) (object-become! (list (cons x y))) x ==> #(and now i am a vector) y ==> #(and now i am a vector) (eq? x y) ==> #t Note: this operation invokes a major garbage collection. The effect of using @code{object-become!} on evicted data (see @code{object-evict}) is undefined. @node Unit lolevel - Magic - mutate-procedure, , Unit lolevel - Magic - object-become!, Unit lolevel - Magic @subsection mutate-procedure @verbatim [procedure] (mutate-procedure OLD PROC) @end verbatim Replaces the procedure @code{OLD} with the result of calling the one-argument procedure @code{PROC}. @code{PROC} will receive a copy of @code{OLD} that will be identical in behaviour to the result of @code{PROC}: ;;; Replace arbitrary procedure with tracing one: (mutate-procedure my-proc @verbatim (lambda (new) (lambda args (printf "~s called with arguments: ~s~%" new args) (apply new args) ) ) ) @end verbatim Previous: @ref{Unit tcp, Unit tcp} Next: @ref{Interface to external functions and variables, Interface to external functions and variables} @node Interface to external functions and variables, Accessing external objects, Unit lolevel, Top @chapter Interface to external functions and variables @itemize @item @ref{Accessing external objects, Accessing external objects} @item @ref{Foreign type specifiers, Foreign type specifiers} @item @ref{Embedding, Embedding} @item @ref{Callbacks, Callbacks} @item @ref{Locations, Locations} @item @ref{Other support procedures, Other support procedures} @item @ref{C interface, C interface} @end itemize Previous: @ref{Supported language, Supported language} Next: @ref{chicken-setup, chicken-setup} @node Accessing external objects, Foreign type specifiers, Interface to external functions and variables, Top @chapter Accessing external objects @menu * Accessing external objects - foreign-code:: * Accessing external objects - foreign-value:: * Accessing external objects - foreign-declare:: * Accessing external objects - define-foreign-type:: * Accessing external objects - define-foreign-variable:: * Accessing external objects - define-foreign-record:: * Accessing external objects - define-foreign-enum:: * Accessing external objects - foreign-lambda:: * Accessing external objects - foreign-lambda*:: * Accessing external objects - foreign-safe-lambda:: * Accessing external objects - foreign-safe-lambda*:: * Accessing external objects - foreign-primitive:: @end menu @node Accessing external objects - foreign-code, Accessing external objects - foreign-value, , Accessing external objects @section foreign-code @verbatim [syntax] (foreign-code STRING ...) @end verbatim Executes the embedded C/C++ code @code{STRING ...}, which should be a sequence of C statements, which are executed and return an unspecified result. (foreign-code "doSomeInitStuff();") => # Code wrapped inside @code{foreign-code} may not invoke callbacks into Scheme. @node Accessing external objects - foreign-value, Accessing external objects - foreign-declare, Accessing external objects - foreign-code, Accessing external objects @section foreign-value @verbatim [syntax] (foreign-value STRING TYPE) @end verbatim Evaluates the embedded C/C++ expression @code{STRING}, returning a value of type given in the foreign-type specifier @code{TYPE}. (print (foreign-value "my_version_string" c-string)) @node Accessing external objects - foreign-declare, Accessing external objects - define-foreign-type, Accessing external objects - foreign-value, Accessing external objects @section foreign-declare @verbatim [syntax] (foreign-declare STRING ...) @end verbatim Include given strings verbatim into header of generated file. @node Accessing external objects - define-foreign-type, Accessing external objects - define-foreign-variable, Accessing external objects - foreign-declare, Accessing external objects @section define-foreign-type @verbatim [syntax] (define-foreign-type NAME TYPE [ARGCONVERT [RETCONVERT]]) @end verbatim Defines an alias for @code{TYPE} with the name @code{NAME} (a symbol). @code{TYPE} may be a type-specifier or a string naming a C type. The namespace of foreign type specifiers is separate from the normal Scheme namespace. The optional arguments @code{ARGCONVERT} and @code{RETCONVERT} should evaluate to procedures that map argument- and result-values to a value that can be transformed to @code{TYPE}: (define-foreign-type char-vector @verbatim nonnull-c-string (compose list->string vector->list) (compose list->vector string->list) ) @end verbatim (define strlen @verbatim (foreign-lambda int "strlen" char-vector) ) @end verbatim (strlen '#(#\a #\b #\c)) ==> 3 (define memset @verbatim (foreign-lambda char-vector "memset" char-vector char int) ) @end verbatim (memset '#(#_ #_ #_) #\X 3) ==> #(#\X #\X #\X) Foreign type-definitions are only visible in the compilation-unit in which they are defined, so use @code{include} to use the same definitions in multiple files. @node Accessing external objects - define-foreign-variable, Accessing external objects - define-foreign-record, Accessing external objects - define-foreign-type, Accessing external objects @section define-foreign-variable @verbatim [syntax] (define-foreign-variable NAME TYPE [STRING]) @end verbatim Defines a foreign variable of name @code{NAME} (a symbol). @code{STRING} should be the real name of a foreign variable or parameterless macro. If @code{STRING} is not given, then the variable name @code{NAME} will be converted to a string and used instead. All references and assignments (via @code{set!}) are modified to correctly convert values between Scheme and C representation. This foreign variable can only be accessed in the current compilation unit, but the name can be lexically shadowed. Note that @code{STRING} can name an arbitrary C expression. If no assignments are performed, then @code{STRING} doesn't even have to specify an lvalue. @enumerate @item > enum @{ abc=3, def, ghi @}; <# @end enumerate (define-macro (define-simple-foreign-enum . items) @verbatim `(begin ,@@(map (match-lambda [(name realname) `(define-foreign-variable ,name int ,realname)] [name `(define-foreign-variable ,name int)] ) items) ) ) @end verbatim (define-simple-foreign-enum abc def ghi) ghi ==> 5 @node Accessing external objects - define-foreign-record, Accessing external objects - define-foreign-enum, Accessing external objects - define-foreign-variable, Accessing external objects @section define-foreign-record @menu * Accessing external objects - define-foreign-record - TYPENAME-SLOTNAME:: * Accessing external objects - define-foreign-record - TYPENAME-SLOTNAME-set!:: * Accessing external objects - define-foreign-record - constructor:: * Accessing external objects - define-foreign-record - destructor:: * Accessing external objects - define-foreign-record - rename:: @end menu @verbatim [syntax] (define-foreign-record NAME [DECL ...] SLOT ...) @end verbatim Defines accessor procedures for a C structure definition. @code{NAME} should either be a symbol or a list of the form @code{(TYPENAME FOREIGNNAME)}. If @code{NAME} is a symbol, then a C declaration will be generated that defines a C struct named @code{struct NAME}. If @code{NAME} is a list, then no struct declaration will be generated and @code{FOREIGNNAME} should name an existing C record type. A foreign-type specifier named @code{NAME} (or @code{TYPENAME}) will be defined as a pointer to the given C structure. A @code{SLOT} definition should be a list of one of the following forms: @verbatim (TYPE SLOTNAME) @end verbatim or @verbatim (TYPE SLOTNAME SIZE) @end verbatim The latter form defines an array of @code{SIZE} elements of the type @code{TYPE} embedded in the structure. For every slot, the following accessor procedures will be generated: @node Accessing external objects - define-foreign-record - TYPENAME-SLOTNAME, Accessing external objects - define-foreign-record - TYPENAME-SLOTNAME-set!, , Accessing external objects - define-foreign-record @subsection TYPENAME-SLOTNAME @verbatim (TYPENAME-SLOTNAME FOREIGN-RECORD-POINTER [INDEX]) @end verbatim A procedure of one argument (a pointer to a C structure), that returns the slot value of the slot @code{SLOTNAME}. If a @code{SIZE} has been given in the slot definition, then an additional argument @code{INDEX} is required that specifies the index of an array-element. @node Accessing external objects - define-foreign-record - TYPENAME-SLOTNAME-set!, Accessing external objects - define-foreign-record - constructor, Accessing external objects - define-foreign-record - TYPENAME-SLOTNAME, Accessing external objects - define-foreign-record @subsection TYPENAME-SLOTNAME-set! @verbatim (TYPENAME-SLOTNAME-set! FOREIGN-RECORD-POINTER [INXDEX] VALUE) @end verbatim A procedure of two arguments (a pointer to a C structure) and a value, that sets the slot value of the slot @code{SLOTNAME} in the structure. If a @code{SIZE} has been given in the slot definition, then an additional argument @code{INDEX} is required for the array index. If a slot type is of the form @code{(const ...)}, then no setter procedure will be generated. Slots of the types @code{(struct ...)} or @code{(union ...)} are accessed as pointers to the embedded struct (or union) and no setter will be generated. Additionally, special record-declarations (@code{DECL ...}) may be given, where each declaration consists of a list of the form @code{(KEYWORD ARGUMENT ...)}. The available declarations are: @node Accessing external objects - define-foreign-record - constructor, Accessing external objects - define-foreign-record - destructor, Accessing external objects - define-foreign-record - TYPENAME-SLOTNAME-set!, Accessing external objects - define-foreign-record @subsection constructor @verbatim (constructor: NAME) @end verbatim Generate a constructor-procedure with no arguments that has the name @code{NAME} (a symbol) that returns a pointer to a structure of this type. The storage will be allocated with @code{malloc(3)}. @node Accessing external objects - define-foreign-record - destructor, Accessing external objects - define-foreign-record - rename, Accessing external objects - define-foreign-record - constructor, Accessing external objects - define-foreign-record @subsection destructor @verbatim (destructor: NAME) @end verbatim Generate a destructor function with the name @code{NAME} that takes a pointer to a structure of this type as its single argument and releases the storage with @code{free(3)}. If the argument is @code{#f}, the destructor procedure does nothing. @node Accessing external objects - define-foreign-record - rename, , Accessing external objects - define-foreign-record - destructor, Accessing external objects - define-foreign-record @subsection rename @verbatim (rename: EXPRESSION) @end verbatim Evaluates @code{EXPRESSION} at compile-/macro-expansion-time and applies the result, which should be a procedure, to the string-representation of the name of each accessor-procedure generated. Another (or the same) string should be returned, which in turn is taken as the actual name of the accessor. An example: (require-for-syntax 'srfi-13) (define-foreign-record Some_Struct @verbatim (rename: (compose string-downcase (cut string-translate <> "_" "-"))) (constructor: make-some-struct) (destructor: free-some-struct) (int xCoord) (int yCoord) ) @end verbatim will generate the following procedures: (make-some-struct) --> C-POINTER (free-some-struct C-POINTER) (some-struct-xcoord C-POINTER) --> NUMBER (some-struct-ycoord C-POINTER) --> NUMBER (some-struct-xcoord-set! C-POINTER NUMBER) (some-struct-ycoord-set! C-POINTER NUMBER) @node Accessing external objects - define-foreign-enum, Accessing external objects - foreign-lambda, Accessing external objects - define-foreign-record, Accessing external objects @section define-foreign-enum @verbatim [syntax] (define-foreign-enum TYPENAME ITEM ...) @end verbatim Defines a foreign type (as with @code{define-foreign-type}) that maps the elements of a C/C++ enum (or a enum-like list of constants) to and from a set of symbols. @code{TYPENAME} names a foreign type that converts a symbol argument from the set @code{ITEM ...} into the appropriate enum value when passed as an argument to a foreign function. A list of symbols passed as an argument will be combined using @code{bitwise-ior}. An empty list will be passed as 0 (zero). Results of the enum type are automatically converted into a symbol (note that combinations are not supported in this case). @code{TYPENAME} may alternatively be a list of the form @code{(SCHEMENAME REALTYPE)} - in this case @code{REALTYPE} designates the native type used. The default native type is @code{"TYPENAME"}. Additionally two procedures are generated named @code{SCHEMENAME->number} and @code{number->SCHEMENAME} which take one argument and convert a symbol (or a list of symbols) into its numeric value and vice versa. Here a heavily contrived example: @enumerate @item > enum foo @{ a_foo = 4, b_foo, c_foo @}; enum foo bar(enum foo x) @{ printf("%d\n", x); return b_foo; @} <# @end enumerate (define-foreign-enum (foo (enum "foo")) a_foo b_foo (c c_foo)) (define bar (foreign-lambda foo bar foo)) (pp (bar '())) (pp (bar 'a_foo)) (pp (bar '(b_foo c))) @node Accessing external objects - foreign-lambda, Accessing external objects - foreign-lambda*, Accessing external objects - define-foreign-enum, Accessing external objects @section foreign-lambda @verbatim [syntax] (foreign-lambda RETURNTYPE NAME ARGTYPE ...) @end verbatim Represents a binding to an external routine. This form can be used in the position of an ordinary @code{lambda} expression. @code{NAME} specifies the name of the external procedure and should be a string or a symbol. @node Accessing external objects - foreign-lambda*, Accessing external objects - foreign-safe-lambda, Accessing external objects - foreign-lambda, Accessing external objects @section foreign-lambda* @verbatim [syntax] (foreign-lambda* RETURNTYPE ((ARGTYPE VARIABLE) ...) STRING ...) @end verbatim Similar to @code{foreign-lambda}, but instead of generating code to call an external function, the body of the C procedure is directly given in @code{STRING ...}: (define my-strlen @verbatim (foreign-lambda* int ((c-string str)) "int n = 0; while(*(str++)) ++n; C_return(n);") ) @end verbatim (my-strlen "one two three") ==> 13 For obscure technical reasons you should use the @code{C_return} macro instead of the normal @code{return} statement to return a result from the foreign lambda body as some cleanup code has to be run before execution commences in the calling code. @node Accessing external objects - foreign-safe-lambda, Accessing external objects - foreign-safe-lambda*, Accessing external objects - foreign-lambda*, Accessing external objects @section foreign-safe-lambda @verbatim [syntax] (foreign-safe-lambda RETURNTYPE NAME ARGTYPE ...) @end verbatim This is similar to @code{foreign-lambda}, but also allows the called function to call Scheme functions and allocate Scheme data-objects. See @ref{Callbacks, Callbacks}. @node Accessing external objects - foreign-safe-lambda*, Accessing external objects - foreign-primitive, Accessing external objects - foreign-safe-lambda, Accessing external objects @section foreign-safe-lambda* @verbatim [syntax] (foreign-safe-lambda* RETURNTYPE ((ARGTYPE VARIABLE)...) STRING ...) @end verbatim This is similar to @code{foreign-lambda*}, but also allows the called function to call Scheme functions and allocate Scheme data-objects. See @ref{Callbacks, Callbacks}. @node Accessing external objects - foreign-primitive, , Accessing external objects - foreign-safe-lambda*, Accessing external objects @section foreign-primitive @verbatim [syntax] (foreign-primitive [RETURNTYPE] ((ARGTYPE VARIABLE) ...) STRING ...) @end verbatim This is also similar to @code{foreign-lambda*} but the code will be executed in a @emph{primitive} CPS context, which means it will not actually return, but call it's continuation on exit. This means that code inside this form may allocate Scheme data on the C stack (the @emph{nursery}) with @code{C_alloc} (see below). If the @code{RETURNTYPE} is omitted it defaults to @code{void}. You can return multiple values inside the body of the @code{foreign-primitive} form by calling this C function: C_values(N + 2, C_SCHEME_UNDEFINED, C_k, X1, ...) where @code{N} is the number of values to be returned, and @code{X1, ...} are the results, which should be Scheme data objects. When returning multiple values, the return-type should be omitted. Previous: @ref{Interface to external functions and variables, Interface to external functions and variables} Next: @ref{Foreign type specifiers, Foreign type specifiers} @node Foreign type specifiers, Embedding, Accessing external objects, Top @chapter Foreign type specifiers @menu * Foreign type specifiers - scheme-object:: * Foreign type specifiers - bool:: * Foreign type specifiers - byte unsigned-byte:: * Foreign type specifiers - char unsigned-char:: * Foreign type specifiers - short unsigned-short:: * Foreign type specifiers - int unsigned-int int32 unsigned-int32:: * Foreign type specifiers - integer unsigned-integer integer32 unsigned-integer32 integer64:: * Foreign type specifiers - long unsigned-long:: * Foreign type specifiers - float double:: * Foreign type specifiers - number:: * Foreign type specifiers - symbol:: * Foreign type specifiers - scheme-pointer:: * Foreign type specifiers - nonnull-scheme-pointer:: * Foreign type specifiers - c-pointer:: * Foreign type specifiers - nonnull-c-pointer:: * Foreign type specifiers - scheme-or-c-pointer:: * Foreign type specifiers - [nonnull-] blob:: * Foreign type specifiers - [nonnull-] u8vector [nonnull-] u16vector [nonnull-] u32vector [nonnull-] s8vector [nonnull-] s16vector [nonnull-] s32vector [nonnull-] f32vector [nonnull-] f64vector:: * Foreign type specifiers - c-string:: * Foreign type specifiers - nonnull-c-string:: * Foreign type specifiers - [nonnull-] c-string*:: * Foreign type specifiers - [nonnull-] unsigned-c-string[*]:: * Foreign type specifiers - c-string-list:: * Foreign type specifiers - c-string-list*:: * Foreign type specifiers - void:: * Foreign type specifiers - (const TYPE):: * Foreign type specifiers - (enum NAME):: * Foreign type specifiers - (pointer TYPE) (c-pointer TYPE):: * Foreign type specifiers - (nonnull-pointer TYPE) (nonnull-c-pointer TYPE):: * Foreign type specifiers - (ref TYPE):: * Foreign type specifiers - (struct NAME):: * Foreign type specifiers - (template TYPE ARGTYPE ...):: * Foreign type specifiers - (union NAME):: * Foreign type specifiers - (instance CNAME SCHEMECLASS):: * Foreign type specifiers - (instance-ref CNAME SCHEMECLASS):: * Foreign type specifiers - (function RESULTTYPE (ARGUMENTTYPE1 ... [...]) [CALLCONV]):: * Foreign type specifiers - Mappings:: @end menu Here is a list of valid foreign type specifiers: @node Foreign type specifiers - scheme-object, Foreign type specifiers - bool, , Foreign type specifiers @section scheme-object An arbitrary Scheme data object (immediate or non-immediate). @node Foreign type specifiers - bool, Foreign type specifiers - byte unsigned-byte, Foreign type specifiers - scheme-object, Foreign type specifiers @section bool As argument: any value (@code{#f} is false, anything else is true). As result: anything different from 0 and the @code{NULL}-pointer is @code{#t}. @node Foreign type specifiers - byte unsigned-byte, Foreign type specifiers - char unsigned-char, Foreign type specifiers - bool, Foreign type specifiers @section byte unsigned-byte A byte. @node Foreign type specifiers - char unsigned-char, Foreign type specifiers - short unsigned-short, Foreign type specifiers - byte unsigned-byte, Foreign type specifiers @section char unsigned-char A character. @node Foreign type specifiers - short unsigned-short, Foreign type specifiers - int unsigned-int int32 unsigned-int32, Foreign type specifiers - char unsigned-char, Foreign type specifiers @section short unsigned-short A short integer number. @node Foreign type specifiers - int unsigned-int int32 unsigned-int32, Foreign type specifiers - integer unsigned-integer integer32 unsigned-integer32 integer64, Foreign type specifiers - short unsigned-short, Foreign type specifiers @section int unsigned-int int32 unsigned-int32 An small integer number in fixnum range (at least 30 bit). @node Foreign type specifiers - integer unsigned-integer integer32 unsigned-integer32 integer64, Foreign type specifiers - long unsigned-long, Foreign type specifiers - int unsigned-int int32 unsigned-int32, Foreign type specifiers @section integer unsigned-integer integer32 unsigned-integer32 integer64 Either a fixnum or a flonum in the range of a (unsigned) machine @emph{int} or with 32/64 bit width. @node Foreign type specifiers - long unsigned-long, Foreign type specifiers - float double, Foreign type specifiers - integer unsigned-integer integer32 unsigned-integer32 integer64, Foreign type specifiers @section long unsigned-long Either a fixnum or a flonum in the range of a (unsigned) machine @emph{long} or with 32 bit width. @node Foreign type specifiers - float double, Foreign type specifiers - number, Foreign type specifiers - long unsigned-long, Foreign type specifiers @section float double A floating-point number. If an exact integer is passed as an argument, then it is automatically converted to a float. @node Foreign type specifiers - number, Foreign type specifiers - symbol, Foreign type specifiers - float double, Foreign type specifiers @section number A floating-point number. Similar to @code{double}, but when used as a result type, then either an exact integer or a floating-point number is returned, depending on whether the result fits into an exact integer or not. @node Foreign type specifiers - symbol, Foreign type specifiers - scheme-pointer, Foreign type specifiers - number, Foreign type specifiers @section symbol A symbol, which will be passed to foreign code as a zero-terminated string. When declared as the result of foreign code, the result should be a string and a symbol with the same name will be interned in the symbol table (and returned to the caller). @node Foreign type specifiers - scheme-pointer, Foreign type specifiers - nonnull-scheme-pointer, Foreign type specifiers - symbol, Foreign type specifiers @section scheme-pointer An untyped pointer to the contents of a non-immediate Scheme object (not allowed as return type). The value @code{#f} is also allowed and is passed as a @code{NULL} pointer. Don't confuse this type with @code{(pointer ...)} which means something different (a machine-pointer object). @node Foreign type specifiers - nonnull-scheme-pointer, Foreign type specifiers - c-pointer, Foreign type specifiers - scheme-pointer, Foreign type specifiers @section nonnull-scheme-pointer As @code{pointer}, but guaranteed not to be @code{#f}. Don't confuse this type with @code{(nonnull-pointer ...)} which means something different (a machine-pointer object). @node Foreign type specifiers - c-pointer, Foreign type specifiers - nonnull-c-pointer, Foreign type specifiers - nonnull-scheme-pointer, Foreign type specifiers @section c-pointer An untyped operating-system pointer or a locative. The value @code{#f} is also allowed and is passed as a @code{NULL} pointer. If uses as the type of a return value, a @code{NULL} pointer will be returned as @code{#f}. @node Foreign type specifiers - nonnull-c-pointer, Foreign type specifiers - scheme-or-c-pointer, Foreign type specifiers - c-pointer, Foreign type specifiers @section nonnull-c-pointer As @code{c-pointer}, but guaranteed not to be @code{#f/NULL}. @node Foreign type specifiers - scheme-or-c-pointer, Foreign type specifiers - [nonnull-] blob, Foreign type specifiers - nonnull-c-pointer, Foreign type specifiers @section scheme-or-c-pointer An untyped pointer. If the argument is a machine-pointer object, the wrapped C pointer will be passed. If it is any other object, then this type is treated as @code{scheme-pointer}. Not allowed as a result type. @node Foreign type specifiers - [nonnull-] blob, Foreign type specifiers - [nonnull-] u8vector [nonnull-] u16vector [nonnull-] u32vector [nonnull-] s8vector [nonnull-] s16vector [nonnull-] s32vector [nonnull-] f32vector [nonnull-] f64vector, Foreign type specifiers - scheme-or-c-pointer, Foreign type specifiers @section [nonnull-] blob A blob object, passed as a pointer to its contents. Arguments of type @code{blob} may optionally be @code{#f}, which is passed as a NULL pointer. This is not allowed as a return type. @node Foreign type specifiers - [nonnull-] u8vector [nonnull-] u16vector [nonnull-] u32vector [nonnull-] s8vector [nonnull-] s16vector [nonnull-] s32vector [nonnull-] f32vector [nonnull-] f64vector, Foreign type specifiers - c-string, Foreign type specifiers - [nonnull-] blob, Foreign type specifiers @section [nonnull-] u8vector [nonnull-] u16vector [nonnull-] u32vector [nonnull-] s8vector [nonnull-] s16vector [nonnull-] s32vector [nonnull-] f32vector [nonnull-] f64vector A SRFI-4 number-vector object, passed as a pointer to its contents. These type specifiers are not allowed as return types. @node Foreign type specifiers - c-string, Foreign type specifiers - nonnull-c-string, Foreign type specifiers - [nonnull-] u8vector [nonnull-] u16vector [nonnull-] u32vector [nonnull-] s8vector [nonnull-] s16vector [nonnull-] s32vector [nonnull-] f32vector [nonnull-] f64vector, Foreign type specifiers @section c-string A C string (zero-terminated). The value @code{#f} is also allowed and is passed as a @code{NULL} pointer. If uses as the type of a return value, a @code{NULL} pointer will be returned as @code{#f}. Note that the string is copied (with a zero-byte appended) when passed as an argument to a foreign function. Also a return value of this type is copied into garbage collected memory. @node Foreign type specifiers - nonnull-c-string, Foreign type specifiers - [nonnull-] c-string*, Foreign type specifiers - c-string, Foreign type specifiers @section nonnull-c-string As @code{c-string}, but guaranteed not to be @code{#f/NULL}. @node Foreign type specifiers - [nonnull-] c-string*, Foreign type specifiers - [nonnull-] unsigned-c-string[*], Foreign type specifiers - nonnull-c-string, Foreign type specifiers @section [nonnull-] c-string* Similar to @code{[nonnull-]c-string}, but if used as a result-type, the pointer returned by the foreign code will be freed (using the C-libraries @code{free(1)}) after copying. This type specifier is not valid as a result type for callbacks defined with @code{define-external}. @node Foreign type specifiers - [nonnull-] unsigned-c-string[*], Foreign type specifiers - c-string-list, Foreign type specifiers - [nonnull-] c-string*, Foreign type specifiers @section [nonnull-] unsigned-c-string[*] Same as @code{c-string}, but maps to the @code{unsigned char *} C type. @node Foreign type specifiers - c-string-list, Foreign type specifiers - c-string-list*, Foreign type specifiers - [nonnull-] unsigned-c-string[*], Foreign type specifiers @section c-string-list Expects a pointer to a list of C strings teminated by a @code{NULL} pointer and returns a list of strings. Only valid as a result type of non-callback functions. @node Foreign type specifiers - c-string-list*, Foreign type specifiers - void, Foreign type specifiers - c-string-list, Foreign type specifiers @section c-string-list* Similar to @code{c-string-list} but releases the storage of each string and the pointer array using @code{free(1)}. @node Foreign type specifiers - void, Foreign type specifiers - (const TYPE), Foreign type specifiers - c-string-list*, Foreign type specifiers @section void Specifies an undefined return value. Not allowed as argument type. @node Foreign type specifiers - (const TYPE), Foreign type specifiers - (enum NAME), Foreign type specifiers - void, Foreign type specifiers @section (const TYPE) The foreign type @code{TYPE} with an additional @code{const} specifier. @node Foreign type specifiers - (enum NAME), Foreign type specifiers - (pointer TYPE) (c-pointer TYPE), Foreign type specifiers - (const TYPE), Foreign type specifiers @section (enum NAME) An enumeration type. Handled internally as an @code{integer}. @node Foreign type specifiers - (pointer TYPE) (c-pointer TYPE), Foreign type specifiers - (nonnull-pointer TYPE) (nonnull-c-pointer TYPE), Foreign type specifiers - (enum NAME), Foreign type specifiers @section (pointer TYPE) (c-pointer TYPE) An operating-system pointer or a locative to an object of @code{TYPE}. @node Foreign type specifiers - (nonnull-pointer TYPE) (nonnull-c-pointer TYPE), Foreign type specifiers - (ref TYPE), Foreign type specifiers - (pointer TYPE) (c-pointer TYPE), Foreign type specifiers @section (nonnull-pointer TYPE) (nonnull-c-pointer TYPE) As @code{(pointer TYPE)}, but guaranteed not to be @code{#f/NULL}. @node Foreign type specifiers - (ref TYPE), Foreign type specifiers - (struct NAME), Foreign type specifiers - (nonnull-pointer TYPE) (nonnull-c-pointer TYPE), Foreign type specifiers @section (ref TYPE) A C++ reference type. Reference types are handled the same way as pointers inside Scheme code. @node Foreign type specifiers - (struct NAME), Foreign type specifiers - (template TYPE ARGTYPE ...), Foreign type specifiers - (ref TYPE), Foreign type specifiers @section (struct NAME) A struct of the name @code{NAME}, which should be a string. Structs can not be directly passed as arguments to foreign function, neither can they be result values. Pointers to structs are allowed, though. @node Foreign type specifiers - (template TYPE ARGTYPE ...), Foreign type specifiers - (union NAME), Foreign type specifiers - (struct NAME), Foreign type specifiers @section (template TYPE ARGTYPE ...) A C++ template type. For example @code{vector} would be specified as @code{(template "vector" int)}. Template types can not be directly passed as arguments or returned as results. @node Foreign type specifiers - (union NAME), Foreign type specifiers - (instance CNAME SCHEMECLASS), Foreign type specifiers - (template TYPE ARGTYPE ...), Foreign type specifiers @section (union NAME) A union of the name @code{NAME}, which should be a string. Unions can not be directly passed as arguments to foreign function, neither can they be result values. Pointers to unions are allowed, though. @node Foreign type specifiers - (instance CNAME SCHEMECLASS), Foreign type specifiers - (instance-ref CNAME SCHEMECLASS), Foreign type specifiers - (union NAME), Foreign type specifiers @section (instance CNAME SCHEMECLASS) A pointer to a C++ class instance. @code{CNAME} should designate the name of the C++ class, and @code{SCHEMECLASS} should be the class that wraps the instance pointer. Normally @code{SCHEMECLASS} should be a subclass of @code{}. @node Foreign type specifiers - (instance-ref CNAME SCHEMECLASS), Foreign type specifiers - (function RESULTTYPE (ARGUMENTTYPE1 ... [...]) [CALLCONV]), Foreign type specifiers - (instance CNAME SCHEMECLASS), Foreign type specifiers @section (instance-ref CNAME SCHEMECLASS) A reference to a C++ class instance. @node Foreign type specifiers - (function RESULTTYPE (ARGUMENTTYPE1 ... [...]) [CALLCONV]), Foreign type specifiers - Mappings, Foreign type specifiers - (instance-ref CNAME SCHEMECLASS), Foreign type specifiers @section (function RESULTTYPE (ARGUMENTTYPE1 ... [...]) [CALLCONV]) A function pointer. @code{CALLCONV} specifies an optional calling convention and should be a string. The meaning of this string is entirely platform dependent. The value @code{#f} is also allowed and is passed as a @code{NULL} pointer. @node Foreign type specifiers - Mappings, , Foreign type specifiers - (function RESULTTYPE (ARGUMENTTYPE1 ... [...]) [CALLCONV]), Foreign type specifiers @section Mappings Foreign types are mapped to C types in the following manner:
bool int
[unsigned-]char [unsigned] char
[unsigned-]short [unsigned] short
[unsigned-]int [unsigned] int
[unsigned-]integer [unsigned] int
[unsigned-]long [unsigned] long
float float
double double
number double
[nonnull-]pointer void *
[nonnull-]c-pointer void *
[nonnull-]blob unsigned char *
[nonnull-]u8vector unsigned char *
[nonnull-]s8vector char *
[nonnull-]u16vector unsigned short *
[nonnull-]s16vector short *
[nonnull-]u32vector uint32_t *
[nonnull-]s32vector int32_t *
[nonnull-]f32vector float *
[nonnull-]f64vector double *
[nonnull-]c-string char *
[nonnull-]unsigned-c-string unsigned char *
c-string-listchar **
symbol char *
void void
([nonnull-]pointer TYPE) TYPE *
(enum NAME) enum NAME
(struct NAME) struct NAME
(ref TYPE) TYPE &
(template T1 T2 ...) T1
(union NAME) union NAME
(function RTYPE (ATYPE ...) [CALLCONV]) [CALLCONV] RTYPE (*)(ATYPE, ...)
(instance CNAME SNAME) CNAME *
(instance-ref CNAME SNAME) CNAME &
Previous: @ref{Accessing external objects, Accessing external objects} Next: @ref{Embedding, Embedding} @node Embedding, Callbacks, Foreign type specifiers, Top @chapter Embedding @menu * Embedding - CHICKEN_parse_command_line:: * Embedding - CHICKEN_initialize:: * Embedding - CHICKEN_run:: * Embedding - return-to-host:: * Embedding - CHICKEN_eval:: * Embedding - CHICKEN_eval_string:: * Embedding - CHICKEN_eval_to_string:: * Embedding - CHICKEN_eval_string_to_string:: * Embedding - CHICKEN_apply:: * Embedding - CHICKEN_apply_to_string:: * Embedding - CHICKEN_read:: * Embedding - CHICKEN_load:: * Embedding - CHICKEN_get_error_message:: * Embedding - CHICKEN_yield:: * Embedding - CHICKEN_continue:: * Embedding - CHICKEN_new_gc_root:: * Embedding - CHICKEN_delete_gc_root:: * Embedding - CHICKEN_gc_root_ref:: * Embedding - CHICKEN_gc_root_set:: * Embedding - CHICKEN_global_lookup:: * Embedding - CHICKEN_global_ref:: * Embedding - CHICKEN_global_set:: @end menu Compiled Scheme files can be linked with C code, provided the Scheme code was compiled in @emph{embedded} mode by passing @code{-DC_EMBEDDED} to the C compiler (this will disable generation of a @code{main()} function). @code{csc} will do this, when given the @code{-embedded} option. Alternatively pass @code{-embedded} to @code{csc}. The following C API is available: @node Embedding - CHICKEN_parse_command_line, Embedding - CHICKEN_initialize, , Embedding @section CHICKEN_parse_command_line @verbatim [C function] void CHICKEN_parse_command_line (int argc, char *argv[], int *heap, int *stack int *symbols) @end verbatim Parse the programs command-line contained in @code{argc} and @code{argv} and return the heap-, stack- and symbol table limits given by runtime options of the form @code{-:...}, or choose default limits. The library procedure @code{argv} can access the command-line only if this function has been called by the containing application. @node Embedding - CHICKEN_initialize, Embedding - CHICKEN_run, Embedding - CHICKEN_parse_command_line, Embedding @section CHICKEN_initialize @verbatim [C function] int CHICKEN_initialize (int heap, int stack, int symbols, void *toplevel) @end verbatim Initializes the Scheme execution context and memory. @code{heap} holds the number of bytes that are to be allocated for the secondary heap. @code{stack} holds the number of bytes for the primary heap. @code{symbols} contains the size of the symbol table. Passing @code{0} to one or more of these parameters will select a default size. @code{toplevel} should be a pointer to the toplevel entry point procedure. You should pass @code{C_toplevel} here. In any subsequent call to @code{CHICKEN_run} you can simply pass @code{NULL}. Calling this function more than once has no effect. If enough memory is available and initialization was successful, then @code{1} is returned, otherwise this function returns @code{0}. @node Embedding - CHICKEN_run, Embedding - return-to-host, Embedding - CHICKEN_initialize, Embedding @section CHICKEN_run @verbatim [C function] C_word CHICKEN_run (void *toplevel) @end verbatim Starts the Scheme program. Call this function once to execute all toplevel expressions in your compiled Scheme program. If the runtime system was not initialized before, then @code{CHICKEN_initialize} is called with default sizes. @code{toplevel} is the toplevel entry-point procedure, you usually pass @code{C_toplevel} here. The result value is the continuation that can be used to re-invoke the Scheme code from the point after it called @code{return-to-host} (see below). If you just need a Scheme interpreter, you can also pass @code{CHICKEN_default_toplevel} as the toplevel procedure, which just uses the default library units. Once @code{CHICKEN_run} has been called, Scheme code is executing until all toplevel expressions have been evaluated or until @code{return-to-host} is called inside the Scheme program. @node Embedding - return-to-host, Embedding - CHICKEN_eval, Embedding - CHICKEN_run, Embedding @section return-to-host @verbatim [procedure] (return-to-host) @end verbatim Exits the Scheme code and returns to the invoking context that called @code{CHICKEN_run} or @code{CHICKEN_continue}. After @code{return-to-host} has been executed and once @code{CHICKEN_run} returns, you can invoke callbacks which have been defined with @code{define-external}. The @code{eval} library unit also provides @emph{boilerplate} callbacks, that simplify invoking Scheme code embedded in a C or C++ application a lot. @node Embedding - CHICKEN_eval, Embedding - CHICKEN_eval_string, Embedding - return-to-host, Embedding @section CHICKEN_eval @verbatim [C macro] int CHICKEN_eval (C_word exp, C_word *result) @end verbatim Evaluates the Scheme object passed in @code{exp}, writing the result value to @code{result}. The return value is 1 if the operation succeeded, or 0 if an error occurred. Call @code{CHICKEN_get_error_message} to obtain a description of the error. @node Embedding - CHICKEN_eval_string, Embedding - CHICKEN_eval_to_string, Embedding - CHICKEN_eval, Embedding @section CHICKEN_eval_string @verbatim [C macro] int CHICKEN_eval_string (char *str, C_word *result) @end verbatim Evaluates the Scheme expression passed in the string @code{str}, writing the result value to @code{result}. @node Embedding - CHICKEN_eval_to_string, Embedding - CHICKEN_eval_string_to_string, Embedding - CHICKEN_eval_string, Embedding @section CHICKEN_eval_to_string @verbatim [C macro] int CHICKEN_eval_to_string (C_word exp, char *result, int size) @end verbatim Evaluates the Scheme expression passed in @code{exp}, writing a textual representation of the result into @code{result}. @code{size} should specify the maximal size of the result string. @node Embedding - CHICKEN_eval_string_to_string, Embedding - CHICKEN_apply, Embedding - CHICKEN_eval_to_string, Embedding @section CHICKEN_eval_string_to_string @verbatim [C macro] int CHICKEN_eval_string_to_string (char *str, char *result, int size) @end verbatim Evaluates the Scheme expression passed in the string @code{str}, writing a textual representation of the result into @code{result}. @code{size} should specify the maximal size of the result string. @node Embedding - CHICKEN_apply, Embedding - CHICKEN_apply_to_string, Embedding - CHICKEN_eval_string_to_string, Embedding @section CHICKEN_apply @verbatim [C macro] int CHICKEN_apply (C_word func, C_word args, C_word *result) @end verbatim Applies the procedure passed in @code{func} to the list of arguments @code{args}, writing the result value to @code{result}. @node Embedding - CHICKEN_apply_to_string, Embedding - CHICKEN_read, Embedding - CHICKEN_apply, Embedding @section CHICKEN_apply_to_string @verbatim [C macro] int CHICKEN_apply_to_string (C_word func, C_word args, char *result, int size) @end verbatim Applies the procedure passed in @code{func} to the list of arguments @code{args}, writing a textual representation of the result into @code{result}. @node Embedding - CHICKEN_read, Embedding - CHICKEN_load, Embedding - CHICKEN_apply_to_string, Embedding @section CHICKEN_read @verbatim [C macro] int CHICKEN_read (char *str, C_word *result) @end verbatim Reads a Scheme object from the string @code{str}, writing the result value to @code{result}. @node Embedding - CHICKEN_load, Embedding - CHICKEN_get_error_message, Embedding - CHICKEN_read, Embedding @section CHICKEN_load @verbatim [C macro] int CHICKEN_load (char *filename) @end verbatim Loads the Scheme file @code{filename} (either in source form or compiled). @node Embedding - CHICKEN_get_error_message, Embedding - CHICKEN_yield, Embedding - CHICKEN_load, Embedding @section CHICKEN_get_error_message @verbatim [C macro] void CHICKEN_get_error_message (char *result, int size) @end verbatim Returns a textual description of the most recent error that occurred in executing embedded Scheme code. @node Embedding - CHICKEN_yield, Embedding - CHICKEN_continue, Embedding - CHICKEN_get_error_message, Embedding @section CHICKEN_yield @verbatim [C macro] int CHICKEN_yield (int *status) @end verbatim If threads have been spawned during earlier invocations of embedded Scheme code, then this function will run the next scheduled thread for one complete time-slice. This is useful, for example, inside an @emph{idle} handler in a GUI application with background Scheme threads. Note that the @code{srfi-18} library unit has to be linked in for this. An example: @verbatim % cat x.scm ;;; x.scm (define (bar x) (gc) (* x x)) (define-external (baz (int i)) double (sqrt i)) (return-to-host) @end verbatim @verbatim % cat y.c /* y.c */ #include #include extern double baz(int); int main() @{ char buffer[ 256 ]; int status; C_word val = C_SCHEME_UNDEFINED; C_word *data[ 1 ]; data[ 0 ] = &val; CHICKEN_run(C_toplevel); status = CHICKEN_read("(bar 99)", &val); assert(status); C_gc_protect(data, 1); printf("data: %08x\n", val); status = CHICKEN_eval_string_to_string("(bar)", buffer, 255); assert(!status); CHICKEN_get_error_message(buffer, 255); printf("ouch: %s\n", buffer); status = CHICKEN_eval_string_to_string("(bar 23)", buffer, 255); assert(status); printf("-> %s\n", buffer); printf("data: %08x\n", val); status = CHICKEN_eval_to_string(val, buffer, 255); assert(status); printf("-> %s\n", buffer); printf("->` %g\n", baz(22)); return 0; @} % csc x.scm y.c -embedded @end verbatim It is also possible to re-enter the computation following the call to @code{return-to-host} by calling @code{CHICKEN_continue}: @node Embedding - CHICKEN_continue, Embedding - CHICKEN_new_gc_root, Embedding - CHICKEN_yield, Embedding @section CHICKEN_continue @verbatim [C function] C_word CHICKEN_continue (C_word k) @end verbatim Re-enters Scheme execution. @code{k} is the continuation received from the previous invocation of @code{CHICKEN_run} or @code{CHICKEN_continue}. When @code{return-to-host} is called again, this function returns another continuation that can be used to restart again. If you invoke callbacks prior to calling @code{CHICKEN_continue}, make sure that the continuation is not reclaimed by garbage collection. This can be avoided by using @code{C_gc_protect} or gc-roots. Another example: @verbatim % cat x.scm (require-extension srfi-18) (define m (make-mutex)) (define (t) (mutex-lock! m) (thread-sleep! 1) (print (thread-name (current-thread))) (mutex-unlock! m) (t) ) (thread-start! (make-thread t 'PING!)) (thread-start! (make-thread t 'PONG!)) (let loop () (return-to-host) (thread-yield!) (loop) ) % cat y.c #include int main() @{ C_word k = CHICKEN_run(C_toplevel); for(;;) k = CHICKEN_continue(k); return 0; @} % csc x.scm y.c -embedded @end verbatim It is advisable not to mix repeated uses of @code{CHICKEN_continue}/@code{return-to-host} (as in the example above) with callbacks. Once @code{return-to-host} is invoked, the runtime system and any Scheme code executed prior to the invocation is initialized and can be conveniently used via callbacks. A simpler interface For handling GC-safe references to Scheme data are the so called @emph{gc-roots}: @node Embedding - CHICKEN_new_gc_root, Embedding - CHICKEN_delete_gc_root, Embedding - CHICKEN_continue, Embedding @section CHICKEN_new_gc_root @verbatim [C function] void* CHICKEN_new_gc_root () @end verbatim Returns a pointer to a @emph{GC root}, which is an object that holds a reference to a Scheme value that will always be valid, even after a garbage collection. The content of the gc root is initialized to an unspecified value. @node Embedding - CHICKEN_delete_gc_root, Embedding - CHICKEN_gc_root_ref, Embedding - CHICKEN_new_gc_root, Embedding @section CHICKEN_delete_gc_root @verbatim [C function] void CHICKEN_delete_gc_root (void *root) @end verbatim Deletes the gc root. @node Embedding - CHICKEN_gc_root_ref, Embedding - CHICKEN_gc_root_set, Embedding - CHICKEN_delete_gc_root, Embedding @section CHICKEN_gc_root_ref @verbatim [C macro] C_word CHICKEN_gc_root_ref (void *root) @end verbatim Returns the value stored in the gc root. @node Embedding - CHICKEN_gc_root_set, Embedding - CHICKEN_global_lookup, Embedding - CHICKEN_gc_root_ref, Embedding @section CHICKEN_gc_root_set @verbatim [C macro] void CHICKEN_gc_root_set (void *root, C_word value) @end verbatim Sets the content of the GC root to a new value. Sometimes it is handy to access global variables from C code: @node Embedding - CHICKEN_global_lookup, Embedding - CHICKEN_global_ref, Embedding - CHICKEN_gc_root_set, Embedding @section CHICKEN_global_lookup @verbatim [C function] void* CHICKEN_global_lookup (char *name) @end verbatim Returns a GC root that holds the global variable with the name @code{name}. If no such variable exists, @code{NULL} is returned. @node Embedding - CHICKEN_global_ref, Embedding - CHICKEN_global_set, Embedding - CHICKEN_global_lookup, Embedding @section CHICKEN_global_ref @verbatim [C function] C_word CHICKEN_global_ref (void *global) @end verbatim Returns the value of the global variable referenced by the GC root @code{global}. @node Embedding - CHICKEN_global_set, , Embedding - CHICKEN_global_ref, Embedding @section CHICKEN_global_set @verbatim [C function] void CHICKEN_global_set (void *global, C_word value) @end verbatim Sets the value of the global variable referenced by the GC root @code{global} to @code{value}. Previous: @ref{Foreign type specifiers, Foreign type specifiers} Next: @ref{Callbacks, Callbacks} @node Callbacks, Locations, Embedding, Top @chapter Callbacks @menu * Callbacks - define-external:: * Callbacks - C_callback:: * Callbacks - C_callback_adjust_stack_limits:: @end menu To enable an external C function to call back to Scheme, the form @code{foreign-safe-lambda} (or @code{foreign-safe-lambda*}) has to be used. This generates special code to save and restore important state information during execution of C code. There are two ways of calling Scheme procedures from C: the first is to invoke the runtime function @code{C_callback} with the closure to be called and the number of arguments. The second is to define an externally visible wrapper function around a Scheme procedure with the @code{define-external} form. Note: the names of all functions, variables and macros exported by the CHICKEN runtime system start with @code{C_}. It is advisable to use a different naming scheme for your own code to avoid name clashes. Callbacks (defined by @code{define-external}) do not capture the lexical environment. Non-local exits leaving the scope of the invocation of a callback from Scheme into C will not remove the C call-frame from the stack (and will result in a memory leak). @node Callbacks - define-external, Callbacks - C_callback, , Callbacks @section define-external @verbatim [syntax] (define-external [QUALIFIERS] (NAME (ARGUMENTTYPE1 VARIABLE1) ...) RETURNTYPE BODY ...) [syntax] (define-external NAME TYPE [INIT]) @end verbatim The first form defines an externally callable Scheme procedure. @code{NAME} should be a symbol, which, when converted to a string, represents a legal C identifier. @code{ARGUMENTTYPE1 ...} and @code{RETURNTYPE} are foreign type specifiers for the argument variables @code{VAR1 ...} and the result, respectively. @code{QUALIFIERS} is an optional qualifier for the foreign procedure definition, like @code{__stdcall}. (define-external (foo (c-string x)) int (string-length x)) The second form of @code{define-external} can be used to define variables that are accessible from foreign code. It declares a global variable named by the symbol @code{NAME} that has the type @code{TYPE}. @code{INIT} can be an arbitrary expression that is used to initialize the variable. @code{NAME} is accessible from Scheme just like any other foreign variable defined by @code{define-foreign-variable}. (define-external foo int 42) ((foreign-lambda* int () @verbatim "C_return(foo);")) ==> 42 @end verbatim @b{Note:} don't be tempted to assign strings or bytevectors to external variables. Garbage collection moves those objects around, so it is very bad idea to assign pointers to heap-data. If you have to do so, then copy the data object into statically allocated memory (for example by using @code{object-evict}). Results of type @code{scheme-object} returned by @code{define-external} are always allocated in the secondary heap, that is, not in the stack. @node Callbacks - C_callback, Callbacks - C_callback_adjust_stack_limits, Callbacks - define-external, Callbacks @section C_callback @verbatim [C function] C_word C_callback (C_word closure, int argc) @end verbatim This function can be used to invoke the Scheme procedure @code{closure}. @code{argc} should contain the number of arguments that are passed to the procedure on the temporary stack. Values are put onto the temporary stack with the @code{C_save} macro. @node Callbacks - C_callback_adjust_stack_limits, , Callbacks - C_callback, Callbacks @section C_callback_adjust_stack_limits @verbatim [C function] void C_callback_adjust_stack_limits (C_word *ptr) @end verbatim The runtime-system uses the stack as a special allocation area and internally holds pointers to estimated limits to distinguish between Scheme data objects inside the stack from objects outside of it. If you invoke callbacks at wildly differing stack-levels, these limits may shift from invocation to invocation. Callbacks defined with @code{define-external} will perform appropriate adjustments automatically, but if you invoke @code{C_callback} manually, you should perform a @code{C_callback_adjust_stack_limits} to make sure the internal limits are set properly. @code{ptr} should point to some data object on the stack. The call will make sure the limits are adjusted so that the value pointed to by @code{ptr} is located in the stack. Previous: @ref{Embedding, Embedding} Next: @ref{Locations, Locations} @node Locations, Other support procedures, Callbacks, Top @chapter Locations @menu * Locations - define-location:: * Locations - let-location:: * Locations - location:: @end menu It is also possible to define variables containing unboxed C data, so called @emph{locations}. It should be noted that locations may only contain simple data, that is: everything that fits into a machine word, and double-precision floating point values. @node Locations - define-location, Locations - let-location, , Locations @section define-location @verbatim [syntax] (define-location NAME TYPE [INIT]) @end verbatim Identical to @code{(define-external NAME TYPE [INIT])}, but the variable is not accessible from outside of the current compilation unit (it is declared @code{static}). @node Locations - let-location, Locations - location, Locations - define-location, Locations @section let-location @verbatim [syntax] (let-location ((NAME TYPE [INIT]) ...) BODY ...) @end verbatim Defines a lexically bound location. @node Locations - location, , Locations - let-location, Locations @section location @verbatim [syntax] (location NAME) [syntax] (location X) @end verbatim This form returns a pointer object that contains the address of the variable @code{NAME}. If the argument to @code{location} is not a location defined by @code{define-location}, @code{define-external} or @code{let-location}, then @verbatim (location X) @end verbatim is essentially equivalent to @verbatim (make-locative X) @end verbatim (See the manual chapter or @code{locatives} for more information about locatives. Note that @code{(location X)} may be abbreviated as @code{#$X}. (define-external foo int) ((foreign-lambda* void (((pointer int) ip)) "*ip = 123;") @verbatim (location foo)) @end verbatim foo ==> 123 This facility is especially useful in situations, where a C function returns more than one result value: @enumerate @item > @item include <# @end enumerate (define modf @verbatim (foreign-lambda double "modf" double (pointer double)) ) @end verbatim (let-location ([i double]) @verbatim (let ([f (modf 1.99 (location i))]) (print "i=" i ", f=" f) ) ) @end verbatim @code{location} returns a value of type @code{c-pointer}, when given the name of a callback-procedure defined with @code{define-external}. Previous: @ref{Callbacks, Callbacks} Next: @ref{Other support procedures, Other support procedures} @node Other support procedures, C interface, Locations, Top @chapter Other support procedures @menu * Other support procedures - argc+argv:: @end menu @node Other support procedures - argc+argv, , , Other support procedures @section argc+argv @verbatim [procedure] (argc+argv) @end verbatim Returns two values: an integer and a foreign-pointer object representing the @code{argc} and @code{argv} arguments passed to the current process. Previous: @ref{Locations, Locations} Next: @ref{C interface, C interface} @node C interface, chicken-setup, Other support procedures, Top @chapter C interface @menu * C interface - C_save:: * C interface - C_restore:: * C interface - C_fix:: * C interface - C_make_character:: * C interface - C_SCHEME_END_OF_LIST:: * C interface - C_word C_SCHEME_END_OF_FILE:: * C interface - C_word C_SCHEME_FALSE:: * C interface - C_word C_SCHEME_TRUE:: * C interface - C_string:: * C interface - C_string2:: * C interface - C_intern2:: * C interface - C_intern3:: * C interface - C_pair:: * C interface - C_flonum:: * C interface - C_int_to_num:: * C interface - C_mpointer:: * C interface - C_vector:: * C interface - C_list:: * C interface - C_alloc:: * C interface - C_SIZEOF_LIST:: * C interface - C_SIZEOF_STRING:: * C interface - C_SIZEOF_VECTOR:: * C interface - C_SIZEOF_INTERNED_SYMBOL:: * C interface - C_SIZEOF_PAIR:: * C interface - C_SIZEOF_FLONUM:: * C interface - C_SIZEOF_POINTER:: * C interface - C_SIZEOF_LOCATIVE:: * C interface - C_SIZEOF_TAGGED_POINTER:: * C interface - C_character_code:: * C interface - C_unfix:: * C interface - C_flonum_magnitude:: * C interface - C_c_string:: * C interface - C_num_to_int:: * C interface - C_pointer_address:: * C interface - C_header_size:: * C interface - C_header_bits:: * C interface - C_block_item:: * C interface - C_u_i_car:: * C interface - C_u_i_cdr:: * C interface - C_data_pointer:: * C interface - C_make_header:: * C interface - C_mutate:: * C interface - C_symbol_value:: * C interface - C_gc_protect:: * C interface - C_gc_unprotect:: * C interface - C_post_gc_hook:: @end menu The following functions and macros are available for C code that invokes Scheme or foreign procedures that are called by Scheme: @node C interface - C_save, C interface - C_restore, , C interface @section C_save @verbatim [C macro] void C_save (C_word x) : @end verbatim Saves the Scheme data object @code{x} on the temporary stack. @node C interface - C_restore, C interface - C_fix, C interface - C_save, C interface @section C_restore @verbatim [C macro] void C_restore @end verbatim Pops and returns the topmost value from the temporary stack. @node C interface - C_fix, C interface - C_make_character, C interface - C_restore, C interface @section C_fix @verbatim [C macro] C_word C_fix (int integer) @end verbatim @node C interface - C_make_character, C interface - C_SCHEME_END_OF_LIST, C interface - C_fix, C interface @section C_make_character @verbatim [C macro] C_word C_make_character (int char_code) @end verbatim @node C interface - C_SCHEME_END_OF_LIST, C interface - C_word C_SCHEME_END_OF_FILE, C interface - C_make_character, C interface @section C_SCHEME_END_OF_LIST @verbatim [C macro] C_SCHEME_END_OF_LIST @end verbatim @node C interface - C_word C_SCHEME_END_OF_FILE, C interface - C_word C_SCHEME_FALSE, C interface - C_SCHEME_END_OF_LIST, C interface @section C_word C_SCHEME_END_OF_FILE @verbatim [C macro] C_SCHEME_END_OF_FILE @end verbatim @node C interface - C_word C_SCHEME_FALSE, C interface - C_word C_SCHEME_TRUE, C interface - C_word C_SCHEME_END_OF_FILE, C interface @section C_word C_SCHEME_FALSE @verbatim [C macro] C_SCHEME_FALSE @end verbatim @node C interface - C_word C_SCHEME_TRUE, C interface - C_string, C interface - C_word C_SCHEME_FALSE, C interface @section C_word C_SCHEME_TRUE @verbatim [C macro] C_SCHEME_TRUE @end verbatim These macros return immediate Scheme data objects. @node C interface - C_string, C interface - C_string2, C interface - C_word C_SCHEME_TRUE, C interface @section C_string @verbatim [C function] C_word C_string (C_word **ptr, int length, char *string) @end verbatim @node C interface - C_string2, C interface - C_intern2, C interface - C_string, C interface @section C_string2 @verbatim [C function] C_word C_string2 (C_word **ptr, char *zero_terminated_string) @end verbatim @node C interface - C_intern2, C interface - C_intern3, C interface - C_string2, C interface @section C_intern2 @verbatim [C function] C_word C_intern2 (C_word **ptr, char *zero_terminated_string) @end verbatim @node C interface - C_intern3, C interface - C_pair, C interface - C_intern2, C interface @section C_intern3 @verbatim [C function] C_word C_intern3 (C_word **ptr, char *zero_terminated_string, C_word initial_value) @end verbatim @node C interface - C_pair, C interface - C_flonum, C interface - C_intern3, C interface @section C_pair @verbatim [C function] C_word C_pair (C_word **ptr, C_word car, C_word cdr) @end verbatim @node C interface - C_flonum, C interface - C_int_to_num, C interface - C_pair, C interface @section C_flonum @verbatim [C function] C_word C_flonum (C_word **ptr, double number) @end verbatim @node C interface - C_int_to_num, C interface - C_mpointer, C interface - C_flonum, C interface @section C_int_to_num @verbatim [C function] C_word C_int_to_num (C_word **ptr, int integer) @end verbatim @node C interface - C_mpointer, C interface - C_vector, C interface - C_int_to_num, C interface @section C_mpointer @verbatim [C function] C_word C_mpointer (C_word **ptr, void *pointer) @end verbatim @node C interface - C_vector, C interface - C_list, C interface - C_mpointer, C interface @section C_vector @verbatim [C function] C_word C_vector (C_word **ptr, int length, ...) @end verbatim @node C interface - C_list, C interface - C_alloc, C interface - C_vector, C interface @section C_list @verbatim [C function] C_word C_list (C_word **ptr, int length, ...) @end verbatim These functions allocate memory from @code{ptr} and initialize a fresh data object. The new data object is returned. @code{ptr} should be the @b{address} of an allocation pointer created with @code{C_alloc}. @node C interface - C_alloc, C interface - C_SIZEOF_LIST, C interface - C_list, C interface @section C_alloc @verbatim [C macro] C_word* C_alloc (int words) @end verbatim Allocates memory from the C stack (@code{C_alloc}) and returns a pointer to it. @code{words} should be the number of words needed for all data objects that are to be created in this function. Note that stack-allocated data objects have to be passed to Scheme callback functions, or they will not be seen by the garbage collector. This is really only usable for callback procedure invocations, make sure not to use it in normal code, because the allocated memory will be re-used after the foreign procedure returns. When invoking Scheme callback procedures a minor garbage collection is performed, so data allocated with @code{C_alloc} will already have moved to a safe place. Note that @code{C_alloc} is really just a wrapper around @code{alloca}, and can also be simulated by declaring a stack-allocated array of @code{C_word}s: @node C interface - C_SIZEOF_LIST, C interface - C_SIZEOF_STRING, C interface - C_alloc, C interface @section C_SIZEOF_LIST @verbatim [C macro] int C_SIZEOF_LIST (int length) @end verbatim @node C interface - C_SIZEOF_STRING, C interface - C_SIZEOF_VECTOR, C interface - C_SIZEOF_LIST, C interface @section C_SIZEOF_STRING @verbatim [C macro] int C_SIZEOF_STRING (int length) @end verbatim @node C interface - C_SIZEOF_VECTOR, C interface - C_SIZEOF_INTERNED_SYMBOL, C interface - C_SIZEOF_STRING, C interface @section C_SIZEOF_VECTOR @verbatim [C macro] int C_SIZEOF_VECTOR (int length) @end verbatim @node C interface - C_SIZEOF_INTERNED_SYMBOL, C interface - C_SIZEOF_PAIR, C interface - C_SIZEOF_VECTOR, C interface @section C_SIZEOF_INTERNED_SYMBOL @verbatim [C macro] int C_SIZEOF_INTERNED_SYMBOL (int length) @end verbatim @node C interface - C_SIZEOF_PAIR, C interface - C_SIZEOF_FLONUM, C interface - C_SIZEOF_INTERNED_SYMBOL, C interface @section C_SIZEOF_PAIR @verbatim [C macro] int C_SIZEOF_PAIR @end verbatim @node C interface - C_SIZEOF_FLONUM, C interface - C_SIZEOF_POINTER, C interface - C_SIZEOF_PAIR, C interface @section C_SIZEOF_FLONUM @verbatim [C macro] int C_SIZEOF_FLONUM @end verbatim @node C interface - C_SIZEOF_POINTER, C interface - C_SIZEOF_LOCATIVE, C interface - C_SIZEOF_FLONUM, C interface @section C_SIZEOF_POINTER @verbatim [C macro] int C_SIZEOF_POINTER @end verbatim @node C interface - C_SIZEOF_LOCATIVE, C interface - C_SIZEOF_TAGGED_POINTER, C interface - C_SIZEOF_POINTER, C interface @section C_SIZEOF_LOCATIVE @verbatim [C macro] int C_SIZEOF_LOCATIVE @end verbatim @node C interface - C_SIZEOF_TAGGED_POINTER, C interface - C_character_code, C interface - C_SIZEOF_LOCATIVE, C interface @section C_SIZEOF_TAGGED_POINTER @verbatim [C macro] int C_SIZEOF_TAGGED_POINTER @end verbatim These are macros that return the size in words needed for a data object of a given type. @node C interface - C_character_code, C interface - C_unfix, C interface - C_SIZEOF_TAGGED_POINTER, C interface @section C_character_code @verbatim [C macro] int C_character_code (C_word character) @end verbatim @node C interface - C_unfix, C interface - C_flonum_magnitude, C interface - C_character_code, C interface @section C_unfix @verbatim [C macro] int C_unfix (C_word fixnum) @end verbatim @node C interface - C_flonum_magnitude, C interface - C_c_string, C interface - C_unfix, C interface @section C_flonum_magnitude @verbatim [C macro] double C_flonum_magnitude (C_word flonum) @end verbatim @node C interface - C_c_string, C interface - C_num_to_int, C interface - C_flonum_magnitude, C interface @section C_c_string @verbatim [C function] char* C_c_string (C_word string) @end verbatim @node C interface - C_num_to_int, C interface - C_pointer_address, C interface - C_c_string, C interface @section C_num_to_int @verbatim [C function] int C_num_to_int (C_word fixnum_or_flonum) @end verbatim @node C interface - C_pointer_address, C interface - C_header_size, C interface - C_num_to_int, C interface @section C_pointer_address @verbatim [C function] void* C_pointer_address (C_word pointer) @end verbatim These macros and functions can be used to convert Scheme data objects back to C data. Note that @code{C_c_string()} returns a pointer to the character buffer of the actual Scheme object and is not zero-terminated. @node C interface - C_header_size, C interface - C_header_bits, C interface - C_pointer_address, C interface @section C_header_size @verbatim [C macro] int C_header_size (C_word x) @end verbatim @node C interface - C_header_bits, C interface - C_block_item, C interface - C_header_size, C interface @section C_header_bits @verbatim [C macro] int C_header_bits (C_word x) @end verbatim Return the number of elements and the type-bits of the non-immediate Scheme data object @code{x}. @node C interface - C_block_item, C interface - C_u_i_car, C interface - C_header_bits, C interface @section C_block_item @verbatim [C macro] C_word C_block_item (C_word x, int index) @end verbatim This macro can be used to access slots of the non-immediate Scheme data object @code{x}. @code{index} specifies the index of the slot to be fetched, starting at 0. Pairs have 2 slots, one for the @b{car} and one for the @b{cdr}. Vectors have one slot for each element. @node C interface - C_u_i_car, C interface - C_u_i_cdr, C interface - C_block_item, C interface @section C_u_i_car @verbatim [C macro] C_word C_u_i_car (C_word x) @end verbatim @node C interface - C_u_i_cdr, C interface - C_data_pointer, C interface - C_u_i_car, C interface @section C_u_i_cdr @verbatim [C macro] C_word C_u_i_cdr (C_word x) @end verbatim Aliases for @code{C_block_item(x, 0)} and @code{C_block_item(x, 1)}, respectively. @node C interface - C_data_pointer, C interface - C_make_header, C interface - C_u_i_cdr, C interface @section C_data_pointer @verbatim [C macro] void* C_data_pointer (C_word x) @end verbatim Returns a pointer to the data-section of a non-immediate Scheme object. @node C interface - C_make_header, C interface - C_mutate, C interface - C_data_pointer, C interface @section C_make_header @verbatim [C macro] C_word C_make_header (C_word bits, C_word size) @end verbatim A macro to build a Scheme object header from its bits and size parts. @node C interface - C_mutate, C interface - C_symbol_value, C interface - C_make_header, C interface @section C_mutate @verbatim [C function] C_word C_mutate (C_word *slot, C_word val) @end verbatim Assign the Scheme value @code{val} to the location specified by @code{slot}. If the value points to data inside the nursery (the first heap-generation), then the garbage collector will remember to handle the data appropriately. Assigning nursery-pointers directly will otherwise result in lost data. Note that no copying takes place at the moment when @code{C_mutate} is called, but later - at the next (minor) garbage collection. @node C interface - C_symbol_value, C interface - C_gc_protect, C interface - C_mutate, C interface @section C_symbol_value @verbatim [C macro] C_word C_symbol_value (C_word symbol) @end verbatim Returns the global value of the variable with the name @code{symbol}. If the variable is unbound @code{C_SCHEME_UNBOUND} is returned. You can set a variable's value with @code{C_mutate(&C_symbol_value(SYMBOL), VALUE)}. @node C interface - C_gc_protect, C interface - C_gc_unprotect, C interface - C_symbol_value, C interface @section C_gc_protect @verbatim [C function] void C_gc_protect (C_word *ptrs[], int n) @end verbatim Registers @code{n} variables at address @code{ptrs} to be garbage collection roots. The locations should not contain pointers to data allocated in the nursery, only immediate values or pointers to heap-data are valid. Any assignment of potential nursery data into a root-array should be done via @code{C_mutate()}. The variables have to be initialized to sensible values before the next garbage collection starts (when in doubt, set all locations in @code{ptrs} to @code{C_SCHEME_UNDEFINED}) @code{C_gc_protect} may not called before the runtime system has been initialized (either by @code{CHICKEN_initialize}, @code{CHICKEN_run} or @code{CHICKEN_invoke}. For a slightly simpler interface to creating and using GC roots see @code{CHICKEN_new_gc_root}. @node C interface - C_gc_unprotect, C interface - C_post_gc_hook, C interface - C_gc_protect, C interface @section C_gc_unprotect @verbatim [C function] void C_gc_unprotect (int n) @end verbatim Removes the last @code{n} registered variables from the set of root variables. @node C interface - C_post_gc_hook, , C interface - C_gc_unprotect, C interface @section C_post_gc_hook @verbatim [C Variable] void (*C_post_gc_hook)(int mode) @end verbatim If not @code{NULL}, the function pointed to by this variable will be called after each garbage collection with a flag indicating what kind of collection was performed (either @code{0} for a minor collection or @code{1} for a major collection). Minor collections happen very frequently, so the hook function should not consume too much time. The hook function may not invoke Scheme callbacks. An example: @verbatim % cat foo.scm #> extern int callout(int, int, int); <# @end verbatim @verbatim (define callout (foreign-safe-lambda int "callout" int int int)) @end verbatim @verbatim (define-external (callin (scheme-object xyz)) int (print "This is 'callin': " xyz) 123) @end verbatim @verbatim (print (callout 1 2 3)) @end verbatim @verbatim % cat bar.c #include #include "chicken.h" @end verbatim @verbatim extern int callout(int, int, int); extern int callin(C_word x); @end verbatim @verbatim int callout(int x, int y, int z) @{ C_word *ptr = C_alloc(C_SIZEOF_LIST(3)); C_word lst; @end verbatim @verbatim printf("This is 'callout': %d, %d, %d\n", x, y, z); lst = C_list(&ptr, 3, C_fix(x), C_fix(y), C_fix(z)); return callin(lst); /* Note: `callin' will have GC'd the data in `ptr' */ @} @end verbatim @verbatim % csc foo.scm bar.c -o foo % foo This is 'callout': 1, 2, 3 This is 'callin': (1 2 3) 123 @end verbatim @b{Notes:} Scheme procedures can call C functions, and C functions can call Scheme procedures, but for every pending C stack frame, the available size of the first heap generation (the @emph{nursery}) will be decreased, because the C stack is identical to the nursery. On systems with a small nursery this might result in thrashing, since the C code between the invocation of C from Scheme and the actual calling back to Scheme might build up several stack-frames or allocates large amounts of stack data. To prevent this it is advisable to increase the default nursery size, either when compiling the file (using the @code{-nursery} option) or when running the executable (using the @code{-:s} runtime option). Calls to Scheme/C may be nested arbitrarily, and Scheme continuations can be invoked as usual, but keep in mind that C stack frames will not be recovered, when a Scheme procedure call from C does not return normally. When multiple threads are running concurrently, and control switches from one thread to another, then the continuation of the current thread is captured and saved. Any pending C stack frame still active from a callback will remain on the stack until the threads is re-activated again. This means that in a multithreading situation, when C callbacks are involved, the available nursery space can be smaller than expected. So doing many nested Scheme->C->Scheme calls can reduce the available memory up to the point of thrashing. It is advisable to have only a single thread with pending C stack-frames at any given time. Pointers to Scheme data objects should not be stored in local or global variables while calling back to Scheme. Any Scheme object not passed back to Scheme will be reclaimed or moved by the garbage collector. Calls from C to Scheme are never tail-recursive. Continuations captured via @code{call-with-current-continuation} and passed to C code can be invoked like any other Scheme procedure. Previous: @ref{Other support procedures, Other support procedures} Next: @ref{chicken-setup, chicken-setup} @node chicken-setup, Data representation, C interface, Top @chapter chicken-setup @menu * chicken-setup - Extension libraries:: * chicken-setup - Installing extensions:: * chicken-setup - Creating extensions:: * chicken-setup - Procedures and macros available in setup scripts:: * chicken-setup - Examples for extensions:: * chicken-setup - chicken-setup reference:: * chicken-setup - Windows notes:: * chicken-setup - Security:: * chicken-setup - Other modes if installation:: * chicken-setup - Linking extensions statically:: @end menu @node chicken-setup - Extension libraries, chicken-setup - Installing extensions, , chicken-setup @section Extension libraries Extension libraries (@emph{eggs}) are extensions to the core functionality provided by the basic CHICKEN system, to be built and installed separately. The mechanism for loading compiled extensions is based on dynamically loadable code and as such is only available on systems on which loading compiled code at runtime is supported. Currently these are most UNIX-compatible platforms that provide the @code{libdl} functionality like Linux, Solaris, BSD, Mac OS X and Windows using Cygwin. Note: Extension may also be normal applications or shell scripts, but are usually libraries. @code{chicken-setup} will download the source code for extension automatically from the canonical server at @uref{http://www.call-with-current-continuation.org/eggs, http://www.call-with-current-continuation.org/eggs} if the requested egg does not exist in the current directory. Various command-line options exist for customizing the process and/or retrieving the egg from other locations or in other formats. @node chicken-setup - Installing extensions, chicken-setup - Creating extensions, chicken-setup - Extension libraries, chicken-setup @section Installing extensions To install an extension library, run the @code{chicken-setup} program with the extension name as argument. The extension archive is downloaded, its contents extracted and the contained @emph{setup} script is executed. This setup script is a normal Scheme source file, which will be interpreted by @code{chicken-setup}. The complete language supported by @code{csi} is available, and the library units @code{srfi-1 regex utils posix tcp} are loaded. Additional libraries can be loaded at run-time. The setup script should perform all necessary steps to build the new library (or application). After a successful build, the extension can be installed by invoking one of the procedures @code{install-extension}, @code{install-program} or @code{install-script}. These procedures will copy a number of given files into the extension repository or in the path where the CHICKEN executables are located (in the case of executable programs or scripts). Additionally the list of installed files, and user-defined metadata is stored in the repository. If no extension name is given on the command-line, and if none of the options @code{-list}, @code{-version}, @code{-repository} (without argument), @code{-program-path} (without argument), @code{-fetch}, @code{-fetch-tree} or @code{-docindex} is given, then all @code{.setup} scripts in the current directory are processed. @node chicken-setup - Creating extensions, chicken-setup - Procedures and macros available in setup scripts, chicken-setup - Installing extensions, chicken-setup @section Creating extensions Extensions can be created by creating an (optionally gzipped) @code{tar} archive named @code{EXTENSION.egg} containing all needed files plus a @code{.setup} script in the root directory. After @code{chicken-setup} has extracted the files, the setup script will be invoked. There are no additional constraints on the structure of the archive, but the setup script has to be in the root path of the archive. @node chicken-setup - Procedures and macros available in setup scripts, chicken-setup - Examples for extensions, chicken-setup - Creating extensions, chicken-setup @section Procedures and macros available in setup scripts @menu * chicken-setup - Procedures and macros available in setup scripts - install-extension:: * chicken-setup - Procedures and macros available in setup scripts - install-program:: * chicken-setup - Procedures and macros available in setup scripts - install-script:: * chicken-setup - Procedures and macros available in setup scripts - run:: * chicken-setup - Procedures and macros available in setup scripts - compile:: * chicken-setup - Procedures and macros available in setup scripts - make:: * chicken-setup - Procedures and macros available in setup scripts - patch:: * chicken-setup - Procedures and macros available in setup scripts - copy-file:: * chicken-setup - Procedures and macros available in setup scripts - move-file:: * chicken-setup - Procedures and macros available in setup scripts - remove-file*:: * chicken-setup - Procedures and macros available in setup scripts - find-library:: * chicken-setup - Procedures and macros available in setup scripts - find-header:: * chicken-setup - Procedures and macros available in setup scripts - try-compile:: * chicken-setup - Procedures and macros available in setup scripts - create-directory:: * chicken-setup - Procedures and macros available in setup scripts - installation-prefix:: * chicken-setup - Procedures and macros available in setup scripts - program-path:: * chicken-setup - Procedures and macros available in setup scripts - setup-root-directory:: * chicken-setup - Procedures and macros available in setup scripts - setup-build-directory:: * chicken-setup - Procedures and macros available in setup scripts - setup-verbose-flag:: * chicken-setup - Procedures and macros available in setup scripts - setup-install-flag:: * chicken-setup - Procedures and macros available in setup scripts - required-chicken-version:: * chicken-setup - Procedures and macros available in setup scripts - required-extension-version:: * chicken-setup - Procedures and macros available in setup scripts - cross-chicken:: @end menu @node chicken-setup - Procedures and macros available in setup scripts - install-extension, chicken-setup - Procedures and macros available in setup scripts - install-program, , chicken-setup - Procedures and macros available in setup scripts @subsection install-extension @menu * chicken-setup - Procedures and macros available in setup scripts - install-extension - syntax:: * chicken-setup - Procedures and macros available in setup scripts - install-extension - require-at-runtime:: * chicken-setup - Procedures and macros available in setup scripts - install-extension - version:: * chicken-setup - Procedures and macros available in setup scripts - install-extension - documentation:: * chicken-setup - Procedures and macros available in setup scripts - install-extension - examples:: * chicken-setup - Procedures and macros available in setup scripts - install-extension - exports:: * chicken-setup - Procedures and macros available in setup scripts - install-extension - static:: * chicken-setup - Procedures and macros available in setup scripts - install-extension - static-options:: @end menu @verbatim (install-extension ID FILELIST [INFOLIST]) @end verbatim Installs the extension library with the name @code{ID}. All files given in the list of strings @code{FILELIST} will be copied to the extension repository. It should be noted here that the extension id has to be identical to the name of the file implementing the extension. The extension may load or include other files, or may load other extensions at runtime specified by the @code{require-at-runtime} property. @code{FILELIST} may be a filename, a list of filenames, or a list of pairs of the form @code{(SOURCE DEST)} (if you want to copy into a particular sub-directory - the destination directory will be created as needed). If @code{DEST} is a relative pathname, < it will be copied into the extension repository. The optional argument @code{INFOLIST} should be an association list that maps symbols to values, this list will be stored as @code{ID.setup} at the same location as the extension code. Currently the following properties are used: @node chicken-setup - Procedures and macros available in setup scripts - install-extension - syntax, chicken-setup - Procedures and macros available in setup scripts - install-extension - require-at-runtime, , chicken-setup - Procedures and macros available in setup scripts - install-extension @subsubsection syntax @verbatim [extension property] (syntax) @end verbatim Marks the extension as syntax-only. No code is compiled, the extension is intended as a file containing macros to be loaded at compile/macro-expansion time. @node chicken-setup - Procedures and macros available in setup scripts - install-extension - require-at-runtime, chicken-setup - Procedures and macros available in setup scripts - install-extension - version, chicken-setup - Procedures and macros available in setup scripts - install-extension - syntax, chicken-setup - Procedures and macros available in setup scripts - install-extension @subsubsection require-at-runtime @verbatim [extension property] (require-at-runtime ID ...) @end verbatim Specifies extensions that should be loaded (via @code{require}) at runtime. This is mostly useful for syntax extensions that need additional support code at runtime. @node chicken-setup - Procedures and macros available in setup scripts - install-extension - version, chicken-setup - Procedures and macros available in setup scripts - install-extension - documentation, chicken-setup - Procedures and macros available in setup scripts - install-extension - require-at-runtime, chicken-setup - Procedures and macros available in setup scripts - install-extension @subsubsection version @verbatim [extension property] (version STRING) @end verbatim Specifies version string. @node chicken-setup - Procedures and macros available in setup scripts - install-extension - documentation, chicken-setup - Procedures and macros available in setup scripts - install-extension - examples, chicken-setup - Procedures and macros available in setup scripts - install-extension - version, chicken-setup - Procedures and macros available in setup scripts - install-extension @subsubsection documentation @verbatim [extension property] (documentation FILENAME) @end verbatim The filename of a HTML document containing extension-specific documentation. This file should be given in the file-list passed to @code{install-extension} and a link to it will be automatically included in the index page (accessible via @code{chicken-setup -docindex}). @node chicken-setup - Procedures and macros available in setup scripts - install-extension - examples, chicken-setup - Procedures and macros available in setup scripts - install-extension - exports, chicken-setup - Procedures and macros available in setup scripts - install-extension - documentation, chicken-setup - Procedures and macros available in setup scripts - install-extension @subsubsection examples @verbatim [extension property] (examples FILENAME ...) @end verbatim Copies the given files into the examples directory, which is usually @code{$prefix/share/chicken/examples} (equivalent to @code{$CHICKEN_HOME/examples} or @code{(make-pathname (chicken-home) "examples")}). Note that the files listed in this property should not be listed in the normal list of files to install passed to @code{install-extension}. This is the only exception - other files that are installed in the repository must be given in the file list. @node chicken-setup - Procedures and macros available in setup scripts - install-extension - exports, chicken-setup - Procedures and macros available in setup scripts - install-extension - static, chicken-setup - Procedures and macros available in setup scripts - install-extension - examples, chicken-setup - Procedures and macros available in setup scripts - install-extension @subsubsection exports @verbatim [extension property] (exports EXPORT ...) @end verbatim Add export-information to the generated extension-information. @code{EXPORT} may be a symbol naming an exported toplevel variable or a string designating a file with exported variables, as generated by the @code{-emit-exports} option or the @code{emit-exports} declaration specifier. @node chicken-setup - Procedures and macros available in setup scripts - install-extension - static, chicken-setup - Procedures and macros available in setup scripts - install-extension - static-options, chicken-setup - Procedures and macros available in setup scripts - install-extension - exports, chicken-setup - Procedures and macros available in setup scripts - install-extension @subsubsection static @verbatim [extension property] (static STRING) @end verbatim If the extension also provides a static library, then STRING should contain the name of that library. Used by @code{csc} when compiling with the @code{-static-extensions} option. @node chicken-setup - Procedures and macros available in setup scripts - install-extension - static-options, , chicken-setup - Procedures and macros available in setup scripts - install-extension - static, chicken-setup - Procedures and macros available in setup scripts - install-extension @subsubsection static-options @verbatim [extension property] (static-options STRING) @end verbatim Additional options that should be passed to the linker when linking with the static version of an extension (see @code{static} above). Used by @code{csc} when compiling with the @code{-static-extensions} option. All other properties are currently ignored. The @code{FILELIST} argument may also be a single string. @node chicken-setup - Procedures and macros available in setup scripts - install-program, chicken-setup - Procedures and macros available in setup scripts - install-script, chicken-setup - Procedures and macros available in setup scripts - install-extension, chicken-setup - Procedures and macros available in setup scripts @subsection install-program @verbatim [procedure] (install-program ID FILELIST [INFOLIST]) @end verbatim Similar to @code{install-extension}, but installs an executable program in the executable path (usually @code{/usr/local/bin}). @node chicken-setup - Procedures and macros available in setup scripts - install-script, chicken-setup - Procedures and macros available in setup scripts - run, chicken-setup - Procedures and macros available in setup scripts - install-program, chicken-setup - Procedures and macros available in setup scripts @subsection install-script @verbatim [procedure] (install-script ID FILELIST [INFOLIST]) @end verbatim Similar to @code{install-program}, but additionally changes the file permissions of all files in @code{FILELIST} to executable (for installing shell-scripts). @node chicken-setup - Procedures and macros available in setup scripts - run, chicken-setup - Procedures and macros available in setup scripts - compile, chicken-setup - Procedures and macros available in setup scripts - install-script, chicken-setup - Procedures and macros available in setup scripts @subsection run @verbatim [syntax] (run FORM ...) @end verbatim Runs the shell command @code{FORM}, which is wrapped in an implicit @code{quasiquote}. @code{(run (csc ...))} is treated specially and passes @code{-v} (if @code{-verbose} has been given to @code{chicken-setup}) and @code{-feature compiling-extension} options to the compiler. @node chicken-setup - Procedures and macros available in setup scripts - compile, chicken-setup - Procedures and macros available in setup scripts - make, chicken-setup - Procedures and macros available in setup scripts - run, chicken-setup - Procedures and macros available in setup scripts @subsection compile @verbatim [syntax] (compile FORM ...) @end verbatim Equivalent to @code{(run (csc FORM ...))}. @node chicken-setup - Procedures and macros available in setup scripts - make, chicken-setup - Procedures and macros available in setup scripts - patch, chicken-setup - Procedures and macros available in setup scripts - compile, chicken-setup - Procedures and macros available in setup scripts @subsection make @verbatim [syntax] (make ((TARGET (DEPENDENT ...) COMMAND ...) ...) ARGUMENTS) @end verbatim A @emph{make} macro that executes the expressions @code{COMMAND ...}, when any of the dependents @code{DEPENDENT ...} have changed, to build @code{TARGET}. This is the same as the @code{make} extension, which is available separately. For more information, see @uref{http://www.call-with-current-continuation.org/eggs/make.html, make}. @node chicken-setup - Procedures and macros available in setup scripts - patch, chicken-setup - Procedures and macros available in setup scripts - copy-file, chicken-setup - Procedures and macros available in setup scripts - make, chicken-setup - Procedures and macros available in setup scripts @subsection patch @verbatim [procedure] (patch WHICH REGEX SUBST) @end verbatim Replaces all occurrences of the regular expression @code{REGEX} with the string @code{SUBST}, in the file given in @code{WHICH}. If @code{WHICH} is a string, the file will be patched and overwritten. If @code{WHICH} is a list of the form @code{OLD NEW}, then a different file named @code{NEW} will be generated. @node chicken-setup - Procedures and macros available in setup scripts - copy-file, chicken-setup - Procedures and macros available in setup scripts - move-file, chicken-setup - Procedures and macros available in setup scripts - patch, chicken-setup - Procedures and macros available in setup scripts @subsection copy-file @verbatim [procedure] (copy-file FROM TO) @end verbatim Copies the file or directory (recursively) given in the string @code{FROM} to the destination file or directory @code{TO}. @node chicken-setup - Procedures and macros available in setup scripts - move-file, chicken-setup - Procedures and macros available in setup scripts - remove-file*, chicken-setup - Procedures and macros available in setup scripts - copy-file, chicken-setup - Procedures and macros available in setup scripts @subsection move-file @verbatim [procedure] (move-file FROM TO) @end verbatim Moves the file or directory (recursively) given in the string @code{FROM} to the destination file or directory @code{TO}. @node chicken-setup - Procedures and macros available in setup scripts - remove-file*, chicken-setup - Procedures and macros available in setup scripts - find-library, chicken-setup - Procedures and macros available in setup scripts - move-file, chicken-setup - Procedures and macros available in setup scripts @subsection remove-file* @verbatim [procedure] (remove-file* PATH) @end verbatim Removes the file or directory given in the string @code{PATH}. @node chicken-setup - Procedures and macros available in setup scripts - find-library, chicken-setup - Procedures and macros available in setup scripts - find-header, chicken-setup - Procedures and macros available in setup scripts - remove-file*, chicken-setup - Procedures and macros available in setup scripts @subsection find-library @verbatim [procedure] (find-library NAME PROC) @end verbatim Returns @code{#t} if the library named @code{libNAME.[a|so]} (unix) or @code{NAME.lib} (windows) could be found by compiling and linking a test program. @code{PROC} should be the name of a C function that must be provided by the library. If no such library was found or the function could not be resolved, @code{#f} is returned. @node chicken-setup - Procedures and macros available in setup scripts - find-header, chicken-setup - Procedures and macros available in setup scripts - try-compile, chicken-setup - Procedures and macros available in setup scripts - find-library, chicken-setup - Procedures and macros available in setup scripts @subsection find-header @verbatim [procedure] (find-header NAME) @end verbatim Returns @code{#t} if a C include-file with the given name is available, or @code{#f} otherwise. @node chicken-setup - Procedures and macros available in setup scripts - try-compile, chicken-setup - Procedures and macros available in setup scripts - create-directory, chicken-setup - Procedures and macros available in setup scripts - find-header, chicken-setup - Procedures and macros available in setup scripts @subsection try-compile @verbatim [procedure] (try-compile CODE #!key cc cflags ldflags compile-only c++) @end verbatim Returns @code{#t} if the C code in @code{CODE} compiles and links successfully, or @code{#f} otherwise. The keyword parameters @code{cc} (compiler name, defaults to the C compiler used to build this system), @code{cflags} and @code{ldflags} accept additional compilation and linking options. If @code{compile-only} is true, then no linking step takes place. If the keyword argument @code{c++} is given and true, then the code will be compiled in C++ mode. @node chicken-setup - Procedures and macros available in setup scripts - create-directory, chicken-setup - Procedures and macros available in setup scripts - installation-prefix, chicken-setup - Procedures and macros available in setup scripts - try-compile, chicken-setup - Procedures and macros available in setup scripts @subsection create-directory @verbatim [procedure] (create-directory PATH) @end verbatim Creates the directory given in the string @code{PATH}, with all parent directories as needed. @node chicken-setup - Procedures and macros available in setup scripts - installation-prefix, chicken-setup - Procedures and macros available in setup scripts - program-path, chicken-setup - Procedures and macros available in setup scripts - create-directory, chicken-setup - Procedures and macros available in setup scripts @subsection installation-prefix @verbatim [parameter] installation-prefix @end verbatim Holds the prefix under which CHICKEN executables and libraries have been installed (either the value of the environment variable @code{CHICKEN_PREFIX} or whatever prefix was specified at the time the system was built. @node chicken-setup - Procedures and macros available in setup scripts - program-path, chicken-setup - Procedures and macros available in setup scripts - setup-root-directory, chicken-setup - Procedures and macros available in setup scripts - installation-prefix, chicken-setup - Procedures and macros available in setup scripts @subsection program-path @verbatim [parameter] (program-path [PATH]) @end verbatim Holds the path where executables are installed and defaults to either @code{$CHICKEN_PREFIX/bin}, if the environment variable @code{CHICKEN_PREFIX} is set, @code{$CHICKEN_HOME} or the path where the CHICKEN binaries (@code{chicken}, @code{csi}, etc.) are installed. @node chicken-setup - Procedures and macros available in setup scripts - setup-root-directory, chicken-setup - Procedures and macros available in setup scripts - setup-build-directory, chicken-setup - Procedures and macros available in setup scripts - program-path, chicken-setup - Procedures and macros available in setup scripts @subsection setup-root-directory @verbatim [parameter] (setup-root-directory [PATH]) @end verbatim Contains the path of the directory where @code{chicken-setup} was invoked. @node chicken-setup - Procedures and macros available in setup scripts - setup-build-directory, chicken-setup - Procedures and macros available in setup scripts - setup-verbose-flag, chicken-setup - Procedures and macros available in setup scripts - setup-root-directory, chicken-setup - Procedures and macros available in setup scripts @subsection setup-build-directory @verbatim [parameter] (setup-build-directory [PATH]) @end verbatim Contains the path of the directory where the extension is built. This is not necessarily identical to @code{setup-root-directory}. @node chicken-setup - Procedures and macros available in setup scripts - setup-verbose-flag, chicken-setup - Procedures and macros available in setup scripts - setup-install-flag, chicken-setup - Procedures and macros available in setup scripts - setup-build-directory, chicken-setup - Procedures and macros available in setup scripts @subsection setup-verbose-flag @verbatim [parameter] (setup-verbose-flag [BOOL]) @end verbatim Reflects the setting of the @code{-verbose} option, i.e. is @code{#t}, if @code{-verbose} was given. @node chicken-setup - Procedures and macros available in setup scripts - setup-install-flag, chicken-setup - Procedures and macros available in setup scripts - required-chicken-version, chicken-setup - Procedures and macros available in setup scripts - setup-verbose-flag, chicken-setup - Procedures and macros available in setup scripts @subsection setup-install-flag @verbatim [parameter] (setup-install-flag [BOOL]) @end verbatim Reflects the setting of the @code{--no-install} option, i.e. is @code{#f}, if @code{-no-install} was given. @node chicken-setup - Procedures and macros available in setup scripts - required-chicken-version, chicken-setup - Procedures and macros available in setup scripts - required-extension-version, chicken-setup - Procedures and macros available in setup scripts - setup-install-flag, chicken-setup - Procedures and macros available in setup scripts @subsection required-chicken-version @verbatim [procedure] (required-chicken-version VERSION) @end verbatim Signals an error if the version of CHICKEN that this script runs under is lexicographically less than @code{VERSION} (the argument will be converted to a string, first). @node chicken-setup - Procedures and macros available in setup scripts - required-extension-version, chicken-setup - Procedures and macros available in setup scripts - cross-chicken, chicken-setup - Procedures and macros available in setup scripts - required-chicken-version, chicken-setup - Procedures and macros available in setup scripts @subsection required-extension-version @verbatim [procedure] (required-extension-version EXTENSION1 VERSION1 ...) @end verbatim Checks whether the extensions @code{EXTENSION1 ...} are installed and at least of version @code{VERSION1 ...}. The test is made by lexicographically comparing the string-representations of the given version with the version of the installed extension. If one of the listed extensions is not installed, has no associated version information or is of a version older than the one specified. @node chicken-setup - Procedures and macros available in setup scripts - cross-chicken, , chicken-setup - Procedures and macros available in setup scripts - required-extension-version, chicken-setup - Procedures and macros available in setup scripts @subsection cross-chicken @verbatim [procedure] (cross-chicken) @end verbatim Retrusn @code{#t} if this system is configured for cross-compilation or @code{#f} otherwise. @node chicken-setup - Examples for extensions, chicken-setup - chicken-setup reference, chicken-setup - Procedures and macros available in setup scripts, chicken-setup @section Examples for extensions The simplest case is a single file that does not export any syntax. For example ;;;; hello.scm (define (hello name) @verbatim (print "Hello, " name " !") ) @end verbatim We need a @code{.setup} script to build and install our nifty extension: ;;;; hello.setup @table @b @item ; compile the code into a dynamically loadable shared object @item ; (will generate hello.so) @end table (compile -s hello.scm) @table @b @item ; Install as extension library @end table (install-extension 'hello "hello.so") After entering @verbatim $ chicken-setup hello @end verbatim at the shell prompt (and in the same directory where the two files exist), the file @code{hello.scm} will be compiled into a dynamically loadable library. If the compilation succeeds, @code{hello.so} will be stored in the repository, together with a file named @code{hello.setup-info} containing an a-list with metadata. If no extension name is given to @code{chicken-setup}, it will simply execute the first file with the @code{.setup} extension it can find. Use it like any other CHICKEN extension: @verbatim $ csi -q #;1> (require-extension hello) ; loading /usr/local/lib/chicken/1/hello.so ... #;2> (hello "me") Hello, me! #;3> @end verbatim Here we create a simple application: ;;;; hello2.scm (print "Hello, ") (for-each (lambda (x) (printf "~A " x)) (command-line-arguments)) (print "!") We also need a setup script: ;;;; hello2.setup (compile hello2.scm) ; compile `hello2' (install-program 'hello2 "hello2") ; name of the extension and files to be installed To use it, just run @code{chicken-setup} in the same directory: @verbatim $ chicken-setup @end verbatim (Here we omit the extension name) Now the program @code{hello2} will be installed in the same location as the other CHICKEN tools (like @code{chicken}, @code{csi}, etc.), which will normally be @code{/usr/local/bin}. Note that you need write-permissions for those locations and may have to run @code{chicken-setup} with administrative rights. Uninstallation is just as easy: @verbatim $ chicken-setup -uninstall hello2 @end verbatim @code{chicken-setup} provides a @code{make} macro, so build operations can be of arbitrary complexity. When running @code{chicken-setup} with an argument @code{NAME}, for which no associated file @code{NAME.setup}, @code{NAME.egg} or @code{NAME.scm} exists will ask you to download the extension via HTTP from the default URL @uref{http://www.call-with-current-continuation.org/eggs, http://www.call-with-current-continuation.org/eggs}. You can use the @code{-host} option to specify an alternative source location. Extensions that are required to compile and/or use the requested extension are downloaded and installed automatically. If the given extension name contains a path prefix and the @code{-host} option is given, then @code{chicken-setup} can also download and install eggs from an arbitrary HTTP server. Alternatively you can pass a full URL (including the @code{http://} prefix. Note that no dependency checks are done when downloading eggs directly with the URL syntax. Finally a somewhat more complex example: We want to package a syntax extension with additional support code that is to be loaded at run-time of any Scheme code that uses that extension. We create a @emph{glass} lambda, a procedure with free variables that can be manipulated from outside: ;;;; glass.scm (define-macro (glass-lambda llist vars . body) @verbatim ;; Low-level macros are fun! (let ([lvar (gensym)] @end verbatim [svar (gensym)] [x (gensym)] [y (gensym)] [yn (gensym)] ) @verbatim `(let ,(map (lambda (v) (list v #f)) vars) (define (,svar ,x . ,y) @end verbatim (let* ([,yn (pair? ,y)] [,y (and ,yn (car ,y))] ) (case ,x ,@@(map (lambda (v) `([,v] (if ,yn (set! ,v ,y) ,v) ) ) vars) (else (error "variable not found" ,x)) ) ) ) @verbatim (define ,lvar (lambda ,llist ,@@body)) (extend-procedure ,lvar ,svar) ) ) ) @end verbatim Here some support code that needs to be loaded at runtime: ;;;; glass-support.scm (require-extension lolevel) (define glass-lambda-accessor procedure-data) (define (glass-lambda-ref gl v) ((procedure-data gl) v)) (define (glass-lambda-set! gl v x) ((procedure-data gl) v x)) The setup script looks like this: (compile -s glass-support.scm) (install-extension @verbatim 'glass '("glass.scm" "glass-support.so") '((syntax) (require-at-runtime glass-support)) ) @end verbatim The invocation of @code{install-extension} provides the files that are to be copied into the extension repository, and a metadata list that specifies that the extension @code{glass} is a syntax extension and that, if it is declared to be used by other code (either with the @code{require-extension} or @code{require-for-syntax} form), then client code should perform an implicit @code{(require 'glass-support)} at startup. This can be conveniently packaged as an @emph{egg}: @verbatim $ tar cfz glass.egg glass.setup glass.scm glass-support.scm @end verbatim And now we use it: @verbatim $ chicken-setup glass $ csi -quiet #;1> (require-extension glass) ; loading /usr/local/lib/chicken/1/glass.scm ... ; loading /usr/local/lib/chicken/1/glass-support.so ... #;2> (define foo (glass-lambda (x) (y) (+ x y))) #;3> (glass-lambda-set! foo 'y 99) #;4> (foo 33) 132 @end verbatim @node chicken-setup - chicken-setup reference, chicken-setup - Windows notes, chicken-setup - Examples for extensions, chicken-setup @section chicken-setup reference Available options: @table @b @item @code{-h -help} Show usage information and exit. @item @code{-V -version} Display version and exit. @item @code{-R -repository [PATHNAME]} When used without an argument, the path of the extension repository is displayed on standard output. When given an argument, the repository pathname (and the @code{repository-path} parameter) will be set to @code{PATHNAME} for all subsequent operations. The default repository path is the installation library directory (usually @code{/usr/local/lib/chicken}), or (if set) the directory given in the environment variable @code{CHICKEN_REPOSITORY}. @code{PATHNAME} should be an absolute pathname. @item @code{-P -program-path [PATHNAME]} When used without an argument, the path for executables is displayed on standard output. When given an argument, the program path for installing executables and scripts will be set to @code{PATHNAME} for all subsequent operations. @code{PATHNAME} should be an absolute pathname. @item @code{-h -host HOSTNAME[:PORT]} Specifies alternative host for downloading extensions, optionally with a TCP port number (which defaults to 80). @item @code{-u -uninstall EXTENSION} Removes all files that were installed for @code{EXTENSION} from the file-system, together with any metadata that has been stored. @item @code{-l -list [NAME ...]} List all installed extensions or show extension information. @item @code{-r -run FILENAME} Load and execute given file. @item @code{-s -script FILENAME} Executes the given Scheme source file with all remaining arguments and exit. The @emph{she-bang} shell script header is recognized, so you can write Scheme scripts that use @code{chicken-setup} just as with @code{csi}. @item @code{-e -eval EXPRESSION} Evaluates the given expression(s). @item @code{-v -verbose} Display additional debug information. @item @code{-k -keep} Keep temporary files and directories. @item @code{-c -csc-option OPTION} Passes @code{OPTION} as an extra argument to invocations of the compiler-driver (@code{csc}). This works only if @code{csc} is invoked as @code{(run (csc ...))}. @item @code{-d -dont-ask} Do not ask the user before trying to download required extensions. @item @code{-n -no-install} Do not install generated binaries and/or support files. Any invocations of @code{install-program}, @code{install-extension} or @code{install-script} will be be no-ops. @item @code{-i -docindex} Displays the path to the index-page of any installed extension-documentation. If the index page does not exist, it is created. @item @code{-t -test EXTENSION ...} return success if all given extensions are installed @item @code{-ls EXTENSION} List installed files for extension @item @code{-fetch-tree} Download and print the repository catalog @item @code{-t -test} If the extension sources contain a directory named @code{tests} and this directory includes a file named @code{run.scm} then this file is executed (with @code{tests} being the current working directory). @item @code{-tree FILENAME} Download and show the repository catalog @item @code{-svn URL} Fetch extension from @uref{http://subversion.tigris.org, Subversion} repository @item @code{-revision REV} Specifies SVN revision to check out @item @code{-local PATHNAME} Fetch extension from local file @item @code{-destdir PATHNAME} Specify alternative installation prefix (for packaging) @item @code{--} Ignore all following arguments. @end table Note that the options are processed exactly in the order in which they appear in the command-line. @node chicken-setup - Windows notes, chicken-setup - Security, chicken-setup - chicken-setup reference, chicken-setup @section Windows notes @code{chicken-setup} works on Windows, when compiled with Visual C++, but depends on the @code{tar} and @code{gunzip} tools to extract the contents of an egg. The best way is to download an egg either manually (or with @code{chicken-setup -fetch}) and extract its contents with a separate program (like @code{winzip}). the @code{CHICKEN_REPOSITORY} environment variable has to be set (in addition to @code{CHICKEN_HOME}) to a directory where your compiled extensions should be located. The @code{.setup} scripts will not always work under Windows, and the extensions may require libraries that are not provided for Windows or work differently. Under these circumstances it is recommended to perform the required steps to build an extension manually. The required UNIX tools are also available as Windows binaries. Google or ask on the CHICKEN mailing list if you need help locating them. @node chicken-setup - Security, chicken-setup - Other modes if installation, chicken-setup - Windows notes, chicken-setup @section Security When extensions are downloaded and installed one is executing code from potentially compromised systems. This applies also when @code{chicken-setup} executes system tests for required extensions. As the code has been retrieved over the network effectively untrusted code is going to be evaluated. When @code{chicken-setup} is run as @emph{root} the whole system is at the mercy of the build instructions (note that this is also the case every time you install software via @code{sudo make install}, so this is not specific to the CHICKEN extension mechanism). Security-conscious users should never run @code{chicken-setup} as root. A simple remedy is to set the environment variable @code{CHICKEN_REPOSITORY}, which will transparently place the repository at an arbitrary user-selected location. Alternatively obtain write/execute access to the default location of the repository (usually @code{/usr/local/lib/chicken}) to avoid running as root. @node chicken-setup - Other modes if installation, chicken-setup - Linking extensions statically, chicken-setup - Security, chicken-setup @section Other modes if installation It is possible to install extensions directly from a @uref{http://subversion.tigris.org, Subversion} repository or from a local checkout by using the @code{-svn} or @code{-local} options. By using either the @code{svn} client program (which must be installed) or file-system operations all necessary files will be copied into the current directory (creating a subdirectory named @code{EXTENSIONNAME.egg-dir}), built and subsequently installed. Dependency information which is necessary to ensure required extensions are also installed is downloaded automatically. If you have no internet connection or don't want to connect, you can als use a local file containing the necessary dependency information. The @code{-fetch-tree} option retrieves the canonical @emph{repository file} at @uref{http://www.call-with-current-continuation.org/eggs/repository, http://www.call-with-current-continuation.org/eggs/repository}, writing it to stdout. Redirecting this output into a file and passing the file via the @code{-tree} option to @code{chicken-setup} allows you now to use the local repository file: Retrieve complete extension repository (big): @verbatim % cd /opt % svn co @uref{https://galinha.ucpel.tche.br/svn/chicken-eggs, https://galinha.ucpel.tche.br/svn/chicken-eggs} @end verbatim Get your own copy of the repository file: @verbatim % chicken-setup -fetch-tree >~/my-repository-file @end verbatim Now you can install eggs from your local checkout, with full dependency tracking and without being connected to the internet: @verbatim % cd ~/tmp % chicken-setup -local /opt/eggs/chicken-eggs -tree ~/my-repository-file opengl @end verbatim @node chicken-setup - Linking extensions statically, , chicken-setup - Other modes if installation, chicken-setup @section Linking extensions statically The compiler and @ref{chicken-setup, chicken-setup} support statically linked eggs. The general approach is to generate an object file or static library (in addition to the usual shared library) in your @code{.setup} script and install it along with the dynamically loadable extension. The setup properties @code{static} should contain the name of the object file (or static library) to be linked, when @code{csc} gets passed the @code{-static-extensions} option: (compile -s -O2 -d1 my-ext.scm) ; dynamically loadable "normal" version (compile -c -O2 -d1 my-ext -unit my-ext) ; statically linkable version (install-extension @verbatim 'my-ext '("my-ext.so" "my-ext.o") '((static "my-ext.o")) ) @end verbatim Note the use of the @code{-unit} option in the second compilation step: static linking must use static library units. @code{chicken-setup} will perform platform-dependent file-extension translation for the file list, but does currently not do that for the @code{static} extension property. To actually link with the static version of @code{my-ext}, do: @verbatim % csc -static-extensions my-program.scm -uses my-ext @end verbatim The compiler will try to do the right thing, but can not handle all extensions, since the ability to statically link eggs is relatively new. Eggs that support static linking are designated as being able to do so. If you require a statically linkable version of an egg that has not been converted yet, contact the extension author or the CHICKEN mailing list. Previous: @ref{Interface to external functions and variables, Interface to external functions and variables} Next: @ref{Data representation, Data representation} @node Data representation, Bugs and limitations, chicken-setup, Top @chapter Data representation @menu * Data representation - Immediate objects:: * Data representation - Non-immediate objects:: @end menu @emph{Note: In all cases below, bits are numbered starting at 1 and beginning with the lowest-order bit.} There exist two different kinds of data objects in the CHICKEN system: immediate and non-immediate objects. @node Data representation - Immediate objects, Data representation - Non-immediate objects, , Data representation @section Immediate objects Immediate objects are represented by a single machine word, which is usually of 32 bits length, or 64 bits on 64-bit architectures. The immediate objects come in four different flavors: @b{fixnums}, that is, small exact integers, where bit 1 is set to 1. This gives fixnums a range of 31 bits for the actual numeric value (63 bits on 64-bit architectures). @b{characters}, where bits 1-4 are equal to @code{C_CHARACTER_BITS}. The Unicode code point of the character is encoded in bits 9 to 32. @b{booleans}, where bits 1-4 are equal to @code{C_BOOLEAN_BITS}. Bit 5 is one for #t and zero for #f. @b{other values}: the empty list, the value of unbound identifiers, the undefined value (void), and end-of-file. Bits 1-4 are equal to @code{C_SPECIAL_BITS}; bits 5 to 8 contain an identifying number for this type of object. The following constants are defined: @code{C_SCHEME_END_OF_LIST C_SCHEME_UNDEFINED C_SCHEME_UNBOUND C_SCHEME_END_OF_FILE} Collectively, bits 1 and 2 are known as the @emph{immediate mark bits}. When bit 1 is set, the object is a fixnum, as described above. When bit 2 is set, it is an immediate object other than a fixnum. If neither is set, the object is non-immediate, as described below. (By definition, bits 1 and 2 may not both be set.) @node Data representation - Non-immediate objects, , Data representation - Immediate objects, Data representation @section Non-immediate objects Non-immediate objects are blocks of data represented by a pointer into the heap. The pointer's immediate mark bits (bits 1 and 2) must be zero to indicate the object is non-immediate; this guarantees the data block is aligned on a 4-byte boundary, at minimum. Alignment of data words is required on modern architectures anyway, so we get the ability to distinguish between immediate and non-immediate objects for free. The first word of the data block contains a header, which gives information about the type of the object. The header has the size of a machine word, usually 32 bits (64 bits on 64 bit architectures). Bits 1 to 24 contain the length of the data object, which is either the number of bytes in a string (or byte-vector) or the the number of elements for a vector or for a structure type. Bits 25 to 28 contain the type code of the object. Bits 29 to 32 contain miscellaneous flags used for garbage collection or internal data type dispatching. These flags are: @table @b @item C_GC_FORWARDING_BIT Flag used for forwarding garbage collected object pointers. @item C_BYTEBLOCK_BIT Flag that specifies whether this data object contains raw bytes (a string or byte-vector) or pointers to other data objects. @item C_SPECIALBLOCK_BIT Flag that specifies whether this object contains a @emph{special} non-object pointer value in its first slot. An example for this kind of objects are closures, which are a vector-type object with the code-pointer as the first item. @item C_8ALIGN_BIT Flag that specifies whether the data area of this block should be aligned on an 8-byte boundary (floating-point numbers, for example). @end table The actual data follows immediately after the header. Note that block-addresses are always aligned to the native machine-word boundary. Scheme data objects map to blocks in the following manner: @b{pairs}: vector-like object (type bits @code{C_PAIR_TYPE}), where the car and the cdr are contained in the first and second slots, respectively. @b{vectors}: vector object (type bits @code{C_VECTOR_TYPE}). @b{strings}: byte-vector object (type bits @code{C_STRING_TYPE}). @b{procedures}: special vector object (type bits @code{C_CLOSURE_TYPE}). The first slot contains a pointer to a compiled C function. Any extra slots contain the free variables (since a flat closure representation is used). @b{flonums}: a byte-vector object (type bits @code{C_FLONUM_BITS}). Slots one and two (or a single slot on 64 bit architectures) contain a 64-bit floating-point number, in the representation used by the host systems C compiler. @b{symbols}: a vector object (type bits @code{C_SYMBOL_TYPE}). Slots one and two contain the toplevel variable value and the print-name (a string) of the symbol, respectively. @b{ports}: a special vector object (type bits @code{C_PORT_TYPE}). The first slot contains a pointer to a file- stream, if this is a file-pointer, or NULL if not. The other slots contain housekeeping data used for this port. @b{structures}: a vector object (type bits @code{C_STRUCTURE_TYPE}). The first slot contains a symbol that specifies the kind of structure this record is an instance of. The other slots contain the actual record items. @b{pointers}: a special vector object (type bits @code{C_POINTER_TYPE}). The single slot contains a machine pointer. @b{tagged pointers}: similar to a pointer (type bits @code{C_TAGGED_POINTER_TYPE}), but the object contains an additional slot with a tag (an arbitrary data object) that identifies the type of the pointer. Data objects may be allocated outside of the garbage collected heap, as long as their layout follows the above mentioned scheme. But care has to be taken not to mutate these objects with heap-data (i.e. non-immediate objects), because this will confuse the garbage collector. For more information see the header file @code{chicken.h}. Previous: @ref{chicken-setup, chicken-setup} Next: @ref{Bugs and limitations, Bugs and limitations} @node Bugs and limitations, FAQ, Data representation, Top @chapter Bugs and limitations @itemize @item Compiling large files takes too much time. @item If a known procedure has unused arguments, but is always called without those parameters, then the optimizer @emph{repairs} the procedure in certain situations and removes the parameter from the lambda-list. @item @code{port-position} currently works only for input ports. @item Leaf routine optimization can theoretically result in code that thrashes, if tight loops perform excessively many mutations. @end itemize Previous: @ref{Data representation, Data representation} Next: @ref{FAQ, FAQ} @node FAQ, Acknowledgements, Bugs and limitations, Top @chapter FAQ @menu * FAQ - General:: * FAQ - Platform specific:: * FAQ - Customization:: * FAQ - Compiled macros:: * FAQ - Warnings and errors:: * FAQ - Optimizations:: * FAQ - Garbage collection:: * FAQ - Interpreter:: * FAQ - Extensions:: @end menu This is the list of Frequently Asked Questions about Chicken Scheme. If you have a question not answered here, feel free to post to the chicken-users mailing list; if you consider your question general enough, feel free to add it to this list. @node FAQ - General, FAQ - Platform specific, , FAQ @section General @menu * FAQ - General - Why yet another Scheme implementation?:: * FAQ - General - What should I do if I find a bug?:: * FAQ - General - Why are values defined with define-foreign-variable or define-constant or define-inline not seen outside of the containing source file?:: * FAQ - General - How does cond-expand know which features are registered in used units?:: * FAQ - General - Why are constants defined by define-constant not honoured in case constructs?:: * FAQ - General - How can I enable case sensitive reading/writing in user code?:: * FAQ - General - How can I change match-error-control during compilation?:: * FAQ - General - Why doesn't CHICKEN support the full numeric tower by default?:: * FAQ - General - How can I specialize a generic function method to match instances of every class?:: * FAQ - General - Does CHICKEN support native threads?:: @end menu @node FAQ - General - Why yet another Scheme implementation?, FAQ - General - What should I do if I find a bug?, , FAQ - General @subsection Why yet another Scheme implementation? Since Scheme is a relatively simple language, a large number of implementations exist and each has its specific advantages and disadvantages. Some are fast, some provide a rich programming environment. Some are free, others are tailored to specific domains, and so on. The reasons for the existence of CHICKEN are: @itemize @item CHICKEN is portable because it generates C code that runs on a large number of platforms. @item CHICKEN is extendable, since its code generation scheme and runtime system/garbage collector fits neatly into a C environment. @item CHICKEN is free and can be freely distributed, including its source code. @item CHICKEN offers better performance than nearly all interpreter based implementations, but still provides full Scheme semantics. @item As far as we know, CHICKEN is the first implementation of Scheme that uses Henry Baker's @uref{http://home.pipeline.com/~hbaker1/CheneyMTA.html, Cheney on the M.T.A} concept. @end itemize @node FAQ - General - What should I do if I find a bug?, FAQ - General - Why are values defined with define-foreign-variable or define-constant or define-inline not seen outside of the containing source file?, FAQ - General - Why yet another Scheme implementation?, FAQ - General @subsection What should I do if I find a bug? Send e-mail to @uref{mailto:felix@@call-with-current-continuation.org, felix@@call-with-current-continuation.org} with some hints about the problem, like version/build of the compiler, platform, system configuration, code that causes the bug, etc. @node FAQ - General - Why are values defined with define-foreign-variable or define-constant or define-inline not seen outside of the containing source file?, FAQ - General - How does cond-expand know which features are registered in used units?, FAQ - General - What should I do if I find a bug?, FAQ - General @subsection Why are values defined with @code{define-foreign-variable} or @code{define-constant} or @code{define-inline} not seen outside of the containing source file? Accesses to foreign variables are translated directly into C constructs that access the variable, so the Scheme name given to that variable does only exist during compile-time. The same goes for constant- and inline-definitions: The name is only there to tell the compiler that this reference is to be replaced with the actual value. @node FAQ - General - How does cond-expand know which features are registered in used units?, FAQ - General - Why are constants defined by define-constant not honoured in case constructs?, FAQ - General - Why are values defined with define-foreign-variable or define-constant or define-inline not seen outside of the containing source file?, FAQ - General @subsection How does @code{cond-expand} know which features are registered in used units? Each unit used via @code{(declare (uses ...))} is registered as a feature and so a symbol with the unit-name can be tested by @code{cond-expand} during macro-expansion-time. Features registered using the @code{register-feature!} procedure are only available during run-time of the compiled file. You can use the @code{eval-when} form to register features at compile time. @node FAQ - General - Why are constants defined by define-constant not honoured in case constructs?, FAQ - General - How can I enable case sensitive reading/writing in user code?, FAQ - General - How does cond-expand know which features are registered in used units?, FAQ - General @subsection Why are constants defined by @code{define-constant} not honoured in @code{case} constructs? @code{case} expands into a cascaded @code{if} expression, where the first item in each arm is treated as a quoted list. So the @code{case} macro can not infer wether a symbol is to be treated as a constant-name (defined via @code{define-constant}) or a literal symbol. @node FAQ - General - How can I enable case sensitive reading/writing in user code?, FAQ - General - How can I change match-error-control during compilation?, FAQ - General - Why are constants defined by define-constant not honoured in case constructs?, FAQ - General @subsection How can I enable case sensitive reading/writing in user code? To enable the @code{read} procedure to read symbols and identifiers case sensitive, you can set the parameter @code{case-sensitivity} to @code{#t}. @node FAQ - General - How can I change match-error-control during compilation?, FAQ - General - Why doesn't CHICKEN support the full numeric tower by default?, FAQ - General - How can I enable case sensitive reading/writing in user code?, FAQ - General @subsection How can I change @code{match-error-control} during compilation? Use @code{eval-when}, like this: (eval-when (compile) (match-error-control #:unspecified) ) @node FAQ - General - Why doesn't CHICKEN support the full numeric tower by default?, FAQ - General - How can I specialize a generic function method to match instances of every class?, FAQ - General - How can I change match-error-control during compilation?, FAQ - General @subsection Why doesn't CHICKEN support the full numeric tower by default? The short answer: % chicken-setup numbers % csi -q @enumerate @item ;1> (use numbers) @end enumerate The long answer: There are a number of reasons for this: - For most applications of Scheme fixnums (exact word-sized integers) and flonums (64-bit floating-point numbers) are more than sufficient; - Interfacing to C is simpler; - Dispatching of arithmetic operations is more efficient. There is an extension based on the GNU Multiprecision Package that implements most of the full numeric tower, see @uref{http://www.call-with-current-continuation.org/eggs/numbers.html, http://www.call-with-current-continuation.org/eggs/numbers.html}. @node FAQ - General - How can I specialize a generic function method to match instances of every class?, FAQ - General - Does CHICKEN support native threads?, FAQ - General - Why doesn't CHICKEN support the full numeric tower by default?, FAQ - General @subsection How can I specialize a generic function method to match instances of every class? Specializing a method on @code{} doesn't work on primitive data objects like numbers, strings, etc. so for example (define-method (foo (x )) ...) (define-method (foo (x )) ...) (foo 123) will signal an error, because to applicable method can be found. To specialize a method for primitive objects, use @code{}: (define-method (foo (x )) ...) @node FAQ - General - Does CHICKEN support native threads?, , FAQ - General - How can I specialize a generic function method to match instances of every class?, FAQ - General @subsection Does CHICKEN support native threads? Currently native threads are not supported. The runtime system is not reentrant, and the garbage-collection algorithm would be made much more complicated, since the location of every object (whether it is allocated on the stack or on the heap or completely outside the GC-able data space) has to be checked - this would be rather complex and inefficient in a situation where multiple threads are involved. @node FAQ - Platform specific, FAQ - Customization, FAQ - General, FAQ @section Platform specific @menu * FAQ - Platform specific - How do I generate a DLL under MS Windows (tm) ?:: * FAQ - Platform specific - How do I generate a GUI application under Windows(tm)?:: * FAQ - Platform specific - Compiling very large files under Windows with the Microsoft C compiler fails with a message indicating insufficient heap space.:: * FAQ - Platform specific - When I run csi inside an emacs buffer under Windows; nothing happens.:: * FAQ - Platform specific - I load compiled code dynamically in a Windows GUI application and it crashes.:: * FAQ - Platform specific - On Windows; csc.exe seems to be doing something wrong.:: * FAQ - Platform specific - On Windows source and/or output filenames with embedded whitespace are not found.:: @end menu @node FAQ - Platform specific - How do I generate a DLL under MS Windows (tm) ?, FAQ - Platform specific - How do I generate a GUI application under Windows(tm)?, , FAQ - Platform specific @subsection How do I generate a DLL under MS Windows (tm) ? Use @code{csc} in combination with the @code{-dll} option: @code{C:\> csc foo.scm -dll} @node FAQ - Platform specific - How do I generate a GUI application under Windows(tm)?, FAQ - Platform specific - Compiling very large files under Windows with the Microsoft C compiler fails with a message indicating insufficient heap space., FAQ - Platform specific - How do I generate a DLL under MS Windows (tm) ?, FAQ - Platform specific @subsection How do I generate a GUI application under Windows(tm)? Invoke @code{csc} with the @code{-windows} option. Or pass the @code{-DC_WINDOWS_GUI} option to the C compiler and link with the GUI version of the runtime system (that's @code{libchicken-gui[-static].lib}. The GUI runtime displays error messages in a message box and does some rudimentary command-line parsing. @node FAQ - Platform specific - Compiling very large files under Windows with the Microsoft C compiler fails with a message indicating insufficient heap space., FAQ - Platform specific - When I run csi inside an emacs buffer under Windows; nothing happens., FAQ - Platform specific - How do I generate a GUI application under Windows(tm)?, FAQ - Platform specific @subsection Compiling very large files under Windows with the Microsoft C compiler fails with a message indicating insufficient heap space. It seems that the Microsoft C compiler can only handle files up to a certain size, and it doesn't utilize virtual memory as well as the GNU C compiler, for example. Try closing running applications. If that fails, try to break up the Scheme code into several library units. @node FAQ - Platform specific - When I run csi inside an emacs buffer under Windows; nothing happens., FAQ - Platform specific - I load compiled code dynamically in a Windows GUI application and it crashes., FAQ - Platform specific - Compiling very large files under Windows with the Microsoft C compiler fails with a message indicating insufficient heap space., FAQ - Platform specific @subsection When I run @code{csi} inside an emacs buffer under Windows, nothing happens. Invoke @code{csi} with the @code{-:c} runtime option. Under Windows the interpreter thinks it is not running under control of a terminal and doesn't print the prompt and does not flush the output stream properly. @node FAQ - Platform specific - I load compiled code dynamically in a Windows GUI application and it crashes., FAQ - Platform specific - On Windows; csc.exe seems to be doing something wrong., FAQ - Platform specific - When I run csi inside an emacs buffer under Windows; nothing happens., FAQ - Platform specific @subsection I load compiled code dynamically in a Windows GUI application and it crashes. Code compiled into a DLL to be loaded dynamically must be linked with the same runtime system as the loading application. That means that all dynamically loaded entities (including extensions built and installed with @code{chicken-setup}) must be compiled with the @code{-windows} @code{csc} option. @node FAQ - Platform specific - On Windows; csc.exe seems to be doing something wrong., FAQ - Platform specific - On Windows source and/or output filenames with embedded whitespace are not found., FAQ - Platform specific - I load compiled code dynamically in a Windows GUI application and it crashes., FAQ - Platform specific @subsection On Windows, @code{csc.exe} seems to be doing something wrong. The Windows development tools include a C# compiler with the same name. Either invoke @code{csc.exe} with a full pathname, or put the directory where you installed CHICKEN in front of the MS development tool path in the @code{PATH} environment variable. @node FAQ - Platform specific - On Windows source and/or output filenames with embedded whitespace are not found., , FAQ - Platform specific - On Windows; csc.exe seems to be doing something wrong., FAQ - Platform specific @subsection On Windows source and/or output filenames with embedded whitespace are not found. There is no current workaround. Do not use filenames with embedded whitespace for code. However, command names with embedded whitespace will work correctly. @node FAQ - Customization, FAQ - Compiled macros, FAQ - Platform specific, FAQ @section Customization @menu * FAQ - Customization - How do I run custom startup code before the runtime-system is invoked?:: * FAQ - Customization - How can I add compiled user passes?:: @end menu @node FAQ - Customization - How do I run custom startup code before the runtime-system is invoked?, FAQ - Customization - How can I add compiled user passes?, , FAQ - Customization @subsection How do I run custom startup code before the runtime-system is invoked? When you invoke the C compiler for your translated Scheme source program, add the C compiler option @code{-DC_EMBEDDED}, or pass @code{-embedded} to the @code{csc} driver program, so no entry-point function will be generated (@code{main()}). When your are finished with your startup processing, invoke: CHICKEN_main(argc, argv, C_toplevel); where @code{C_toplevel} is the entry-point into the compiled Scheme code. You should add the following declarations at the head of your code: @enumerate @item include "chicken.h" extern void C_toplevel(C_word,C_word,C_word) C_noret; @end enumerate @node FAQ - Customization - How can I add compiled user passes?, , FAQ - Customization - How do I run custom startup code before the runtime-system is invoked?, FAQ - Customization @subsection How can I add compiled user passes? To add a compiled user pass instead of an interpreted one, create a library unit and recompile the main unit of the compiler (in the file @code{chicken.scm}) with an additional @code{uses} declaration. Then link all compiler modules and your (compiled) extension to create a new version of the compiler, like this (assuming all sources are in the current directory): % cat userpass.scm ;;;; userpass.scm - My very own compiler pass (declare (unit userpass)) @table @b @item ; Perhaps more user passes/extensions are added @end table (let ([old (user-pass)]) (user-pass (lambda (x) (let ([x2 (do-something-with x)]) (if old (old x2) x2) ) ) ) ) @verbatim % csc -c -x userpass.scm % csc chicken.scm -c -o chicken-extended.o -uses userpass % gcc chicken-extended.o support.o easyffi.o compiler.o optimizer.o batch-driver.o c-platform.o \ c-backend.o userpass.o `csc -ldflags -libs` -o chicken-extended @end verbatim On platforms that support it (Linux ELF, Solaris, Windows + VC++), compiled code can be loaded via @code{-extend} just like source files (see @code{load} in the User's Manual). @node FAQ - Compiled macros, FAQ - Warnings and errors, FAQ - Customization, FAQ @section Compiled macros @menu * FAQ - Compiled macros - Why is define-macro complaining about unbound variables?:: * FAQ - Compiled macros - Why isn't load properly loading my library of macros?:: * FAQ - Compiled macros - Why is include unable to load my hygienic macros?:: * FAQ - Compiled macros - Why are macros not visible outside of the compilation unit in which they are defined?:: @end menu @node FAQ - Compiled macros - Why is define-macro complaining about unbound variables?, FAQ - Compiled macros - Why isn't load properly loading my library of macros?, , FAQ - Compiled macros @subsection Why is @code{define-macro} complaining about unbound variables? Macro bodies that are defined and used in a compiled source-file are evaluated during compilation and so have no access to anything created with @code{define}. Use @code{define-for-syntax} instead. @node FAQ - Compiled macros - Why isn't load properly loading my library of macros?, FAQ - Compiled macros - Why is include unable to load my hygienic macros?, FAQ - Compiled macros - Why is define-macro complaining about unbound variables?, FAQ - Compiled macros @subsection Why isn't @code{load} properly loading my library of macros? During compile-time, macros are only available in the source file in which they are defined. Files included via @code{include} are considered part of the containing file. @node FAQ - Compiled macros - Why is include unable to load my hygienic macros?, FAQ - Compiled macros - Why are macros not visible outside of the compilation unit in which they are defined?, FAQ - Compiled macros - Why isn't load properly loading my library of macros?, FAQ - Compiled macros @subsection Why is @code{include} unable to load my hygienic macros? It is not sufficient for the included file to require the @code{syntax-case} extension. Call @code{(require-extension syntax-case)} @emph{before} calling @code{include}. @node FAQ - Compiled macros - Why are macros not visible outside of the compilation unit in which they are defined?, , FAQ - Compiled macros - Why is include unable to load my hygienic macros?, FAQ - Compiled macros @subsection Why are macros not visible outside of the compilation unit in which they are defined? Macros are defined during compile time, so when a file has been compiled, the definitions are gone. An exception to this rule are macros defined with @code{define-macro}, which are also visible at run-time, i.e. in @code{eval}. To use macros defined in other files, use the @code{include} special form. @node FAQ - Warnings and errors, FAQ - Optimizations, FAQ - Compiled macros, FAQ @section Warnings and errors @menu * FAQ - Warnings and errors - Why does my program crash when I use callback functions (from Scheme to C and back to Scheme again)?:: * FAQ - Warnings and errors - Why does the linker complain about a missing function _C_..._toplevel?:: * FAQ - Warnings and errors - Why does the linker complain about a missing function _C_toplevel?:: * FAQ - Warnings and errors - Why does my program crash when I compile a file with -unsafe or unsafe declarations?:: * FAQ - Warnings and errors - Why do I get a warning when I define a global variable named match?:: * FAQ - Warnings and errors - Why don't toplevel-continuations captured in interpreted code work?:: * FAQ - Warnings and errors - Why does define-reader-ctor not work in my compiled program?:: * FAQ - Warnings and errors - Why do built-in units; such as srfi-1; srfi-18; and posix fail to load?:: * FAQ - Warnings and errors - How can I increase the size of the trace shown when runtime errors are detected?:: @end menu @node FAQ - Warnings and errors - Why does my program crash when I use callback functions (from Scheme to C and back to Scheme again)?, FAQ - Warnings and errors - Why does the linker complain about a missing function _C_..._toplevel?, , FAQ - Warnings and errors @subsection Why does my program crash when I use callback functions (from Scheme to C and back to Scheme again)? There are two reasons why code involving callbacks can crash out of no apparent reason: @enumerate @item It is important to use @code{foreign-safe-lambda/foreign-safe-lambda*} for the C code that is to call back into Scheme. If this is not done than sooner or later the available stack space will be exhausted. @item If the C code uses a large amount of stack storage, or if Scheme-to-C-to-Scheme calls are nested deeply, then the available nursery space on the stack will run low. To avoid this it might be advisable to run the compiled code with a larger nursery setting, i.e. run the code with @code{-:s...} and a larger value than the default (for example @code{-:s300k}), or use the @code{-nursery} compiler option. Note that this can decrease runtime performance on some platforms. @end enumerate @node FAQ - Warnings and errors - Why does the linker complain about a missing function _C_..._toplevel?, FAQ - Warnings and errors - Why does the linker complain about a missing function _C_toplevel?, FAQ - Warnings and errors - Why does my program crash when I use callback functions (from Scheme to C and back to Scheme again)?, FAQ - Warnings and errors @subsection Why does the linker complain about a missing function @code{_C_..._toplevel}? This message indicates that your program uses a library-unit, but that the object-file or library was not supplied to the linker. If you have the unit @code{foo}, which is contained in @code{foo.o} than you have to supply it to the linker like this (assuming a GCC environment): @code{% csc program.scm foo.o -o program} @node FAQ - Warnings and errors - Why does the linker complain about a missing function _C_toplevel?, FAQ - Warnings and errors - Why does my program crash when I compile a file with -unsafe or unsafe declarations?, FAQ - Warnings and errors - Why does the linker complain about a missing function _C_..._toplevel?, FAQ - Warnings and errors @subsection Why does the linker complain about a missing function @code{_C_toplevel}? This means you have compiled a library unit as an application. When a unit-declaration (as in @code{(declare (unit ...))}) is given, then this file has a specially named toplevel entry procedure. Just remove the declaration, or compile this file to an object-module and link it to your application code. @node FAQ - Warnings and errors - Why does my program crash when I compile a file with -unsafe or unsafe declarations?, FAQ - Warnings and errors - Why do I get a warning when I define a global variable named match?, FAQ - Warnings and errors - Why does the linker complain about a missing function _C_toplevel?, FAQ - Warnings and errors @subsection Why does my program crash when I compile a file with @code{-unsafe} or unsafe declarations? The compiler option @code{-unsafe} or the declaration @code{(declare (unsafe))} disable certain safety-checks to improve performance, so code that would normally trigger an error will work unexpectedly or even crash the running application. It is advisable to develop and debug a program in safe mode (without unsafe declarations) and use this feature only if the application works properly. @node FAQ - Warnings and errors - Why do I get a warning when I define a global variable named match?, FAQ - Warnings and errors - Why don't toplevel-continuations captured in interpreted code work?, FAQ - Warnings and errors - Why does my program crash when I compile a file with -unsafe or unsafe declarations?, FAQ - Warnings and errors @subsection Why do I get a warning when I define a global variable named @code{match}? Even when the @code{match} unit is not used, the macros from that package are visible in the compiler. The reason for this is that macros can not be accessed from library units (only when explicitly evaluated in running code). To speed up macro-expansion time, the compiler and the interpreter both already provide the compiled @code{match-...} macro definitions. Macros shadowed lexically are no problem, but global definitions of variables named identically to (global) macros are useless - the macro definition shadows the global variable. This problem can be solved using a different name or undefining the macro, like this: (eval-when (compile eval) (undefine-macro! 'match)) @node FAQ - Warnings and errors - Why don't toplevel-continuations captured in interpreted code work?, FAQ - Warnings and errors - Why does define-reader-ctor not work in my compiled program?, FAQ - Warnings and errors - Why do I get a warning when I define a global variable named match?, FAQ - Warnings and errors @subsection Why don't toplevel-continuations captured in interpreted code work? Consider the following piece of code: (define k (call-with-current-continuation (lambda (k) k))) (k k) When compiled, this will loop endlessly. But when interpreted, @code{(k k)} will return to the read-eval-print loop! This happens because the continuation captured will eventually read the next toplevel expression from the standard-input (or an input-file if loading from a file). At the moment @code{k} was defined, the next expression was @code{(k k)}. But when @code{k} is invoked, the next expression will be whatever follows after @code{(k k)}. In other words, invoking a captured continuation will not rewind the file-position of the input source. A solution is to wrap the whole code into a @code{(begin ...)} expression, so all toplevel expressions will be loaded together. @node FAQ - Warnings and errors - Why does define-reader-ctor not work in my compiled program?, FAQ - Warnings and errors - Why do built-in units; such as srfi-1; srfi-18; and posix fail to load?, FAQ - Warnings and errors - Why don't toplevel-continuations captured in interpreted code work?, FAQ - Warnings and errors @subsection Why does @code{define-reader-ctor} not work in my compiled program? The following piece of code does not work as expected: (eval-when (compile) (define-reader-ctor 'integer->char integer->char) ) (print #,(integer->char 33)) The problem is that the compiler reads the complete source-file before doing any processing on it, so the sharp-comma form is encountered before the reader-ctor is defined. A possible solution is to include the file containing the sharp-comma form, like this: (eval-when (compile) (define-reader-ctor 'integer->char integer->char) ) (include "other-file") ;;; other-file.scm: (print #,(integer->char 33)) @node FAQ - Warnings and errors - Why do built-in units; such as srfi-1; srfi-18; and posix fail to load?, FAQ - Warnings and errors - How can I increase the size of the trace shown when runtime errors are detected?, FAQ - Warnings and errors - Why does define-reader-ctor not work in my compiled program?, FAQ - Warnings and errors @subsection Why do built-in units, such as srfi-1, srfi-18, and posix fail to load? When you try to @code{use} a built-in unit such as @code{srfi-18}, you may get the following error: @enumerate @item ;1> (use srfi-18) ; loading library srfi-18 ... Error: (load-library) unable to load library srfi-18 "dlopen(libchicken.dylib, 9): image not found" ;; on a Mac "libchicken.so: cannot open shared object file: No such file or directory" ;; Linux @end enumerate Another symptom is that @code{(require 'srfi-18)} will silently fail. This typically happens because the Chicken libraries have been installed in a non-standard location, such as your home directory. The workaround is to explicitly tell the dynamic linker where to look for your libraries: @verbatim export DYLD_LIBRARY_PATH=~/scheme/chicken/lib:$DYLD_LIBRARY_PATH ;; Mac export LD_LIBRARY_PATH=~/scheme/chicken/lib:$LD_LIBRARY_PATH ;; Linux @end verbatim @node FAQ - Warnings and errors - How can I increase the size of the trace shown when runtime errors are detected?, , FAQ - Warnings and errors - Why do built-in units; such as srfi-1; srfi-18; and posix fail to load?, FAQ - Warnings and errors @subsection How can I increase the size of the trace shown when runtime errors are detected? When a runtime error is detected, Chicken will print the last entries from the trace of functions called (unless your executable was compiled with the @code{-no-trace} option. By default, only 16 entries will be shown. To increase this number pass the @code{-:aN} parameter to your executable. @node FAQ - Optimizations, FAQ - Garbage collection, FAQ - Warnings and errors, FAQ @section Optimizations @menu * FAQ - Optimizations - How can I obtain smaller executables?:: * FAQ - Optimizations - How can I obtain faster executables?:: * FAQ - Optimizations - Which non-standard procedures are treated specially when the extended-bindings or usual-integrations declaration or compiler option is used?:: * FAQ - Optimizations - Can I load compiled code at runtime?:: @end menu @node FAQ - Optimizations - How can I obtain smaller executables?, FAQ - Optimizations - How can I obtain faster executables?, , FAQ - Optimizations @subsection How can I obtain smaller executables? If you don't need @code{eval} or the stuff in the @code{extras} library unit, you can just use the @code{library} unit: (declare (uses library)) (display "Hello, world!\n") (Don't forget to compile with the @code{-explicit-use} option) Compiled with Visual C++ this generates an executable of around 240 kilobytes. It is theoretically possible to compile something without the library, but a program would have to implement quite a lot of support code on its own. @node FAQ - Optimizations - How can I obtain faster executables?, FAQ - Optimizations - Which non-standard procedures are treated specially when the extended-bindings or usual-integrations declaration or compiler option is used?, FAQ - Optimizations - How can I obtain smaller executables?, FAQ - Optimizations @subsection How can I obtain faster executables? There are a number of declaration specifiers that should be used to speed up compiled files: declaring @code{(standard-bindings)} is mandatory, since this enables most optimizations. Even if some standard procedures should be redefined, you can list untouched bindings in the declaration. Declaring @code{(extended-bindings)} lets the compiler choose faster versions of certain internal library functions. This might give another speedup. You can also use the the @code{usual-integrations} declaration, which is identical to declaring @code{standard-bindings} and @code{extended-bindings} (note that @code{usual-integrations} is set by default). Declaring @code{(block)} tells the compiler that global procedures are not changed outside the current compilation unit, this gives the compiler some more opportunities for optimization. If no floating point arithmetic is required, then declaring @code{(number-type fixnum)} can give a big performance improvement, because the compiler can now inline most arithmetic operations. Declaring @code{(unsafe)} will switch off most safety checks. If threads are not used, you can declare @code{(disable-interrupts)}. You should always use maximum optimizations settings for your C compiler. Good GCC compiler options on Pentium (and compatible) hardware are: @code{-Os -fomit-frame-pointer -fno-strict-aliasing} Some programs are very sensitive to the setting of the nursery (the first heap-generation). You should experiment with different nursery settings (either by compiling with the @code{-nursery} option or by using the @code{-:s...} runtime option). @node FAQ - Optimizations - Which non-standard procedures are treated specially when the extended-bindings or usual-integrations declaration or compiler option is used?, FAQ - Optimizations - Can I load compiled code at runtime?, FAQ - Optimizations - How can I obtain faster executables?, FAQ - Optimizations @subsection Which non-standard procedures are treated specially when the @code{extended-bindings} or @code{usual-integrations} declaration or compiler option is used? The following standard bindings are handled specially, depending on optimization options and compiler settings: @verbatim @code{+} @code{*} @code{-} @code{/} @code{quotient} @code{eq?} @code{eqv?} @code{equal?} @code{apply} @code{c...r} @code{values} @code{call-with-values} @code{list-ref} @code{null?} @code{length} @code{not} @code{char?} @code{string?} @code{symbol?} @code{vector?} @code{pair?} @code{procedure?} @code{boolean?} @code{number?} @code{complex?} @code{rational?} @code{real?} @code{exact?} @code{inexact?} @code{list?} @code{eof-object?} @code{string-ref} @code{string-set!} @code{vector-ref} @code{vector-set!} @code{char=?} @code{char?} @code{char<=?} @code{char>=?} @code{char-numeric?} @code{char-alphabetic?} @code{char-whitespace?} @code{char-upper-case?} @code{char-lower-case?} @code{char-upcae} @code{char-downcase} @code{list-tail} @code{assv} @code{memv} @code{memq} @code{assoc} @code{member} @code{set-car!} @code{set-cdr!} @code{abs} @code{exp} @code{sin} @code{cos} @code{tan} @code{log} @code{asin} @code{acos} @code{atan} @code{sqrt} @code{zero?} @code{positive?} @code{negative?} @code{vector-length} @code{string-length} @code{char->integer} @code{integer->char} @code{inexact->exact} @code{=} @code{>} @code{<} @code{>=} @code{<=} @code{for-each} @code{map} @code{substring} @code{string-append} @code{gcd} @code{lcm} @code{list} @code{exact->inexact} @code{string->number} @code{number->string} @code{even?} @code{odd?} @code{remainder} @code{floor} @code{ceiling} @code{truncate} @code{round} @code{cons} @code{vector} @code{string} @code{string=?} @code{string-ci=?} @code{make-vector} @code{call-with-current-continuation} @code{write-char} @code{read-string} @end verbatim The following extended bindings are handled specially: @code{bitwise-and} @code{bitwise-ior} @code{bitwise-xor} @code{bitwise-not} @code{bit-set?} @code{add1} @code{sub1} @code{fx+} @code{fx-} @code{fx*} @code{fx/} @code{fxmod} @code{fx=} @code{fx>} @code{fx>=} @code{fixnum?} @code{fxneg} @code{fxmax} @code{fxmin} @code{fxand} @code{fxior} @code{fxxor} @code{fxnot} @code{fxshl} @code{fxshr} @code{flonum?} @code{fp+} @code{fp-} @code{fp*} @code{fp/} @code{atom?} @code{fp=} @code{fp>} @code{fp>=} @code{fpneg} @code{fpmax} @code{fpmin} @code{arithmetic-shift} @code{signum} @code{flush-output} @code{thread-specific} @code{thread-specific-set!} @code{not-pair?} @code{null-list?} @code{print} @code{print*} @code{u8vector->blob/shared} @code{s8vector->blob/shared} @code{u16vector->blob/shared} @code{s16vector->blob/shared} @code{u32vector->blob/shared} @code{s32vector->blob/shared} @code{f32vector->blob/shared} @code{f64vector->blob/shared} @code{block-ref} @code{blob-size} @code{u8vector-length} @code{s8vector-length} @code{u16vector-length} @code{s16vector-length} @code{u32vector-length} @code{s32vector-length} @code{f32vector-length} @code{f64vector-length} @code{u8vector-ref} @code{s8vector-ref} @code{u16vector-ref} @code{s16vector-ref} @code{u32vector-ref} @code{s32vector-ref} @code{f32vector-ref} @code{f64vector-ref} @code{u8vector-set!} @code{s8vector-set!} @code{u16vector-set!} @code{s16vector-set!} @code{u32vector-set!} @code{s32vector-set!} @code{hash-table-ref} @code{block-set!} @code{number-of-slots} @code{first} @code{second} @code{third} @code{fourth} @code{null-pointer?} @code{pointer->object} @code{make-record-instance} @code{locative-ref} @code{locative-set!} @code{locative?} @code{locative->object} @code{identity} @code{cpu-time} @code{error} @code{call/cc} @code{any?} @code{substring=?} @code{substring-ci=?} @code{substring-index} @code{substring-index-ci} @node FAQ - Optimizations - Can I load compiled code at runtime?, , FAQ - Optimizations - Which non-standard procedures are treated specially when the extended-bindings or usual-integrations declaration or compiler option is used?, FAQ - Optimizations @subsection Can I load compiled code at runtime? Yes. You can load compiled at code at runtime with @code{load} just as well as you can load Scheme source code. Compiled code will, of course, run faster. To do this, pass to @code{load} a path for a shared object. Use a form such as @code{(load "foo.so")} and run @code{csc -shared foo.scm} to produce @code{foo.so} from @code{foo.scm} (at which point @code{foo.scm} will no longer be required). @node FAQ - Garbage collection, FAQ - Interpreter, FAQ - Optimizations, FAQ @section Garbage collection @menu * FAQ - Garbage collection - Why does a loop that doesn't cons still trigger garbage collections?:: * FAQ - Garbage collection - Why do finalizers not seem to work in simple cases in the interpeter?:: @end menu @node FAQ - Garbage collection - Why does a loop that doesn't cons still trigger garbage collections?, FAQ - Garbage collection - Why do finalizers not seem to work in simple cases in the interpeter?, , FAQ - Garbage collection @subsection Why does a loop that doesn't @code{cons} still trigger garbage collections? Under CHICKENs implementation policy, tail recursion is achieved simply by avoiding to return from a function call. Since the programs is CPS converted, a continuous sequence of nested procedure calls is performed. At some stage the stack-space has to run out and the current procedure and its parameters (including the current continuation) are stored somewhere in the runtime system. Now a minor garbage collection occurs and rescues all live data from the stack (the first heap generation) and moves it into the the second heap generation. Than the stack is cleared (using a @code{longjmp}) and execution can continue from the saved state. With this method arbitrary recursion (in tail- or non-tail position) can happen, provided the application doesn't run out of heap-space. (The difference between a tail- and a non-tail call is that the tail-call has no live data after it invokes its continuation - and so the amount of heap-space needed stays constant) @node FAQ - Garbage collection - Why do finalizers not seem to work in simple cases in the interpeter?, , FAQ - Garbage collection - Why does a loop that doesn't cons still trigger garbage collections?, FAQ - Garbage collection @subsection Why do finalizers not seem to work in simple cases in the interpeter? Consider the following interaction in CSI: @verbatim #;1> (define x '(1 2 3)) #;2> (define (yammer x) (print x " is dead")) #;3> (set-finalizer! x yammer) (1 2 3) #;4> (gc #t) 157812 #;5> (define x #f) #;6> (gc #t) 157812 #;7> @end verbatim While you might expect objects to be reclaimed and "@emph{(1 2 3) is dead}" printed, it won't happen: the literal list gets held in the interpreter history, because it is the result value of the set-finalizer! call. Running this in a normal program will work fine. When testing finalizers from the interpreter, you might want to define a trivial macro such as @verbatim (define-macro (v x) `(begin (print ,x) (void))) @end verbatim and wrap calls to @code{set-finalizer!} in it. @node FAQ - Interpreter, FAQ - Extensions, FAQ - Garbage collection, FAQ @section Interpreter @menu * FAQ - Interpreter - Does CSI support history and autocompletion?:: * FAQ - Interpreter - Does code loaded with load run compiled or interpreted?:: @end menu @node FAQ - Interpreter - Does CSI support history and autocompletion?, FAQ - Interpreter - Does code loaded with load run compiled or interpreted?, , FAQ - Interpreter @subsection Does CSI support history and autocompletion? CSI doesn't support it natively but it can be activated with the @uref{http://www.call-with-current-continuation.org/eggs/readline.html, http://www.call-with-current-continuation.org/eggs/readline.html} egg. After installing the egg, add the following to your @code{~/.csirc} or equivalent file: ; The regex egg is required for ##csi#name-of-symbols-starting-with (require 'readline) (current-input-port (make-gnu-readline-port)) (gnu-history-install-file-manager (string-append (or (getenv "HOME") ".") "/.csi.history")) Users of *nix-like systems (including Cygwin), may also want to check out @uref{http://utopia.knoware.nl/~hlub/rlwrap/, rlwrap}. This program lets you "wrap" another process (e.g. @code{rlwrap csi}) with the readline library, giving you history, autocompletion, and the ability to set the keystroke set. Vi fans can get vi keystrokes by adding "set editing-mode vi" to their @code{.inputrc} file. @node FAQ - Interpreter - Does code loaded with load run compiled or interpreted?, , FAQ - Interpreter - Does CSI support history and autocompletion?, FAQ - Interpreter @subsection Does code loaded with @code{load} run compiled or interpreted? If you compile a file with a call to @code{load}, the code will be loaded at runtime and, if the file loaded is a Scheme source code file (instead of a shared object), it will be interpreted (even if the caller program is compiled). @node FAQ - Extensions, , FAQ - Interpreter, FAQ @section Extensions @menu * FAQ - Extensions - How can I install Chicken eggs to a non-default location?:: * FAQ - Extensions - Can I install chicken eggs as a non-root user?:: @end menu @node FAQ - Extensions - How can I install Chicken eggs to a non-default location?, FAQ - Extensions - Can I install chicken eggs as a non-root user?, , FAQ - Extensions @subsection How can I install Chicken eggs to a non-default location? You can just set the @code{CHICKEN_REPOSITORY} environment variable. It should contain the path where you want eggs to be installed: @verbatim $ export CHICKEN_REPOSITORY=~/chicken/ $ chicken-setup extensionname @end verbatim In order to make programs (including csi) see these eggs, you should set this variable when you run them. Alternatively, you can call the @code{repository-path} Scheme procedure before loading the eggs, as in: (repository-path "/home/azul/chicken") (use format-modular) Note, however, that using @code{repository-path} as above hard-codes the location of your eggs in your source files. While this might not be an issue in your case, it might be safe to keep this configuration outside of the source code (that is, specifying it as an environment variable) to make it easier to maintain. @node FAQ - Extensions - Can I install chicken eggs as a non-root user?, , FAQ - Extensions - How can I install Chicken eggs to a non-default location?, FAQ - Extensions @subsection Can I install chicken eggs as a non-root user? Yes, just @ref{FAQ - Extensions - How can I install Chicken eggs to a non-default location?, install them in a directory you can write}. Previous: @ref{Bugs and limitations, Bugs and limitations} Next: @ref{Acknowledgements, Acknowledgements} @node Acknowledgements, Bibliography, FAQ, Top @chapter Acknowledgements Many thanks to Nico Amtsberg, William Annis, Marc Baily, Peter Barabas, Jonah Beckford, Arto Bendiken, Peter Bex, Jean-François Bignolles, Dave Bodenstab, Fabian Böhlke, T. Kurt Bond, Ashley Bone, Dominique Boucher, Terence Brannon, Roy Bryant, Adam Buchbinder, Hans Bulfone, Category 5, Taylor Campbell, Franklin Chen, Thomas Chust, Gian Paolo Ciceri, John Cowan, Grzegorz Chrupała, James Crippen, Tollef Fog Heen, Alejandro Forero Cuervo, Linh Dang, Brian Denheyer, dgym, Chris Double, Jarod Eells, Petter Egesund, Steve Elkins, Daniel B. Faken, WIll Farr, Graham Fawcett, Fizzie, Kimura Fuyuki, Tony Garnock-Jones, Martin Gasbichler, Joey Gibson, Stephen C. Gilardi, Joshua Griffith, Johannes Grødem, Damian Gryski, Mario Domenech Goulart, Andreas Gustafsson, Sven Hartrumpf, Jun-ichiro itojun Hagino, Matthias Heiler, Karl M. Hegbloom, William P. Heinemann, Bill Hoffman, Bruce Hoult, Hans Hübner, Markus Hülsmann, Goetz Isenmann, Paulo Jabardo, David Janssens, Christian Jaeger, Dale Jordan, Valentin Kamyshenko, Daishi Kato, Peter Keller, Brad Kind, Ron Kneusel, Matthias Koeppe, Krysztof Kowałczyk, Todd R. Kueny Sr, Goran Krampe, Micky Latowicki, John Lenz, Kirill Lisovsky, Kon Lovett, Dennis Marti, Charles Martin, Bob McIsaac, Alain Mellan, Eric Merrit, Perry Metzger, Scott G. Miller, Mikael, Bruce Mitchener, Chris Moline, Eric E. Moore, Julian Morrison, Dan Muresan, Lars Nilsson, Ian Oversby, o.t., Gene Pavlovsky, Levi Pearson, Nicolas Pelletier, Carlos Pita, Robin Lee Powell, Pupeno, Davide Puricelli, Doug Quale, Eric Raible, Ivan Raikov, Joel Reymont, Andreas Rottman, David Rush, Lars Rustemeier, Daniel Sadilek, Oskar Schirmer, Burton Samograd, Reed Sheridan, Ronald Schröder, Spencer Schumann, Alex Shinn, Ivan Shmakov, Shmul, Tony Sidaway, Jeffrey B. Siegal, Andrey Sidorenko, Michele Simionato, Volker Stolz, Dorai Sitaram, Robert Skeels, Jason Songhurst, Clifford Stein, Sunnan, Zbigniew Szadkowski, Mike Thomas, Minh Thu, Christian Tismer, Andre van Tonder, John Tobey, Henrik Tramberend, Vladimir Tsichevsky, Neil van Dyke, Sander Vesik, Panagiotis Vossos, Shawn Wagner, Peter Wang, Ed Watkeys, Thomas Weidner, Goeran Weinholt, Matthew Welland, Joerg Wittenberger, Peter Wright, Mark Wutka, Richard Zidlicky and Houman Zolfaghari for bug-fixes, tips and suggestions. CHICKEN uses the PCRE regular expression package (@uref{http://www.pcre.org, http://www.pcre.org}), which is written by Philip Hazel. Special thanks to Brandon van Every for contributing the @uref{http://www.cmake.org, CMake} support and for helping with Windows build issues. Also special thanks to Benedikt Rosenau for his constant encouragement. CHICKEN contains code from several people: @table @b @item Eli Barzilay some performance tweaks used in TinyCLOS. @item Mikael Djurfeldt topological sort used by compiler. @item Marc Feeley pretty-printer. @item Aubrey Jaffer implementation of @code{dynamic-wind}. @item Richard O'Keefe sorting routines. @item Olin Shivers implementation of @code{let-optionals[*]} and reference implementations of SRFI-1, SRFI-13 and SRFI-14. @item Andrew Wilcox queues. @item Andrew Wright pattern matcher. @end table Previous: @ref{FAQ, FAQ} Next: @ref{Bibliography, Bibliography} @node Bibliography, , Acknowledgements, Top @chapter Bibliography Henry Baker: @emph{CONS Should Not CONS Its Arguments, Part II: Cheney on the M.T.A.} @uref{http://home.pipeline.com/~hbaker1/CheneyMTA.html, http://home.pipeline.com/~hbaker1/CheneyMTA.html} @emph{Revised^5 Report on the Algorithmic Language Scheme} @uref{http://www.schemers.org/Documents/Standards/R5RS, http://www.schemers.org/Documents/Standards/R5RS} Previous: @ref{Acknowledgements, Acknowledgements} @shortcontents @contents @bye