Chibi-Scheme
Tue Apr 16 06:57:12 2013
Chibi-Scheme is a very small library intended for use as an extension and scripting language in C programs. In addition to support for lightweight VM-based threads, each VM itself runs in an isolated heap allowing multiple VMs to run simultaneously in different OS threads.
The default language is an extended subset of the current draft R7RS Scheme, with support for all libraries. Support for additional languages such as JavaScript, Go, Lua and Bash are planned for future releases. Scheme is chosen as a substrate because its first class continuations and guaranteed tail-call optimization makes implementing other languages easy.
The system is designed in optional layers, beginning with a VM based on a small set of opcodes, a set of primitives implemented in C, a default language, a module system implementation, and a set of standard modules. You can choose whichever layer suits your needs best and customize the rest. Adding your own primitives or wrappers around existing C libraries is easy with the C FFI.
Chibi is known to build and run on 32 and 64-bit Linux, FreeBSD, DragonFly, OS X, iOS, Windows (under Cygwin) and Plan9.
To build, just run "make". This will provide a shared library "libchibi-scheme", as well as a sample "chibi-scheme" command-line repl. The "chibi-scheme-static" make target builds an equivalent static executable. If your make doesn't support GNU make conditionals, then you'll need to edit the top of the Makefile to choose the appropriate settings. On Plan9 just run "mk". You can test the build with "make test".
To install run "make install". If you want to try the executable out without installing, you will probably need to set LD_LIBRARY_PATH, depending on your platform. If you have an old version installed, run "make uninstall" first, or manually delete the directory.
You can edit the file chibi/features.h for a number of settings, mostly disabling features to make the executable smaller. You can specify standard options directly as arguments to make, for example
make CFLAGS=-Os CPPFLAGS=-DSEXP_USE_NO_FEATURES=1
to optimize for size, or
make LDFLAGS=-L/usr/local/lib CPPFLAGS=-I/usr/local/include
to compile against a library installed in /usr/local.
By default Chibi uses a custom, precise, non-moving GC (non-moving is important so you can maintain references from C code). You can link against the Boehm conservative GC by editing the features.h file, or directly from make with:
make SEXP_USE_BOEHM=1
To compile a static executable, use
make chibi-scheme-static SEXP_USE_DL=0
To compile a static executable with all C libraries statically included, first you need to create a clibs.c file, which can be done with:
make clibs.c
or edited manually. Be sure to run this with a non-static chibi-scheme. Then you can make the static executable with:
make -B chibi-scheme-static SEXP_USE_DL=0 CPPFLAGS=-DSEXP_USE_STATIC_LIBS
The include file "chibi/features.h" describes a number of
C preprocessor values which can be enabled or disabled by setting to
1 or 0 respectively. For example, the above commands used the
features SEXP_USE_BOEHM, SEXP_USE_DL and
SEXP_USE_STATIC_LIBS. Many features are still experimental
and may be removed from future releases, but the important features
are listed below.
SEXP_USE_BOEHM- link with the Boehm GC instead of the native Chibi GCSEXP_USE_DL- allow dynamic linking (enabled by default)SEXP_USE_STATIC_LIBS- compile the standard C libs staticallySEXP_USE_MODULES- use the module systemSEXP_USE_GREEN_THREADS- use lightweight threads (enabled by default)SEXP_USE_SIMPLIFY- use a simplification optimizer pass (enabled by default)SEXP_USE_BIGNUMS- use bignums (enabled by default)SEXP_USE_FLONUMS- use flonums (enabled by default)SEXP_USE_RATIOS- use exact ratios (enabled by default)SEXP_USE_COMPLEX- use complex numbers (enabled by default)SEXP_USE_UTF8_STRINGS- Unicode support (enabled by default)SEXP_USE_NO_FEATURES- disable almost all features
The command-line programs chibi-scheme, chibi-doc and
chibi-ffi are installed by default, along with manpages.
chibi-scheme provides a REPL and way to run scripts. In the
interest of size it has no --help option - see the man page for usage.
chibi-doc is the command-line interface to the literate
documentation system described in
(chibi scribble), and used to
build this manual. chibi-ffi is a tool to build wrappers for
C libraries, described in the FFI section below.
The default language is based on the latest draft of
R7RS, which is mostly a
superset of
R5RS.
Some of the more expensive bindings are not included in the interest
of size and quick startup, and some extra low-level utilities are
included for convenience and bootstrapping. Note the builtin
equal? does not support cyclic structures (you need the R7RS
(scheme base) or (chibi equiv)), nor do the default
reader and writer (you need (srfi 38) or the R7RS
(scheme read) and (scheme write)).
To get the exact R7RS language, you can (import (scheme base)),
and likewise for the other R7RS libraries.
The reader defaults to case-sensitive, like R6RS and R7RS but unlike R5RS. The default configuration includes the full numeric tower: fixnums, flonums, bignums, exact rationals and complex numbers.
Full continuations are supported, but currently continuations don't
take C code into account. This means that you can call from Scheme to
C and then from C to Scheme again, but continuations passing through
this chain may not do what you expect. The only higher-order C
functions (thus potentially running afoul of this) in the standard
environment are load and eval. The result of
invoking a continuation created by a different thread is also
currently unspecified.
In R7RS (and R6RS) semantics it is impossible to use two macros from
different modules which both use the same auxiliary keywords (like
else in cond forms) without renaming one of the
keywords. By default Chibi considers all top-level bindings
effectively unbound when matching auxiliary keywords, so this case
will "just work". This decision was made because the chance of
different modules using the same keywords seems more likely than user
code unintentionally matching a top-level keyword with a different
binding, however if you want to use R7RS semantics you can compile
with SEXP_USE_STRICT_TOPLEVEL_BINDINGS=1.
load is extended to accept an optional environment argument, like
eval. You can also load shared libraries in addition to
Scheme source files - in this case the function sexp_init_library is
automatically called with the following signature:
sexp_init_library(sexp context, sexp self, sexp_sint_t n, sexp environment,
const char* version, sexp_abi_identifier_t abi);
The following additional procedures are available in the default environment:
(print-exception exn out)- prints a human-readable description ofexnto the output portout(port-fold-case? port)- returns#tiff the given input port folds case onread(set-port-fold-case! port bool)- set the case-folding behavior ofport(string-concatenate list-of-strings [sep])- append the strings joined bysep
Chibi uses the R7RS module system natively, which is a simple static module system in the style of the Scheme48 module system. As with most features this is optional, and can be ignored or completely disabled at compile time.
Modules names are hierarchical lists of symbols or numbers. A module definition uses the following form:
(define-library (foo bar baz)
<library-declarations> ...)
where <library-declarations> can be any of
(export <id> ...) ;; specify an export list
(import <import-spec> ...) ;; specify one or more imports
(begin <expr> ...) ;; inline Scheme code
(include <file> ...) ;; load one or more files
(include-shared <file> ...) ;; dynamic load a library
<import-spec> can either be a module name or any of
(only <import-spec> <id> ...)
(except <import-spec> <id> ...)
(rename <import-spec> (<from-id> <to-id>) ...)
(prefix <prefix-id> <import-spec>)
These forms perform basic selection and renaming of individual identifiers from the given module. They may be composed to perform combined selection and renaming.
Some modules can be statically included in the initial configuration,
and even more may be included in image files, however in general
modules are searched for in a module load path. The definition of the
module (foo bar baz) is searched for in the file
"foo/bar/baz.sld". The default module path includes the
installed directories, "." and "./lib". Additional
directories can be specified with the command-line options -I
and -A (see the command-line options below) or with the
add-modue-directory procedure at runtime. You can search for
a module file with (find-module-file <file>), or load it with
(load-module-file <file> <env>).
Within the module definition, files are loaded relative to the .sld file, and are written with their extension (so you can use whatever suffix you prefer - .scm, .ss, .sls, etc.).
Shared modules, on the other hand, should be specified without the extension - the correct suffix will be added portably (e.g. .so for Unix and .dylib for OS X).
You may also use cond-expand and arbitrary macro expansions in a
module definition to generate <module-declarations>.
syntax-rules macros are provided by default, with the extensions from
SRFI-46.
In addition, low-level hygienic macros are provided with a
syntactic-closures interface, including sc-macro-transformer,
rsc-macro-transformer, and er-macro-transformer. A good
introduction to syntactic-closures can be found at
http://community.schemewiki.org/?syntactic-closures.
identifier?, identifier->symbol, identifier=?, and
make-syntactic-closure and strip-syntactic-closures are
also available.
You can define new record types with SRFI-9, or inherited record types with SRFI-99. These are just syntactic sugar for the following more primitive type constructors:
(register-simple-type <name-string> <parent> <num-fields>)
=> <type>
(make-type-predicate <opcode-name-string> <type>)
=> <opcode> ; takes 1 arg, returns #t iff that arg is of the type
(make-constructor <constructor-name-string> <type>)
=> <opcode> ; takes 0 args, returns a newly allocated instance of type
(make-getter <getter-name-string> <type> <field-index>)
=> <opcode> ; takes 1 args, retrieves the field located at the index
(make-setter <setter-name-string> <type> <field-index>)
=> <opcode> ; takes 2 args, sets the field located at the index
Chibi supports Unicode strings, encoding them as utf8. This provides easy
interoperability with many C libraries, but means that string-ref and
string-set! are O(n), so they should be avoided in
performance-sensitive code.
In general you should use high-level APIs such as string-map
to ensure fast string iteration. String ports also provide a simple
way to efficiently iterate and construct strings, by looping over an
input string or accumulating characters in an output string.
The in-string and in-string-reverse iterators in the
(chibi loop) module will also iterate over strings
efficiently while hiding the low-level details.
In the event that you do need a low-level interface, such as when writing your own iterator protocol, you should use the following string cursor API instead of indexes.
(string-cursor-start str)returns a start cursor for the string
(string-cursor-end str)returns a cursor one past the last valid cursor
(string-cursor-ref str cursor)get the char at the given cursor
(string-cursor-next str cursor)increment to the next cursor
(string-cursor-prev str cursor)decrement to the previous cursor
(substring-cursor str cs1 [cs2])take a substring from the given cursors
(string-cursor<? cs1 cs2)cs1 is before cs2
(string-cursor<=? cs1 cs2)cs1 is before or the same as cs2
(string-cursor=? cs1 cs2)cs1 is the same as cs2
(string-cursor>? cs1 cs2)cs1 is after cs2
(string-cursor>=? cs1 cs2)cs1 is the same or after cs2
To use Chibi-Scheme in a program you need to link against the "libchibi-scheme" library and include the "eval.h" header file:
#include <chibi/eval.h>
All definitions begin with a "sexp_" prefix, or "SEXP_" for constants. In addition to the prototypes and utility macros, this includes the following type definitions:
sexp- an s-expression, used to represent all Scheme objectssexp_uint_t- an unsigned integer using as many bits as sexpsexp_sint_t- a signed integer using as many bits as sexp
A simple program might look like:
void dostuff(sexp ctx) {
/* declare and preserve local variables *
sexp_gc_var2(obj1, obj2);
sexp_gc_preserve2(ctx, obj1, obj2);
/* load a file containing Scheme code *
obj1 = sexp_c_string(ctx, "/path/to/source/file.scm", -1);
sexp_load(ctx, obj1, NULL);
/* eval a C string as Scheme code *
sexp_eval_string(ctx, "(some scheme expression)", -1, NULL);
/* construct a Scheme expression to eval *
obj1 = sexp_intern(ctx, "my-procedure", -1);
obj2 = sexp_cons(ctx, obj1, SEXP_NULL);
sexp_eval(ctx, obj2, NULL);
/* release the local variables *
sexp_gc_release2(ctx);
}
int main(int argc, char** argv) {
sexp ctx;
ctx = sexp_make_eval_context(NULL, NULL, NULL, 0, 0);
sexp_load_standard_env(ctx, NULL, SEXP_SEVEN);
sexp_load_standard_ports(ctx, NULL, stdin, stdout, stderr, 0);
dostuff(ctx);
sexp_destroy_context(ctx);
}
Looking at main, sexp_make_eval_context and
sexp_destroy_context create and destroy a "context", which
manages the heap and VM state. The meaning of the arguments is
explained in detail below, but these values will give reasonable
defaults, in this case constructing an environment with the core
syntactic forms, opcodes, and standard C primitives.
This is still a fairly bare environment, so we call
sexp_load_standard_env to find and load the default
initialization file.
The resulting context can then be used to construct objects, call
functions, and most importantly evaluate code, as is done in
dostuff. The default garbage collector for Chibi is precise,
which means we need to declare and preserve references to any
temporary values we may generate, which is what the
sexp_gc_var2, sexp_gc_preserve2 and
sexp_gc_release2 macros do (there are similar macros for
values 1-6). Precise GCs prevent a class of memory leaks (and
potential attackes based thereon), but if you prefer convenience then
Chibi can be compiled with a conservative GC and you can ignore these.
The interesting part is then the calls to sexp_load,
eval_string and eval which evaluate code stored in
files, C strings, or represented as s-expressions respectively.
Destroying a context runs any finalizers for all objects in the heap and then frees the heap memory (but has no effect on other contexts you or other users of the library may have created).
Contexts represent the state needed to perform evaluation. This includes
keeping track of the heap (when using precise GC), a default environment,
execution stack, and any global values. A program being evaluated in one
context may spawn multiple child contexts, such as when you call eval,
and each child will share the same heap and globals. When using multiple
interpreter threads, each thread has its own context.
You can also create independent contexts with their own separate heaps. These can run simultaneously in multiple OS threads without any need for synchronization.
sexp_make_context(sexp ctx, size_t size, size_t max_size)Creates a new context object. The context has no associated environment, and so cannot be used for evaluation, but can be used to construct Scheme objects and call primitive C functions on them. If
ctxis non-NULL it becomes the "parent" context. The resulting context will share the same heap as its parent, and when using a precise GC preserve any variables preserved by the parent, but the parent will not preserve the child context by default. Typically you either preserve the child manually or use it to perform a single sub-task then discard it and return to using only the parent. Otherwise, a new heap is allocated withsizebytes, expandable to a maximum ofmax_sizebytes, using the system defaults if either is 0.sexp_make_eval_context(sexp ctx, sexp stack, sexp env, sexp_uint_t size, sexp_uint_t max_size)Similar to sexp_make_context, but also associates a stack, environment, and additional globals necessary to evaluate code. Either or both of
stackandenvmay be NULL, in which case defaults will be generated. The default environment includes the compiled-in C primitives, as well as the 10 core forms:define,set!,lambda,if,begin,quote,syntax-quote,define-syntax,let-syntax, andletrec-syntax.sexp_load_standard_env(sexp ctx, sexp env, sexp version)Loads the standard parameters for
env, constructs the feature list from pre-compiled defaults, and loads the installed initialization file forversion, which should be the valueSEXP_SEVEN. Also creates aninteraction-environmentparameter and setsenvitself to that.sexp_load_standard_ports(sexp ctx, sexp env, FILE* in, FILE* out, FILE* err, int leave_open)Creates
current-input-port,current-output-port, andcurrent-error-portparameters fromin,outanderr, and binds them inenv. IfenvisNULL the default context environment is used. Any of theFILE*may beNULL , in which case the corresponding port is not set. Ifleave_openis true, then the underlyingFILE*is left open after the Scheme port is closed, otherwise they are both closed together.sexp_load(sexp ctx, sexp file, sexp env)Searches the installation path for the
fileand loads it in the environmentenv.filemay be a dynamic library or source code.sexp_eval(sexp ctx, sexp obj, sexp env)Evaluates
objas a source form in the environmentenvand returns the result.sexp_eval_string(sexp ctx, const char* str, int len, sexp env)Reads a s-expression from the C string
str(or the firstlenbytes iflenis non-negative), evaluates the resulting form in the environmentenv, and returns the result.sexp_apply(sexp ctx, sexp proc, sexp args)Applies the procedure
procto the arguments in the listargsand returns the result.sexp_context_env(sexp ctx)Returns the current default environment associated with the context
ctx.sexp_env_define(sexp ctx, sexp env, sexp sym, sexp val)Adds a new binding for
syminenvwith valueval.sexp_env_ref(sexp env, sexp sym, sexp dflt)Returns the current binding of
syminenv, ordfltif there is no binding.sexp_parameter_ref(sexp ctx, sexp param)Returns the current dynamic value of the parameter
paramin the given context.
Chibi uses a precise garbage collector by default, which means when performing multiple computations on the C side you must explicitly preserve any temporary values. You can declare variables to be preserved with sexp_gc_varn, for n from 1 to 6.
sexp_gc_varn(obj1, obj2, ..., objn)
This is equivalent to the declaration
sexp obj1, obj2, ..., objn;
except it makes preservation possible. Because it is a declaration it must occur at the beginning of your function, and because it includes assignments (in the macro-expanded form) it should occur after all other declarations.
To preserve these variables for a given context, you can then use sexp_gc_preserven:
sexp_gc_preserven(ctx, obj1, obj2, ..., objn)
This can be delayed in your code until you know a potentially memory-allocating computation will be performed, but once you call sexp_gc_preserven it must be paired with a matching sexp_gc_releasen:
sexp_gc_releasen(ctx);
Note each of these have different signatures. sexp_gc_varn just lists the variables to be declared. sexp_gc_preserven prefixes these with the context in which they are to be preserved, and sexp_gc_releasen just needs the context.
A typical usage for these is:
sexp foo(sexp ctx, sexp bar, sexp baz) {
/* variable declarations *
int i, j;
...
sexp_gc_var3(tmp1, tmp2, res);
/* asserts or other shortcut returns *
sexp_assert_type(ctx, sexp_barp, SEXP_BAR, bar);
sexp_assert_type(ctx, sexp_bazp, SEXP_BAZ, baz);
/* preserve the variables in ctx *
sexp_gc_preserve3(ctx, tmp1, tmp2, res);
/* perform your computations *
tmp1 = ...
tmp2 = ...
res = ...
/* release before returning *
sexp_gc_release3(ctx);
return res;
}
If compiled with the Boehm GC, sexp_gc_varn just translates to the plain declaration, while sexp_gc_preserven and sexp_gc_releasen become noops.
When interacting with a garbage collection system from another
language, or communicating between different Chibi managed heaps, you
may want to manually ensure objects are preserved irrespective of any
references to it from other objects in the same heap. This can be
done with the sexp_preserve_object and
sexp_release_object utilities.
sexp_preserve_object(ctx, obj)
Increment the absolute reference count for obj. So long as the
reference count is above 0, obj will not be reclaimed even if
there are no references to it from other object in the Chibi managed
heap.
sexp_release_object(ctx, obj)
Decrement the absolute reference count for obj.
The sexp represents different Scheme types with the use of tag bits for so-called "immediate" values, and a type tag for heap-allocated values. The following predicates can be used to distinguish these types. Note the predicates in C all end in "p". For efficiency they are implemented as macros, and so may evaluate their arguments multiple times.
sexp_booleanp(obj)-objis#tor#fsexp_fixnump(obj)-objis an immediate integersexp_flonump(obj)-objis an inexact realsexp_bignump(obj)-objis a heap-allocated integersexp_integerp(obj)-objis an integersexp_numberp(obj)-objis any kind of numbersexp_charp(obj)-objis a charactersexp_stringp(obj)-objis a stringsexp_symbolp(obj)-objis a symbolsexp_idp(obj)-objis a symbol or hygienic identifiersexp_nullp(obj)-objis the null valuesexp_pairp(obj)-objis a pairsexp_vectorp(obj)-objis a vectorsexp_iportp(obj)-objis an input portsexp_oportp(obj)-objis an output portsexp_portp(obj)-objis any kind of portsexp_procedurep(obj)-objis a proceduresexp_opcodep(obj)-objis a primitive opcodesexp_applicablep(obj)-objis valid as the first arg to applysexp_typep(obj)-objis a typesexp_exceptionp(obj)-objis an exceptionsexp_contextp(obj)-objis a contextsexp_envp(obj)-objis an environmentsexp_corep(obj)-objis a special formsexp_macrop(obj)-objis a macrosexp_synclop(obj)-objis a syntactic closuresexp_bytecodep(obj)-objis compiled bytecodesexp_cpointerp(obj)-objis an opaque C pointer
The following shortcuts for various immediate values are available.
SEXP_FALSE- the false booleanSEXP_TRUE- the true booleanSEXP_NULL- the empty listSEXP_EOF- the end-of-file objectSEXP_VOID- an undefined value often returned by mutatorsSEXP_ZERO- shortcut for sexp_make_fixnum(0)- ...
SEXP_TEN- shortcut for sexp_make_fixnum(10)SEXP_NEG_ONE- shortcut for sexp_make_fixnum(-1)
The following macros provide access to the different components of the Scheme types. They do no type checking, essentially translating directly to pointer offsets, so you should be sure to use the above predicates to check types first. They only evaluate their arguments once.
sexp_make_boolean(n)-#fifnis 0,#totherwisesexp_unbox_boolean(obj)- 1 ifobjis#t, 0 otherwisesexp_make_fixnum(n)- creates a new fixnum representing intnsexp_unbox_fixnum(obj)- converts a fixnum to a C integersexp_make_character(ch)- creates a new character representing charchsexp_unbox_character(obj)- converts a character to a C charsexp_car(pair)- the car ofpairsexp_cdr(pair)- the cdr ofpairsexp_ratio_numerator(q)- the numerator of the ratioqsexp_ratio_denominator(q)- the denominator of the ratioqsexp_complex_real(z)- the real part of the complexzsexp_complex_imag(z)- the imaginary part of the complexzsexp_string_length(str)- the byte length ofstras an intsexp_string_ref(str, i)- thei'th byte of stringstrsexp_string_set(str, i, ch)- set thei'th byte of stringstrsexp_vector_length(vec)- the length ofvecas an intsexp_vector_ref(vec, i)- thei'th object of vectorvecsexp_vector_set(vec, i, obj)- set thei'th object of vectorvecsexp_bytes_length(bv)- the number of bytes in bytevectorbvsexp_bytes_ref(bv, i)- thei'th byte of bytevectorbvsexp_bytes_set(bv, i, k)- set thei'th byte of bytevectorbv
Constructors allocate memory and so must be passed a context argument. Any of these may fail and return the OOM exception object.
sexp_cons(sexp ctx, sexp obj1, sexp obj2)- create a new pair whose car isobj1and whose cdr isobj2sexp_list1(sexp ctx, sexp obj)- alias for sexp_cons(ctx, obj, SEXP_NULL)sexp_list2(sexp ctx, sexp obj1, sexp obj2)- create a list of two elementssexp_make_string(sexp ctx, sexp len, sexp ch)- create a new Scheme string oflencharacters, all initialized tochsexp_c_string(sexp ctx, const char* str, int len)- create a new Scheme string copying the firstlencharacters of the C stringstr. Iflenis -1, uses strlen(str).sexp_intern(sexp ctx, const char* str, int len)- interns a symbol from the firstlencharacters of the C stringstr. Iflenis -1, uses strlen(str).sexp_make_vector(sexp ctx, sexp len, sexp obj)- create a new vector oflenelements, all initialized toobjsexp_make_integer(sexp ctx, sexp_sint_t n)- create an integer, heap allocating as a bignum if neededsexp_make_unsigned_integer(sexp ctx, sexp_uint_t n)- create an unsigned integer, heap allocating as a bignum if needed
sexp_read(sexp ctx, sexp in)- read a single datum from portinsexp_write(sexp ctx, sexp obj, sexp out)- writeobjto portoutsexp_write_string(sexp ctx, char* str, sexp out)- write the characters instrto portoutsexp_display(sexp ctx, sexp obj, sexp out)- displayobjto portoutsexp_newline(sexp ctx, sexp out)- write a newline to portoutsexp_print_exception(sexp ctx, sexp exn, sexp out)- print an error message forexnto portoutsexp_current_input_port(sexp ctx)- thecurrent-input-portsexp_current_output_port(sexp ctx)- thecurrent-output-portsexp_current_error_port(sexp ctx)- thecurrent-error-portsexp_debug(sexp ctx, char* msg, sexp obj)- writeobjwith a debug message prefix tocurrent-error-portsexp_read_from_string(sexp ctx, char* str, int len)- read a single datum fromstr, using at mostlenbytes iflenis non-negativesexp_write_to_string(sexp ctx, sexp obj)- return a Scheme string representation ofobj
sexp_equalp(sexp ctx, sexp x, sexp y)-equal?sexp_length(sexp ctx, sexp ls)-lengthsexp_listp(sexp ctx, sexp x)-list?sexp_memq(sexp ctx, sexp x, sexp ls)-memqsexp_assq(sexp ctx, sexp x, sexp ls)-assqsexp_reverse(sexp ctx, sexp ls)-reversesexp_nreverse(sexp ctx, sexp ls)-reverse!sexp_append2(sexp ctx, sexp ls)-appendfor two argumentssexp_copy_list(sexp ctx, sexp ls)- return a shallow copy oflssexp_list_to_vector(sexp ctx, sexp ls)-list->vectorsexp_symbol_to_string(sexp ctx, sexp sym)-symbol->stringsexp_string_to_symbol(sexp ctx, sexp str)-string->symbolsexp_string_to_number(sexp ctx, sexp str)-string->number
You can add your own types and primitives with the following functions.
sexp sexp_define_foreign(sexp ctx, sexp env, const char* name, int num_args, sexp_proc1 func)Defines a new primitive procedure with the name
namein the environmentenv. The procedure takesnum_argsarguments and passes them to the C functionfunc. The C function must take the standard calling convention:sexp func(sexp ctx, sexp self, sexp n, sexp arg1, ..., sexp argnum_args)wherectxis the current context,selfis the procedure itself, andnis the number of arguments passed.funcis responsible for checking its own argument types.sexp sexp_define_foreign_opt(sexp ctx, sexp env, const char* name, int num_args, sexp_proc1 func, sexp dflt)Equivalent to
sexp_define_foreign, except the final argument is optional and defaults to the valuedflt.sexp sexp_define_foreign_param(sexp ctx, sexp env, const char* name, int num_args, sexp_proc1 func, const char* param)Equivalent to
sexp_define_foreign_opt, except instead of a fixed default argumentparamshould be the name of a parameter bound inenv.sexp sexp_register_simple_type(sexp ctx, sexp name, sexp parent, sexp slots)Defines a new simple record type having
slotsnew slots in addition to any inherited from the parent typeparent. Ifparentis false, inherits from the defaultobjectrecord type.
See the C FFI for an easy way to automate adding bindings for C functions.
The "chibi-ffi" script reads in the C function FFI definitions from an input file and outputs the appropriate C wrappers into a file with the same base name and the ".c" extension. You can then compile that C file into a shared library:
chibi-ffi file.stub
cc -fPIC -shared file.c -lchibi-scheme
(or using whatever flags are appropriate to generate shared libs on
your platform) and the generated .so file can be loaded directly with
load, or portably using (include-shared "file") in a
module definition (note that include-shared uses no suffix).
The goal of this interface is to make access to C types and functions easy, without requiring the user to write any C code. That means the stubber needs to be intelligent about various C calling conventions and idioms, such as return values passed in actual parameters. Writing C by hand is still possible, and several of the core modules provide C interfaces directly without using the stubber.
(c-include header)- includes the fileheader(c-system-include header)- includes the system fileheader(c-declare args ...)- outputsargsdirectly in the top-level C source(c-init args ...)- evaluatesargsas C code after all other library initializations have been performed, withctx andenv in scope
C structs can be bound as Scheme types with the
define-c-struct form:
(define-c-struct struct_name
[predicate: predicate-name]
[constructor: constructor-name]
[finalizer: c_finalizer_name]
(type c_field_name getter-name setter-name) ...)
struct_name should be the name of a C struct type. If provided,
predicate-name is bound to a procedure which takes one object
and returns #t iff the object is of type struct_name.
If provided, constructor-name is bound to a procedure of zero
arguments which creates and returns a newly allocated instance of the
type.
If a finalizer is provided, c_finalizer_name must be a C
function which takes one argument, a pointer to the struct, and
performs any cleanup or freeing of resources necessary.
The remaining slots are similar to the
SRFI-9 syntax,
except they are prefixed with a C type (described below). The
c_field_name should be a field name of struct_name.
getter-name will then be bound to a procedure of one argument, a
type, which returns the given field. If provided,
setter-name will be bound to a procedure of two arguments to
mutate the given field.
The variants define-c-class and define-c-union take
the same syntax but define types with the class and
union keywords respectively. define-c-type just
defines accessors to an opaque type without any specific struct-like
keyword.
;; Example: the struct addrinfo returned by getaddrinfo.
(c-system-include "netdb.h")
(define-c-struct addrinfo
finalizer: freeaddrinfo
predicate: address-info?
(int ai_family address-info-family)
(int ai_socktype address-info-socket-type)
(int ai_protocol address-info-protocol)
((link sockaddr) ai_addr address-info-address)
(size_t ai_addrlen address-info-address-length)
((link addrinfo) ai_next address-info-next))
C functions are defined with:
(define-c return-type name-spec (arg-type ...))
where name-space is either a symbol name, or a list of
(scheme-name c_name). If just a symbol is used, the C name
is generated automatically by replacing any dashes (-) in the Scheme
name with underscores (_).
Each arg-type is a type suitable for input validation and
conversion as discussed below.
;; Example: define connect(2) in Scheme
(define-c int connect (int sockaddr int))
Constants can be defined with:
(define-c-const type name-space)
where name-space is the same form as in define-c. This
defines a Scheme variable with the same value as the C constant.
;; Example: define address family constants in Scheme
(define-c-const int (address-family/unix "AF_UNIX"))
(define-c-const int (address-family/inet "AF_INET"))
voidbooleancharsexp(no conversions)
signed-charshortintlongunsigned-charunsigned-shortunsigned-intunsigned-longsize_tpid_tuid_tgid_ttime_t(in seconds, but using the chibi epoch of 2010/01/01)errno(as a return type returns#fon error)
floatdoublelong-double
string- a null-terminated char*env-string- aVAR=VALUEstring represented as a(VAR . VALUE)pair in Scheme(array char)is equivalent tostring
input-portoutput-port
Struct types are by default just referred to by the bare
struct_name from define-c-struct, and it is assumed you
want a pointer to that type. To refer to the full struct, use the
struct modifier, as in (struct struct-name).
Any type may also be written as a list of modifiers followed by the type itself. The supported modifiers are:
constPrepends the "const" C type modifier. As a return or result parameter, makes non-immediates immutable.
freeIt's Scheme's responsibility to "free" this resource. As a return or result parameter, registers the freep flag this causes the type finalizer to be run when GCed.
maybe-nullThis pointer type may be NULL. As a result parameter, NULL is translated to #f normally this would just return a wrapped NULL pointer. As an input parameter, #f is translated to NULL normally this would be a type error.
pointerCreate a pointer to this type. As a return parameter, wraps the result in a vanilla cpointer. As a result parameter, boxes then unboxes the value.
referenceA stack-allocated pointer to this type. As a result parameter, passes a stack-allocated pointer to the value, then returns the dereferenced pointer.
structTreat this struct type as a struct, not a pointer. As an input parameter, dereferences the pointer. As a type field, indicates a nested struct.
linkAdd a gc link. As a field getter, link to the parent object, so the parent won't be GCed so long as we have a reference to the child. This behavior is automatic for nested structs.
resultReturn a result in this parameter. If there are multiple results (including the return type), they are all returned in a list. If there are any result parameters, a return type of errno returns #f on failure, and as eliminated from the list of results otherwise.
(value <expr>)Specify a fixed value. As an input parameter, this parameter is not provided in the Scheme API but always passed as <expr>.
(default <expr>)Specify a default value. As the final input parameter, makes the Scheme parameter optional, defaulting to <expr>.
(array <type> [<length>])An array type. Length must be specified for return and result parameters. If specified, length can be either an integer, indicating a fixed size, or the symbol null, indicating a NULL-terminated array.
A number of SRFIs are provided in the default installation. Note that SRFIs 0, 6, 23, 46 and 62 are built into the default environment so there's no need to import them. SRFI 22 is available with the "-r" command-line option. This list includes popular SRFIs or SRFIs used in standard Chibi modules
- (srfi 0) - cond-expand
- (srfi 1) - list library
- (srfi 2) - and-let*
- (srfi 6) - basic string ports
- (srfi 8) - receive
- (srfi 9) - define-record-type
- (srfi 11) - let-values/let*-values
- (srfi 16) - case-lambda
- (srfi 18) - multi-threading support
- (srfi 22) - running scheme scripts on Unix
- (srfi 23) - error reporting mechanism
- (srfi 26) - cut/cute partial application
- (srfi 27) - sources of random bits
- (srfi 33) - bitwise operators
- (srfi 38) - read/write shared structures
- (srfi 39) - parameter objects
- (srfi 46) - basic syntax-rules extensions
- (srfi 55) - require-extension
- (srfi 62) - s-expression comments
- (srfi 69) - basic hash tables
- (srfi 95) - sorting and merging
- (srfi 98) - environment access
- (srfi 99) - ERR5RS records
Additional non-standard modules are put in the (chibi) module
namespace.
- (chibi ast) - Abstract Syntax Tree and other internal data types
- (chibi config) - General configuration management
- (chibi disasm) - Disassembler for the virtual machine
- (chibi equiv) - A version of
equal?which is guaranteed to terminate - (chibi filesystem) - Interface to the filesystem and file descriptor objects
- (chibi generic) - Generic methods for CLOS-style object oriented programming
- (chibi heap-stats) - Utilities for gathering statistics on the heap
- (chibi io) - Various I/O extensions and custom ports
- (chibi loop) - Fast and extensible loop syntax
- (chibi match) - Intuitive and widely supported pattern matching syntax
- (chibi mime) - Parse MIME files into SXML
- (chibi modules) - Introspection for the module system itself
- (chibi net) - Simple networking interface
- (chibi pathname) - Utilities to decompose and manipulate pathnames
- (chibi process) - Interface to spawn processes and handle signals
- (chibi repl) - A full-featured Read/Eval/Print Loop
- (chibi scribble) - A parser for the scribble syntax used to write this manual
- (chibi stty) - A high-level interface to ioctl
- (chibi system) - Access to the host system and current user information
- (chibi test) - A simple unit testing framework
- (chibi time) - An interface to the current system time
- (chibi trace) - A utility to trace procedure calls
- (chibi type-inference) - An easy-to-use type inference system
- (chibi uri) - Utilities to parse and construct URIs
- (chibi weak) - Data structures with weak references