@c EN
\input texinfo    @c -*- mode: texinfo; coding: utf-8; -*-
@c JP
\input texinfo-ja @c -*- mode: texinfo; coding: utf-8; -*-
@c COMMON
@comment %**start of header
@documentencoding UTF-8
@c EN
@documentlanguage en
@setfilename gauche-deve.info
@settitle Gauche Developers' Reference
@dircategory The Algorithmic Language Scheme
@direntry
* Gauche Developers' Reference: (gauche-deve.info).	Internals of Gauche
@end direntry
@c JP
@documentlanguage ja
@setfilename gauche-devj.info
@settitle Gauche Developers' Reference
@dircategory The Algorithmic Language Scheme
@direntry
* Gauche Developers' Reference (ja): (gauche-devj.info).	Internals of Gauche
@end direntry
@c COMMON
@comment %**end of header

@titlepage
@c EN
@title Gauche Developers' Reference
@c JP
@title Gauche Developers' Reference
@c COMMON
@subtitle version @VERSION@
@author Shiro Kawai (shiro@@acm.org)

@page
@vskip 0pt plus 1filll
Copyright @copyright{} 2009-2025  Shiro Kawai  <shiro@@acm.org>

@end titlepage

@node Top, Introduction, (dir), (dir)

@ifnottex
This document explains the internal guts of Gauche
for developers who want to extend Gauche functionality in C,
or to embed Gauche to other applications.
This manual is for version @VERSION@.
@end ifnottex

@menu
* Introduction::
* Getting started::
* Fundamental concepts::
* Real-life examples::
* C API reference::
* Creating new Scheme datatypes::
* Helper program reference::
* Indices::
@end menu

@c ======================================================================
@node Introduction, Getting started, Top, Top
@chapter Introduction

The core part of the Gauche runtime is written in C and provided
as a library, @file{libgauche}.  This document explains how to
use it from C.  Using C API, you can extend Gauche's
functionality (e.g. providing bindinds to the existing C library),
and also link @file{libgauche} to your application, making
Gauche as an embedded scripting language.

Gauche's C API is designed for efficiency, consistency,
simplicity and safety, roughly in this order of precedence.
That is, sometimes we omit a safety net for efficiency, or we provide
several different APIs, each of which is efficient for a particular
purpose, rather than simple generic interface with overhead.
By saying efficiency over safety doesn't mean Gauche has security
holes, but we do assume you know what you're doing.  If you need
safety nets, you can write in Scheme and call it from C.

That said, it won't be too difficult to use Gauche's C API
as far as you know some fundamental design concepts.

We intend this document to serve both a programmer's guide
that explains such design concepts, and a programmer's reference
that describes every C API in detail.

The guide part begins with @ref{Getting started}, that shows
how to write a simple Gauche extension in C, as well as
a simple application that embeds Gauche.  It gives an overview
of the whole process.

The following chapter, @ref{Fundamental concepts}, describes
the design behind the API.  We strongly recommend you to
understand this chapter before trying to use Gauche C API
seriously.  As we mentioned above, it is very easy to break
something without knowing those concepts.

The guide part concludes with @ref{Real-life examples}, that
explains pitfalls in the practical situations using excerpt
of the actual Gauche extension code.

The reference part consists of two chapters: @ref{C API reference}
lists all the public C API.  @ref{Helper program reference}
explains several programs installed as a part of Gauche Scheme
system to help program development.

@c ======================================================================
@node Getting started, Fundamental concepts, Introduction, Top
@chapter Getting started

This chapter explains the basics of how to use Gauche C API
by several simple examples.

Although each example is too small to be practical value,
we try to present working code for each example, so that you
can actually play with it.  We recommend you to read through
all examples, for we introduce new concepts in each step.

We deal with the advanced topics that arise in the practical
situation in @ref{Real-life examples}.

The prerequisites for building Gauche extension, besides
the basic compiler chain, are the followings.  We assume
these are installed in your system.
@itemize @bullet
@item
Gauche 0.9.10 or later
@item
A compiler suite compatible to the one used to build @file{libgauche}.
@end itemize

@menu
* A trivial extension::
* Simple readline binding::
@end menu

@node A trivial extension, Simple readline binding, Getting started, Getting started
@section A trivial extension

@menu
* Generating skeletons::
* Building the trivial module::
* The templates explained::
* Introduction of the stub file::
@end menu

@node Generating skeletons, Building the trivial module, A trivial extension, A trivial extension
@subsection Generating skeletons

Let's create a Gauche extension that does nothing.

Gauche can generate a skeleton of the extension code
by @code{gauche-package generate} command.  You give the
package name to the command-line argument (here we pick @code{trivial}).

@smallexample
% @b{ls trivial}
ls: trivial: No such file or directory
% @b{gauche-package generate trivial}
% @b{ls trivial}
configure    package.scm  trivial.c  triviallib.stub
Makefile.in  test.scm	  trivial.h  trivial.scm
@end smallexample

The @code{gauche-package} command creates a directory @file{trivial},
and populates it with template files.  The role of each file is shown
below.

@table @emph
@item Package description (@file{package.scm})
This file contains metainformation about the extension,
such as version, dependency, license or repository URL.

@item Glue code (@file{trivial.c} and @file{trivial.h})
If what you want to do is just to write C functions and make it
available from Scheme, the function definitions and declarations
would go to these files.

Even if what you want to do is just to write bindings to
an existing library, it is typical that you need small amount
of auxiliary management code, such as initializing the library
and allocating/freeing library-side data structures.

@item Stub file (@file{triviallib.stub})
This file is the bridge between C world and Scheme world.
You have to list C functions you want to make it visible from
Scheme world.  Because of its nature, this file looks like
a mixture of Scheme code and C code fragments.

When the package is compiled, Gauche's helper scripts generate
a C file from a stub file, and compile it with other glue code
to generate a dynamically loadable object code, called DLL
(dynamically loadable library) or SO (shared object), depending
on the platform.

(Note: We're in middle of the process of retiring @file{*.stub} file;
instead, you'll be able to mix Scheme and C code in @file{*.scm} file
that will be compiled into DSO.  The extensions bundled with the Gauche
distribution, and several Gauche extensions, have already been switched;
you can take a peek and maybe start trying it.  The detailed specification
of this @emph{precompilation}, or ahead-of-time compilation, is still
fluid and may be changed in incompatible way, though.)

@item Module file (@file{trivial.scm})
This file typically defines Gauche modules and sets exported
symbols, and dynamically loads the compiled object code.
You may put auxiliary Scheme code in it.

@item Makefile template (@file{Makefile.in})
Gauche relies on the traditional build workflow---you run @file{configure}
script to generate @file{Makefile} that is tailored for your system.
Sticking to good old @code{make} makes it easy to incorporate
third party libraries.

@item Configure script (@file{configure})
This is a script that generates @file{Makefile} from @file{Makefile.in}.
Edit this if you need other files to be tailored, or need to test
other features on the platform.

We used to use GNU @code{autoconf} to generate @file{configure},
but we're moving away from it.  GNU @code{autoconf} is a fine tool
with lots of practical knowledge had put into development, but its
premise is that you have limited set of tools on the platform where
you compile the software, and that limitation makes the pipeline
complicated.

When you build Gauche extension, we already know you have Gauche
installed, so we can use Gauche's features to do configuration
work instead of relying on shell and other limited set of command-line
tools.  It is especially handy since we no longer need an extra
pass to generate @file{configure} from @file{configure.ac}.  With
the power of Gauche you can write @file{configure} file directly,
and you can check it in to VCS.  The users won't need @code{autoconf}
to build from the (unpreprocessed) source tree.

We try to match the interface of @file{configure} script to
@code{autoconf}-generated ones; it accepts most of the standard
options such as @code{--prefix}.

@item Unit test (@file{test.scm})
It is strongly encouraged to include unit test in your package,
and this file contains the skeleton of it.  The package user
can run the test by @code{make check}.
@end table

@node Building the trivial module, The templates explained, Generating skeletons, A trivial extension
@subsection Building, testing and installing the trivial module

These auto-generated files are already buildable.
First, you need to
run the @file{configure} script to
generate @file{Makefile}, then run @code{make}.

@smallexample
% @b{cd trivial}
% @b{./configure}
checking for gosh... /usr/bin/gosh
checking for gauche-config... /usr/bin/gauche-config
checking for gauche-package... /usr/bin/gauche-package
checking for gauche-install... /usr/bin/gauche-install
checking for gauche-cesconv... /usr/bin/gauche-cesconv
configure: creating trivial.gpd
configure: creating Makefile
% @b{make}
/usr/bin/gauche-package compile --verbose trivial trivial.c triviallib.stub
@i{(... message truncated ...)}
% @b{ls}
Makefile     config.log  trivial.c    trivial.o    triviallib.o
Makefile.in  configure	 trivial.gpd  trivial.scm  triviallib.stub
VERSION      test.scm	 trivial.h    trivial.so
@end smallexample

The build process creates @file{trivial.so}, the dynamically loadable
object file (the actual suffix may differ on some OSes).

Now it's ready to load the extension into Gauche.  The skeleton code
defines a Scheme function @code{test-trivial}, which just returns
a string.   Run the Gauche interpreter, load the @code{trivial} module,
and call @code{test-trivial} function.  Note that you need to give
@code{-I.} option to @code{gosh}, so that Gauche can find the @file{trivial}
module files.

@smallexample
% @b{gosh -I.}
gosh> @b{(use trivial)}
gosh> @b{(test-trivial)}
"trivial is working"
gosh>
@end smallexample

You may have noticed a file @file{trivial.gpd}.  The unfamiliar
suffix @code{gpd} stands for ``Gauche package description''.
It is created by @file{configure}, and records the name and version
of the package, and the configure options.  It is installed as a part
of the package and will be used by @code{gauche-package} script
(e.g. @code{gauche-package list} lists the installed packages).

You can also run a unit test by @code{make check}.

@smallexample
% make check
/usr/bin/gosh -I. test.scm > test.log
Testing trivial ...                                              passed.
@end smallexample

For now, it just checks if the compiled extension can be loaded,
and the integrity of the module.  As you add APIs in the extension,
you're expected to add tests as well.

Finally, you can install the extension by @code{make install}.

@smallexample
% make install
/usr/bin/gauche-install -m 444 -T /usr/lib/gauche/site/include
/usr/bin/gauche-install -m 444 -T /usr/share/gauche/site/lib trivial.scm
/usr/bin/gauche-install -m 555 -T /usr/lib/gauche/site/0.8.8/i686-pc-linux-gnu trivial.so
/usr/bin/gauche-install -m 444 -T /usr/share/gauche/site/lib/.packages trivial.gpd
@end smallexample

By default, the files are installed in the site-specific area
reserved within the installed Gauche.
If you want to change the install location, you can do the
same as typical autoconfigured softwares; e.g. giving
@code{--prefix} option to the @code{configure} script.

@node The templates explained, Introduction of the stub file, Building the trivial module, A trivial extension
@subsection The templates explained





@node Introduction of the stub file,  , The templates explained, A trivial extension
@subsection Introduction of the stub file



@node Simple readline binding,  , A trivial extension, Getting started
@section Simple readline binding









@c ======================================================================
@node Fundamental concepts, Real-life examples, Getting started, Top
@chapter Fundamental concepts

@menu
* Naming convention::
* Scheme types and C types::
* Memories::
* The VM::
* CPS API::
@end menu

@node Naming convention, Scheme types and C types, Fundamental concepts, Fundamental concepts
@section Naming convention

@c Memo:
@c   Scm_XXXXSet(XXXX xxxx, ...) - operation to modify xxxx.
@c   Scm_SetXXXX(...)  - operation to modify some global (or per-vm) value.

@node Scheme types and C types, Memories, Naming convention, Fundamental concepts
@section Scheme types and C types

@node Memories, The VM, Scheme types and C types, Fundamental concepts
@section Memories

@node The VM, CPS API, Memories, Fundamental concepts
@section The VM




@node CPS API,  , The VM, Fundamental concepts
@section CPS API




@c ======================================================================
@node Real-life examples, C API reference, Fundamental concepts, Top
@chapter Real-life examples

To be written. Meanwhile have a look at @file{examples/mqueue-cpp/README.adoc}
in the Gauche source tree.

@c ======================================================================
@node C API reference, Creating new Scheme datatypes, Real-life examples, Top
@chapter C API reference

In this chapter we describe most of public C APIs provided by
libgauche.  We say `most' because the features to let you create
a new Scheme datatype requires dedicated chapter,
@ref{Creating new Scheme datatypes}.

@menu
* Representation of Scheme objects::
* Initialization and cleanup::
* Memory allocation and GC::
* Booleans::
* Numbers::
* Pairs and lists::
* Symbols::
* Glocs::
* Modules::
* Characters::
* Character sets::
* Strings::
* Regular expressions::
* Vectors::
* Dictionaries::
* Weak pointers::
* Exceptions::
* Calling back to Scheme::
* Input and output::
* Loading programs::
* System interface::
@end menu

@node Representation of Scheme objects, Initialization and cleanup, C API reference, C API reference
@section Representation of Scheme objects

@deftp {Type} ScmObj
Scheme objects are uniformly treated as of type @code{ScmObj},
which may be either a tagged pointer to a heap allocated object
or a tagged immediate value.

Most Scheme objects are heap allocated, and except Scheme pairs,
heap allocated Scheme object has a fixed header.  We don't go
into more details here, but we'll revisit this topic in
@ref{Creating new Scheme datatypes}.   Certain frequently used
Scheme objects, such as boolean values, small exact integers
and characters, are encoded in a word without allocating
objects in heap, and we call them @emph{immediate values}.

Querying the type of a Scheme object and accessing its fields
should be done via provided macros or APIs.  The user code must
treat @code{ScmObj} as an opaque word, since the internal
representation may change.

The standard way to treat @code{ScmObj} value is (1) check to see
if its type matches what you expect, and (2) cast @code{ScmObj} to
the actual type and use it, as the following example shows.

@example
void your_C_function(ScmObj arg)
@{
  if (SCM_STRINGP(arg)) @{            /* check */
     ScmString *s = SCM_STRING(arg);  /* cast  */
     do_whatever_you_like_with_scheme_string(s);
  @} else @{
     SCM_TYPE_ERROR(arg, "a string");
  @}
@}
@end example

The @code{SCM_TYPE_ERROR} macro raises an error reporting
"a string is required for arg, but got ...".  That's a convenient
way to report the wrong type argument.  See @ref{Exceptions}
for more details of reporting errors.

Although it is not always checked explicitly, the programmer should
keep in mind that C's @code{NULL} is never a valid value for @code{ScmObj}.
If a C API requires @code{ScmObj} as an argument, you shouldn't pass
@code{NULL} to it.  Also if your function returns @code{ScmObj},
you should make sure it will never return @code{NULL}.
@end deftp

@deftypefn {Macro} ScmObj SCM_OBJ (void *@var{obj})
Typecast @var{obj} to @code{ScmObj}.  @var{Obj} must be
a pointer to an actual Scheme object.
@end deftypefn

We describe a few special constant Scheme objects here:

@deftypevr {Macro} ScmObj SCM_EOF
The Scheme's @code{#<eof>} object.
@end deftypevr

@deftypevr {Macro} ScmObj SCM_UNDEFINED
The Gauche's @code{#<undef>} object.  In Gauche, it is used as a
placeholder where the value itself doesn't matter.  At the time of
writing this document, there's a discussion in the next Scheme standard
to define @emph{the `unspecified' value} for this purpose, and it is
likely that this value will become such a value.
@end deftypevr

@deftypevr {Macro} ScmObj SCM_UNBOUND
This is a special value only seen in C world, and used to indicate
that a variable hasn't got a Scheme value assigned.  For example,
if a Scheme procedure with an optional argument is defined in C,
and no value is passed to the optional argument, @code{SCM_UNBOUND}
is given in C world.  This value should never be leaked out to
Scheme world.
@end deftypevr

@deftypefn {Macro} int SCM_EOFP (ScmObj @var{obj})
@deftypefnx {Macro} int SCM_UNDEFINEDP (ScmObj @var{obj})
@deftypefnx {Macro} int SCM_UNBOUNDP (ScmObj @var{obj})
Predicates to check whether the given @var{obj} is @code{SCM_EOF},
@code{SCM_UNDEFINED}, or @code{SCM_UNBOUND}, respectively.
@end deftypefn

@node Initialization and cleanup, Memory allocation and GC, Representation of Scheme objects, C API reference
@section Initialization and cleanup

This section explains how to initialize Gauche scheme runtime,
and how to clean it up.

These functions are for the applications that uses Gauche as
an embedded Scheme engine; when you're writing Gauche extensions,
you don't (and shouldn't) use these functions.

@subsubheading Initialization

@deftypefun void Scm_Init (const char *@var{signature})
Initializes the runtime.  Must be called before any other
Gauche API call.

To @var{signature}, you should always
pass a macro @code{GAUCHE_SIGNATURE}.  It is used to check a
proper version of Gauche shared library is linked.  If you
have several version of Gauche libraries (e.g. different
encoding or thread configuration), accidentally linking
unintended version would cause mysterious runtime crash.
If the signature doesn't match the library's, this function
exits the process with a message explaining it.
@end deftypefun

@subsubheading Cleanup and termination

@deftypefun void Scm_Exit (int @var{code})
Exits the process with @var{code} as the exit code.
Calling @code{Scm_Exit} is the easiest way to terminate Gauche
application safely.   It runs pending dynamic handlers,
registered cleanup handlers (see below), flushes output ports,
then calls @code{exit(2)} to exit.

Directly calling @code{exit(2)} would skip all those cleanup
process.
@end deftypefun

@deftypefun void Scm_Cleanup (void)
Cleans up the Scheme runtime just like @code{Scm_Exit()},
but does not call @code{exit(2)} at the end.  This is useful
for applications that want to shut down Gauche runtime but
need to continue running.

Once you call @code{Scm_Cleanup()}, you shouldn't use any
other Gauche functions.

It is harmless to call @code{Scm_Cleanup()} more than once;
it becomes no-op from the second time and after.
@end deftypefun

@deftypefun void Scm_Panic (const char *@var{msg}, @dots{})
The @var{msg} and other arguments are treated like @code{printf(3)}.
Formats and displays the formatted message, then exits the process
by calling @code{_exit(2)} with exit code 1.  No cleanup is done.

This is called when a serious defect is detected in the Gauche
runtime and cannot continue normal operation in any way.
@end deftypefun

@deftypefun void Scm_Abort (const char *@var{msg})
Writes @var{msg} to file descriptor 2, and exits the process
by calling @code{_exit(2)} with exit code 1.  No cleanup is done.

This is the last resort of emergency exit, where you cannot
even call @code{malloc} reliably.
@end deftypefun

@subsubheading Cleanup handlers

You can register functions to be called when Gauche runtime
is shut down.  The registered functions are called by
@code{Scm_Exit()} or @code{Scm_Cleanup()} in the reverse
order of their registration.

@deftypefun {void *} Scm_AddCleanupHandler (void (*@var{h})(void *), void *@var{d})
Adds a function @var{h} to the cleanup handler chain, with an opaque
data pointer @var{d}.  At the cleanup time, @var{h} is called
with @var{d} as the single argument.

Returns an opaque handle, which can be passed to DeleteCleanupHandler.
@end deftypefun

@deftypefun void Scm_DeleteCleanupHandler (void *@var{handle})
Delete cleanup handler.  The @var{handle} argument should be an opaque pointer
returned from @code{Scm_AddCleanupHandler}.  (But it won't complain if
other pointer is given; it just does nothing.)
@end deftypefun

@node Memory allocation and GC, Booleans, Initialization and cleanup, C API reference
@section Memory allocation and GC

Memories allocated by using the following macros are owned
by Gauche runtime and managed by the garbage collector.

@subsubheading Allocator macros

There's two kind of allocators; ordinary ones and
@emph{atomic} ones.  Here the term @emph{atomic} means
the allocated memory would never contain pointers
the collector needs to trace.  For example, when you
allocate memory for a character string, you can use
atomic allocator since the memory won't contain any
pointers.

It is important to use atomic versions whenever possible.
Gauche's GC is conservative, which means if there's a
word that looks like a pointer in a live object, the collector assumes
it is a pointer and retains the memory chunk pointed by it.
If it is not really a pointer, the collector may retain
unnecessary memory chunks.  It is called false pointers.
Telling the collector that a chunk of memory never contains
traceable pointer you can reduce the chance of false pointers.

It is OK for the atomic memory chunk to contain a pointer,
as far as the pointed chunk is reachable by other means,
or you can allow the pointed chunk to be collected (like
weak pointers).

Note: The term @emph{atomic} here probably came from the
fact that such a memory chunk is a terminal node, or an atom,
in the graph the collector traverses.  It has nothing to
do with the atomic operations.

@deftypefn {Macro} {@var{TYPE} *} SCM_NEW (@var{TYPE})
@deftypefnx {Macro} {@var{TYPE} *} SCM_NEW_ATOMIC (@var{TYPE})
Allocates memory for datatype @var{TYPE} and returns its pointer.
@code{ATOMIC} version allocates the memory as an atomic chunk.
@end deftypefn

@deftypefn {Macro} {@var{TYPE} *} SCM_NEW_ARRAY (@var{TYPE}, size_t @var{nelts})
@deftypefnx {Macro} {@var{TYPE} *} SCM_NEW_ATOMIC_ARRAY (@var{TYPE}, size_t @var{nelts})
Allocates memory for an array of size @var{nelts} of datatype @var{TYPE},
and returns its pointer.
@end deftypefn

@deftypefn {Macro} {@var{TYPE} *} SCM_NEW2 (@var{TYPE}, size_t @var{size})
@deftypefnx {Macro} {@var{TYPE} *} SCM_NEW_ATOMIC2 (@var{TYPE}, size_t @var{size})
Allocates memory of @var{size} bytes, and returns it as a pointer to
the datatype @var{TYPE}.
@end deftypefn

Note: to allocate a Scheme object for the class that is inheritable
from Scheme, you should use @code{SCM_ALLOCATE} macro to do some
extra initialization.  It is described in @ref{Creating new Scheme datatypes}.
You don't need to worry about it as far as you uses provided set
of Scheme datatypes, for each of them have a special "make" function
such as @code{Scm_MakeString}, @code{Scm_MakeVector}, etc.

@subsubheading Garbage collection

The garbage collector runs implicitly whenever it is necessary.
However, you can run it explicitly by this function:

@deftypefun void Scm_GC (void)
Triggers full GC.
@end deftypefun



@subsubheading Finalizers

@deftypefun void Scm_RegisterFinalizer (ScmObj @var{obj}, ScmFinalizerProc @var{finalizer}, void *@var{data})
Register the function @var{finalizer} to be called by the garbage
collector after the object @var{obj} is determined as dead. The function will
be given two arguments, the object and @var{data}.

GC works as this: After sweeping phase it has a set of unreachable objects.
If an unreachable object has a finalizer, it queues the object
in ``to-be-finalized'' list.  Gauche's VM checks the queue occasionally
and processes them if it's not empty.

You should consider a finalizer as an asynchronous callback, much like
Scheme-level signal handlers.  It is guaranteed to be called when VM
state is consistent (thus you can call back Gauche API safely from
the finalizer) and outside of GC (thus you can allocate inside
the finalizer), but you can't assume much more.

If @var{obj} points to another objects that's also being garbage collected,
that objects might already be finalized when @var{obj}'s finalizer
is called.  So you have to make finalizers set the objects to harmless
state, and you also have to check the case
objects referred from @var{obj} are in such state.

You can't choose which thread will call the finalizer.  Any thread that
allocates may call the finalizer.

You can resurrect @var{obj} by storing a pointer to it in some root set.
GC doesn't immediately put back @var{obj} to a free memor pool
after the finalizer is run; basically
it leaves @var{obj}'s fate to the finalizer.  If the finalizer doesn't keep
references to @var{obj}, then @var{obj} will be reclaimed in @emph{next}
GC cycle, for it isn't pointed from live objects.
Note that GC unregisters finalizer of @var{obj} when it
chains @var{obj} to ``to-be-finalized'' list.  So when the finalizer
is called, @var{obj} no longer has a finalizer.

Last but not least, there's no guarantee that the finalizer is called
promptly after @var{obj} lost all live references,
or whether it is called at all.  There might be an indefinite delay
between the point when @var{obj} becomes a garbage and the finalizer is run.
You should think finalizers as a safety-net, rather than a guaranteed clean-up
mechanism.  If your object requires explicit clean-up, ask users to do it
explicitly (possibly wrapping it with @code{call-with-*} style procedure).
Finalizers are for back up when the user fails to do so.
@end deftypefun

@deftypefun void Scm_UnregisterFinalizer (ScmObj @var{obj})
@end deftypefun

@node Booleans, Numbers, Memory allocation and GC, C API reference
@section Booleans

@deftypevr {Macro} ScmObj SCM_TRUE
@deftypevrx {Macro} ScmObj SCM_FALSE
Scheme's @code{#t} and @code{#f}.
@end deftypevr

@deftypefn {Macro} int SCM_TRUEP (ScmObj @var{obj})
@deftypefnx {Macro} int SCM_FALSEP (ScmObj @var{obj})
Predicates to check whether the given @var{obj} is @code{SCM_TRUE} or
@code{SCM_FALSE}, respectively.   Note that @code{!SCM_FALSEP(obj)}
is different from @code{SCM_TRUEP(obj)}.  Since Scheme treats anything
other than @code{#f} as a true value, usually what you need is
@code{SCM_FALSEP}.  You use @code{SCM_TRUEP} only iff you want
to make sure the object is @code{#t}.
@end deftypefn

@deftypefn {Macro} int SCM_BOOLP (ScmObj @var{obj})
Returns @code{TRUE} iff @var{obj} is either @code{SCM_FALSE} or
@code{SCM_TRUE}.
@end deftypefn

@deftypefn {Macro} int SCM_BOOL_VALUE (ScmObj @var{obj})
Converts Scheme value to C boolean value.  Returns @code{FALSE}
iff @var{obj} is @code{#f}.
@end deftypefn

@deftypefn {Macro} ScmObj SCM_MAKE_BOOL (@var{obj})
Converts C boolean value to a Scheme boolean value.
Returns @code{SCM_FALSE} if @var{obj} is @code{FALSE},
and @code{SCM_TRUE} for any other values.
@end deftypefn

@deftypefn {Macro} int SCM_EQ (ScmObj @var{x}, ScmObj @var{y})
Compares two Scheme objects are the same, in the sense of
Scheme's @code{eq?}.   You should always use this macro
instead of comparing two Scheme objects by @code{==}.
@end deftypefn

@deftypefun int Scm_EqP (ScmObj @var{x}, ScmObj @var{y})
A function version of @code{SCM_EQ}.
@end deftypefun

@deftypefun int Scm_EqvP (ScmObj @var{x}, ScmObj @var{y})
Scheme's @code{eqv?}.
@end deftypefun

@deftypefun int Scm_EqualP (ScmObj @var{x}, ScmObj @var{y})
Scheme's @code{equal?}.  Note: this function may call back VM recursively.
@end deftypefun

@deftypefun int Scm_EqualM (ScmObj @var{x}, ScmObj @var{y}, int @var{mode})
A convenient function to write functions with parameterized
equivalence procedure.   @var{Mode} may be one of the following
constants:
@table @code
@item SCM_CMP_EQ
Compare using @code{eq?}
@item SCM_CMP_EQV
Compare using @code{eqv?}
@item SCM_CMP_EQUAL
Compare using @code{equal?}
@end table
@end deftypefun



@node Numbers, Pairs and lists, Booleans, C API reference
@section Numbers

@menu
* Scheme number objects::
* Number predicates::
* Converting C and Scheme numbers::
* Generic arithmetics::
* Subtype-specific number operations::
* Reading and writing numbers::
@end menu

@node Scheme number objects, Number predicates, Numbers, Numbers
@subsection Scheme number objects

@subsubheading C representation of numbers

Gauche uses several different structures to represent Scheme
numbers.  Because of this polymorphic nature, the Scheme numbers
are almost always passed as @code{ScmObj}, except special occasions.
In Scheme level you usually don't need to think much
about different types of numbers, for Gauche automatically
converts them as needed.   There are C routines that accept
generic Scheme numbers like Scheme, but from time to time
you need to check the actual type of the number and cast it
from @code{ScmObj} to the actual structure.

Currently Gauche has the following C-level representations.

@table @emph
@item Fixnum
For small Scheme exact integers (30 or 62 bit signed integer
in 32 or 64 bit
architectures, respectively), we encode its immediate value into
a machine word.
@item Bignum
If a Scheme exact integer doesn't fit in fixnum, it is represented
as a bignum, by a @code{ScmBignum} structure.
@item Ratnum
A Scheme exact non-integral number is represented as a ratnum,
by a @code{ScmRatnum} structure.
@item Flonum
Scheme real numbers are represented as flonum, by @code{ScmFlonum}
structure.
@item Compnum
Scheme complex numbers are represented as compnum, by
a @code{ScmCompnum} structure.
@end table

It is important to not confuse these @emph{representations} and
Scheme numeric hierarchy: A Scheme real number can be represented
in either flonum, ratnum, bignum or fixnum, for example.
For each possible Scheme numeric type and exactness, the possible
C representation is shown in the table below:

@example
        |        exact         |    inexact    |
--------+----------------------+---------------+
integer |fixnum, bignum        |flonum         |
        |                      |               |
rational|fixnum, bignum, ratnum|flonum         |
        |                      |               |
real    |fixnum, bignum, ratnum|flonum         |
        |                      |               |
complex |fixnum, bignum, ratnum|flonum, compnum|
________|______________________|_______________|
@end example

(Note: Exact real and exact complex are supported in a sense
that exact rational number is always a real and complex number
as well.)

@subsubheading Normalized form

One Scheme number may be represented by more than
one C types; for example, an exact integer can also
be represented in ratnum with its denominator as 1.

To make things simple and clean, there's one important
rule C-routine writers should know:
If your routine returns a Scheme number, it must be in
a @emph{normalized} form, i.e.:

@itemize @bullet
@item
If the number is an exact integer, it should be either
fixnum or bignum; if the value fits in fixnum, it should be
fixnum.
@item
Denominator of ratnum is always greater than 1.  That is,
the sign of ratnum is the sign of its numerator.
@item
If the imaginary part of the number is 0.0, it must be
in flonum, rather than compnum.
@end itemize

(Note: here we use the term @emph{normalized} and @emph{denormalized}
in the sense that Scheme numbers should be represented in a simplest
possible C structure.  It is unrelated to the term in
IEEE floating point number.)

Most C APIs expect normalized numbers, and return normalized one.
As far as you're using those APIs, you don't need to care about
normalization, or even how the number is represented in Scheme.

If you ever need to peek into the representation, or deal with
denormalized numbers, see @ref{Subtype-specific number operations}.
Carrying around a denormalized Scheme number should be limited
for intermediate results, and only when you find the overhead of
conversion is a problem.  Generally such overhead is negligible
compared to other overheads.  If you use denormalized numbers,
make sure normalize them before passing it back to the rest
of the world, or bad things will happen.

@subsubheading Conversions and clamping

Converting a Scheme number to a C number is a
tricky business.  It's always possible that the Scheme number
you got may not fit into the desired C variable.  There are several
options you can choose.

@itemize @bullet
@item
Error: Throws an error.
@item
Clamp: If the Scheme value falls out of the supported range
of C variable, use the closest representable value.
@item
Convert only when possible.  If conversion is not possible, use
the Scheme value as-is.  It is useful to provide a shortcut path
to improve performance.
@end itemize

Some C APIs take @var{clamp} argument to specify the behavior.  The value
can be one of the following enums.

@deftp {Enum} ScmClampMode
@table @code
@item SCM_CLAMP_ERROR
An error is thrown if the given Scheme number doesn't fit
to the resulting C number.
@item SCM_CLAMP_HI
If the given Scheme number is too large to fit in the
resulting C number, the largest possible C number in the
result type is returned instead.  If the given Scheme number
is too small, an error is signalled.
@item SCM_CLAMP_LO
If the given Scheme number is too small to fit in the
resulting C number, the smallest possible C number in the
result type is returned instead.  If the given Scheme number
is too large, an error is signalled.
@item SCM_CLAMP_BOTH
Clamp both sides; with this argument, the API won't throw
an out-of-range error.
@item SCM_CLAMP_NONE
If the given Scheme number is out of the range, no conversion
is performed (an extra output argument tells you whether
it has happened or not).
@end table
@end deftp

See @var{Scm_GetIntegerClamp} below for a concrete example.

@node Number predicates, Converting C and Scheme numbers, Scheme number objects, Numbers
@subsection Number predicates

@deftypefn {Macro} int SCM_INTEGERP (ScmObj @var{obj})
Returns @code{TRUE} if @var{obj} is a Scheme exact integer; that is,
@var{obj} is either a fixnum or a bignum.
(The name is somewhat misleading.  This is @emph{not} Scheme's @code{integer?}.
To check whether @var{obj} is an integer, regardless of exact or
inexact, use @code{Scm_IntegerP} below).
@end deftypefn

@deftypefn {Macro} int SCM_RATIONALP (ScmObj @var{obj})
Returns @code{TRUE} iff @var{obj} is a Scheme exact rational number; that is,
@var{obj} is either one of fixnum, bignum or ratnum.
@end deftypefn

@deftypefn {Macro} int SCM_REALP (ScmObj @var{obj})
Returns @code{TRUE} iff @var{obj} is a Scheme real number; that is,
@var{obj} is either one of fixnum, bignum, ratnum or flonum.
@end deftypefn

@deftypefn {Macro} int SCM_NUMBERP (ScmObj @var{obj})
Returns @code{TRUE} iff @var{obj} is a Scheme number,
that is, either a fixnum, bignum, ratnum, flonum, or compnum.
@end deftypefn

@deftypefun int Scm_IntegerP (ScmObj @var{num})
Returns @code{TRUE} iff @var{num} is (exact or inexact) integer.

Note: If @var{num} is a flonum with exponent larger than certain value,
@code{Scm_IntegerP} always returns @code{TRUE}, because of its limited
precision of mantissa.
@end deftypefun

@deftypefun int Scm_OddP (ScmObj @var{num})
Returns @code{TRUE} iff a Scheme (exact or inexact) integer is
an odd number.  This throws an error if @var{num} is not an integer.
@end deftypefun

@deftypefun int Scm_FiniteP (ScmObj @var{obj})
@deftypefunx int Scm_IniniteP (ScmObj @var{obj})
@deftypefunx int Scm_NanP (ScmObj @var{obj})
Returns @code{TRUE} iff @var{obj} is a finite number,
an infinite number, or a NaN, respectively.  It is an error if
@var{obj} is not a Scheme number object.
@end deftypefun

@node Converting C and Scheme numbers, Generic arithmetics, Number predicates, Numbers
@subsection Converting C and Scheme numbers

@subsubheading Integers

@deftypefun ScmObj Scm_MakeInteger (long @var{i})
@deftypefunx ScmObj Scm_MakeIntegerU (u_long @var{i})
@deftypefunx ScmObj Scm_MakeInteger64 (int64_t @var{i})
@deftypefunx ScmObj Scm_MakeIntegerU64 (uint64_t @var{i})
Convert a C integer to a Scheme integer.
Always returns a normalized number.
@end deftypefun

@deftypefun long Scm_GetIntegerClamp (ScmObj obj, int clamp, int *oor)
@deftypefunx u_long Scm_GetIntegerUClamp (ScmObj obj, int clamp, int *oor)
@deftypefunx int Scm_GetInteger8Clamp (ScmObj obj, int clamp, int *oor)
@deftypefunx u_int Scm_GetIntegerU8Clamp (ScmObj obj, int clamp, int *oor)
@deftypefunx int Scm_GetInteger16Clamp (ScmObj obj, int clamp, int *oor)
@deftypefunx u_int Scm_GetIntegerU16Clamp (ScmObj obj, int clamp, int *oor)
@deftypefunx int32_t Scm_GetInteger32Clamp (ScmObj obj, int clamp, int *oor)
@deftypefunx uint32_t Scm_GetIntegerU32Clamp (ScmObj obj, int clamp, int *oor)
@deftypefunx int64_t Scm_GetInteger64Clamp (ScmObj obj, int clamp, int *oor)
@deftypefunx uint64_t Scm_GetIntegerU64Clamp (ScmObj obj, int clamp, int *oor)
Convert a Scheme number @var{obj} to a C integer.
If @var{obj} is a FLONUM or a RATNUM, they are rounded to the nearest
integer.

If the number @var{obj} can't be represented by the desired C integer type,
the behavior depends on @var{clamp},
which must be one of @code{ScmClampMode}.  See above for how out-of-range
value can be clamped.  If the out-of-range value isn't clamped by @var{clamp}
argument, @var{clamp} is not @code{SCM_CLAMP_ERROR}, and @var{oor} is not
@code{NULL} then @code{*oor} is set to @code{TRUE} and 0 is returned.
Otherwise, an error is thrown.

If @var{obj} is not a real number, an error is thrown.
@end deftypefun

@deftypefun long Scm_GetInteger (ScmObj obj)
@deftypefunx u_long Scm_GetIntegerU (ScmObj obj)
@deftypefunx int Scm_GetInteger8 (ScmObj obj)
@deftypefunx u_int Scm_GetIntegerU8 (ScmObj obj)
@deftypefunx int Scm_GetInteger16 (ScmObj obj)
@deftypefunx u_int Scm_GetIntegerU16 (ScmObj obj)
@deftypefunx int32_t Scm_GetInteger32 (ScmObj obj)
@deftypefunx uint32_t Scm_GetIntegerU32 (ScmObj obj)
@deftypefunx int64_t Scm_GetInteger64 (ScmObj obj)
@deftypefunx uint64_t Scm_GetIntegerU64 (ScmObj obj)
These are actually macros, expand into
@code{Scm_GetIntegerClamp(obj, SCM_CLAMP_ERROR, NULL)} etc.
@end deftypefun

@subsubheading Rational numbers

@deftypefun ScmObj Scm_MakeRational (ScmObj numer, ScmObj denom)
Numerator @var{numer} and denominator @var{denom} must both be
exact integers, and @var{denum} must not be zero.
This returns a simplest Scheme numebr of @code{numer/denom},
that is, it simplifies the rational number as much as possible;
it can even be an integer if @var{numer} is a multiple of @var{denom}.
@end deftypefun

@deftypefun ScmObj Scm_MakeRatnum (ScmObj numer, ScmObj denom)
Numerator @var{numer} and denominator @var{denom} must both be
exact integers, and @var{denum} must not be zero.
Returns a RATNUM of @code{numer/denom}.  This doesn't do any
simplification.

You should only use this to create an intermediate result, where
you'll eventually simplify the result along the way.
Whenever you create a number to return to the Scheme world,
you should always use @code{Scm_MakeRational} above.
@end deftypefun

@deftypefun ScmObj Scm_ReduceRational (ScmObj rational)
The argument must be a Scheme rational number (exact integer or ratnum).
Returns a simplified rational number, either in ratnum or integer.
@end deftypefun

@deftypefun ScmObj Scm_Numerator (ScmObj n)
@deftypefunx ScmObj Scm_Denominator (ScmObj n)
The argument must be a Scheme real number (integer, ratnum or flonum).
Returns its numerator and denominator, respectively.
If the argument is a flonum, it is first converted to an exact
number by @code{Scm_Exact}.
@end deftypefun


@subsubheading Real numbers

@deftypefun ScmObj Scm_MakeFlonum (double @var{d})
Returns a flonum from C @code{double} value.
@end deftypefun

@deftypefun ScmObj Scm_MakeFlonumToNumber (double @var{d}, int exactp)
Returns a scheme number corresponds to C @code{double} value @var{d}.
Unlike @code{Scm_MakeFlonum}, this routine returns a Scheme exact
integer if @code{exactp} is not @code{FALSE},
and @var{d} is an integer.
@end deftypefun

@deftypefun double Scm_GetDouble (ScmObj @var{obj})
Returns a C @code{double} value of Scheme real number @var{obj}
(that means @var{obj} can be a Scheme integer or ratnum as well).
If @var{obj} is not a Scheme real number, 0.0 is returned.
If @var{obj} is a ratnum, the closest IEEE double floating point number
is returned.
If @var{obj} is a bignum or ratnum that can't be represented by @code{double},
an infinity (positive or negative, depends on @var{obj}'s sign)
is returned.
@end deftypefun

@deftypefun ScmObj Scm_DecodeFlonum (double d, int *exp, int *sign)
Decompose a C double value @var{d} into its mantissa, exponent and sign.
Returns the mantissa as a Scheme exact integer, and stores the exponent
and the sign (either -1 or 1) in the location pointed by
@var{exp} and @var{sign}.

It returns Scheme integer since mantissa may not fit in @code{long}
on 32bit platforms, and this was created before @code{int64_t} became
available universally.  On 64bit platforms, returned number is always
a fixnum so no allocation occurs.
@end deftypefun

@deftypefun double Scm_EncodeFlonum (ScmObj mant, int exp, int sign)
Inverse of @code{Scm_DecodeFlonum}.  Given mantissa (a Scheme exact integer),
exponent and sign, returns a C double.

@var{sign} must be either -1 or 1, and @var{exp} must be greater than or
equal to -1074 and less than or equal to 971.  @var{mant} must be between
2^52 (inclusive) and 2^53 (exclusive) if @var{exp} is greater than -1074,
or between 0 (inclusive) and 2^52 (exclusive) if @var{exp} is -1074
(denormalized number).

The returned value is @code{(@var{sign} * @var{mant} * 2^@var{exp})}.

Note that the exponent value is offset by the mantissa scale, so it is not
the literal value stored in the exponent field of the IEEE double.
@end deftypefun

@deftypefun int Scm_FlonumSign (double d)
Returns -1 or 1, depending on the sign bit of @var{d}.  This differs
from @code{Scm_Sign} which returns 0 for both +0.0 and -0.0.
@end deftypefun

@deftp {Type} ScmHalfFloat
16-bit floating point number (1 bit sign, 5 bit exponent and 10-bit mantissa).
This format is sometimes used in the image data.
@end deftp

@deftypefun double Scm_HalfToDouble (ScmHalfFloat v)
@deftypefunx ScmHalfFloat Scm_DoubleToHalf (double d)
Convert between half float and C double.
If the given double can't be represented in half float, it is mapped
to infinities.
@end deftypefun

@subsubheading Complex numbers

@deftypefun ScmObj Scm_MakeComplex (double @var{real}, double @var{imag})
Returns a Scheme number @code{@var{real}+@var{imag}i}.
The return value is normalized, so it may be just a flonum
if @var{imag} is zero.
@end deftypefun

@deftypefun ScmObj Scm_MakeComplexPolar (double @var{mag}, double @var{angle})
Returns a Scheme number @code{@var{real}@@@var{imag}i}.
The return value is normalized, so it may be just a flonum
if the imaginary part of the number is zero.
@end deftypefun

@deftypefun double Scm_RealPart (ScmObj @var{obj})
@deftypefunx double Scm_ImagPart (ScmObj @var{obj})
@deftypefunx double Scm_Magnitude (ScmObj @var{obj})
@deftypefunx double Scm_Angle (ScmObj @var{obj})
Returns real part, imaginary part, magnitude and angle of a Scheme number
@var{obj}, which can be any number.
@end deftypefun

@deftp {Type} ScmDoubleComplex
@deftpx {Type} ScmFloatComplex
@deftpx {Type} ScmHalfComplex
C-world representation of compelx numbers, using @code{double}, @code{float}
and @code{ScmHalfFloat} for each complenent, respectively.
@end deftp

@deftypefun ScmDoubleComplex Scm_GetDoubleComplex (ScmObj z)
@deftypefunx ScmFloatComplex Scm_GetFloatComplex (ScmObj z)
@deftypefunx ScmHalfComplex Scm_GetHalfeComplex (ScmObj z)
Converts a Scheme number object @var{z} (can be any Scheme number)
to C-world complex representation.
@end deftypefun

@deftypefun ScmObj Scm_DoubleComplexToComplex (ScmDoubleCompex z)
@deftypefunx ScmObj Scm_FloatComplexToComplex (ScmFloatCompex z)
@deftypefunx ScmObj Scm_HalfComplexToComplex (ScmHalfCompex z)
Converts C-world complex representation to a Scheme number object.
@end deftypefun

@subsubheading Exactness

@deftypefun ScmObj Scm_Exact (ScmObj obj)
Scheme's @code{exact}.  An error is thrown if @var{obj} is not a
Scheme number object, an infinity, or a NaN.
@end deftypefun

@deftypefun ScmObj Scm_Inexact (ScmObj obj)
Scheme's @code{inexact}.  An error is thrown if @var{obj} is not a
Scheme number object.  If @var{obj} is out of range where IEEE double
can represent, an infinity object is returned.
@end deftypefun


@node Generic arithmetics, Subtype-specific number operations, Converting C and Scheme numbers, Numbers
@subsection Generic arithmetics


@subsubheading Exact integer operations

The following routines operates on Scheme exact integers.  If
the given @code{ScmObj} argument is not a Scheme exact integer,
an error is signalled.   For bitwise routines, an integer is
regarded in 2's complement form in case if it is negative.

@deftypefun ScmObj Scm_LogAnd (ScmObj @var{x}, ScmObj @var{y})
@deftypefunx ScmObj Scm_LogIor (ScmObj @var{x}, ScmObj @var{y})
@deftypefunx ScmObj Scm_LogXor (ScmObj @var{x}, ScmObj @var{y})
@deftypefunx ScmObj Scm_LogNot (ScmObj @var{x})
Bitwise operations.  Arguments must be Scheme exact integers.
Returns a Scheme exact integer, each bit of which is logical
@emph{and}, @emph{inclusive or}, @emph{exclusive or},
and @emph{not} of the corresponding bit(s) of the argument(s).
Correspond to Scheme @code{logand}, @code{logior},
@code{logxor} and @code{lognot}, respectively.
@end deftypefun

@deftypefun ScmObj Scm_Ash (ScmObj @var{x}, int @var{cnt})
Arithmetic left shift of a Scheme exact integer @var{x} by @var{cnt} bits.
If @var{cnt} is negative, it it shifts to right by @var{-cnt} bits.
Corresponds to Scheme @code{ash}.
@end deftypefun

@deftypefun int Scm_LogTest (ScmObj @var{x}, ScmObj @var{y})
Returns @code{FALSE} if bitwise @emph{and} of two Scheme exact
integers @var{x} and @var{y} yields zero, or @var{TRUE} otherwise.
Corresponds to Scheme @code{logtest}.
@end deftypefun

@deftypefun int Scm_LogBit (ScmObj @var{x}, int @var{b})
Returns @code{TRUE} or @code{FALSE} if @var{b}-th bit of
a Scheme exact integer @var{x} is set or not set, respectively.
0-th bit is the least significant bit.
Corresponds to Scheme @code{logbit}.
@end deftypefun

@subsubheading General operations

@deftypefun ScmObj Scm_Abs (ScmObj @var{num})
Returns the distance between 0 and @var{num}, which can
be any number (including complex numbers).  Exactness
of @var{num} is preserved.   An error is signalled if
@var{num} is not a Scheme number.
@end deftypefun

@deftypefun int Scm_Sign (ScmObj @var{num})
@var{Num} must be a real number.  Returns -1, 0, or 1
when @var{num} is less than, equal to, or greater than zero,
respectively.  If @var{num} is not a Scheme real number,
an error is signalled.

Note that this returns 0 for negative zero @code{-0.0}.  To check
the sign of zero, use @code{Scm_FlonumSign}.
@end deftypefun

@deftypefun ScmObj Scm_Negate (ScmObj @var{num})
@end deftypefun

@deftypefun ScmObj Scm_Reciprocal (ScmObj @var{num})
@end deftypefun

@deftypefun ScmObj Scm_Add (ScmObj @var{arg1}, ScmObj @var{arg2})
@deftypefunx ScmObj Scm_Sub (ScmObj @var{arg1}, ScmObj @var{arg2})
@deftypefunx ScmObj Scm_Mul (ScmObj @var{arg1}, ScmObj @var{arg2})
@deftypefunx ScmObj Scm_Div (ScmObj @var{arg1}, ScmObj @var{arg2})
@end deftypefun

@deftypefun ScmObj Scm_Quotient (ScmObj @var{arg1}, ScmObj @var{arg2}, ScmObj *@var{rem})
Returns @code{(quotient @var{arg1} @var{arg2})}.
If @var{rem} is not NULL, the remainder is stored in @code{*rem}.
@end deftypefun

@deftypefun ScmObj Scm_Modulo (ScmObj @var{arg1}, ScmObj @var{arg2}, int remainderp)
@end deftypefun

@deftypefun ScmObj Scm_Expt (ScmObj @var{x}, ScmObj @var{y})
@end deftypefun

@deftypefun int Scm_NumEq (ScmObj @var{x}, ScmObj @var{y})
Returns @code{TRUE} iff two Scheme numbers are equal
(same as Scheme's @code{=}).
@end deftypefun

@deftypefun int Scm_NumCmp (ScmObj @var{x}, ScmObj @var{y})
Returns @code{-1}, @code{0}, or @code{1}, where @code{x < y}, @code{x = y}
or @code{x > y}, respectively.  Arguments must be Scheme real numbers.
@end deftypefun

@deftypefun void Scm_MinMax (ScmObj @var{arg0}, ScmObj @var{args}, ScmObj *@var{min}, ScmObj *@var{max})
@end deftypefun

@deftp {Enum} ScmRoundMode
@example
enum ScmRoundMode @{
    SCM_ROUND_FLOOR,
    SCM_ROUND_CEIL,
    SCM_ROUND_TRUNC,
    SCM_ROUND_ROUND
@};
@end example
@end deftp

@deftypefun ScmObj Scm_Round (ScmObj @var{num}, int @var{mode})
Round a real number @var{num} to an integer.
@end deftypefun



@node Subtype-specific number operations, Reading and writing numbers, Generic arithmetics, Numbers
@subsection Subtype-specific number operations

@menu
* Fixnum operations::
* Bignum operations::
* Flonum operations::
* Compnum operations::
@end menu

@node Fixnum operations, Bignum operations, Subtype-specific number operations, Subtype-specific number operations
@subsubsection Fixnum operations

The following macros treat fixnums specifically.
In most cases you should use generic versions above, so that
you don't need to care about difference between fixnums and bignums,
and normalization.  However, if you know your Scheme number is
mostly small and you need speed, these macros will be handy.

@deftypefn {Macro} int SCM_INTP (ScmObj @var{obj})
Returns @code{TRUE} iff @var{obj} is a fixnum.

See @code{SCM_INTEGERP} (@pxref{Number predicates}),
to see if @var{obj} is an exact integer (either a fixnum or a bignum).
@end deftypefn

@deftypevr {Macro} int SCM_SMALL_INT_SIZE
Number of bits (excluding sign bit) of an integer representable
in fixnum.  Currently it is 29 and 61 for 32 and 64-bit architectures,
respectively.
@end deftypevr

@deftypevr {Macro} long SCM_SMALL_INT_MAX
@deftypevrx {Macro} long SCM_SMALL_INT_MIN
Maximum and minimum integer values representable in fixnum.
@end deftypevr

@deftypefn {Macro} int SCM_SMALL_INT_FITS (long @var{k})
Returns @code{TRUE} iff @var{k} fits in fixnum.
@end deftypefn

@deftypefn {Macro} long SCM_INT_VALUE (ScmObj @var{fixnum})
Extracts (unboxes) an integer value from @var{fixnum}.  You have to check
whether @var{fixnum} is a fixnum or not before applying this.
@end deftypefn

@deftypefn {Macro} ScmObj SCM_MAKE_INT (long @var{i})
Boxes an integer value @var{i} to a fixnum.  You have to make
sure @var{i} is in the range representable by fixnum.
@end deftypefn

@deftypefn {Macro} int SCM_UINTP (ScmObj @var{obj})
A convenience macro to check if @var{obj} is a fixnum
@emph{and} non-negative.
@end deftypefn

@node Bignum operations, Flonum operations, Fixnum operations, Subtype-specific number operations
@subsubsection Bignum operations

Again, it should generally be avoided to use bignums explicitly;
generic integer routines should take care of most cases.

A bignum keeps the absolute value in array of @code{u_long}s,
least significant word first.
The sign is kept separately.  It also keeps the number of
words used.

There's one more constraint about normalization.  Normalized
bignum uses only as many words as necessary to represent the
given number.  That is, the most significant word should never
be zero for normalized bignums.   You may see denormalized
bignums only in limited occasions, such as the intermediate
results.  Denormalized bignums should never be leaked out
to other APIs or to the Scheme world.

@deftypefn {Macro} int SCM_BIGNUMP (ScmObj @var{obj})
Returns @code{TRUE} iff @var{obj} is a bignum.
@end deftypefn

@deftypefn {Macro} ScmBignum* SCM_BIGNUM (ScmObj @var{bignum})
Cast @var{bignum} to @code{ScmBignum*}.
@end deftypefn

@deftypefn {Macro} int SCM_BIGNUM_SIZE (ScmObj @var{bignum})
Returns the number of words used in the bignum.
@end deftypefn

@deftypefn {Macro} int SCM_BIGNUM_SIGN (ScmObj @var{bignum})
Returns the sign (-1 or 1) of the bignum.  If @var{bignum}
is denormalized and contains zero, this macro returns 0.
@end deftypefn

The following APIs are for internal use, and only available
when you include @file{gauche/bignum.h}.  You should need
these only if you're implementing some basic bignum arithmetics.

@deftypefun ScmObj Scm_MakeBignumFromSI (long @var{val})
@deftypefunx ScmObj Scm_MakeBignumFromUI (u_long @var{val})
Converts C @code{long} or @code{u_long} value to a bignum.
The result is always a bignum, even when @var{val} can fit
in fixnum (i.e. the result can be denormalized).
@end deftypefun

@deftypefun ScmObj Scm_MakeBignumFromUIArray (int @var{sign}, u_long *@var{values}, int @var{size})
Creates a (possibly denormalized) bignum from the given @code{u_long}
array of length @var{size}.  @var{Size} must be greater than 0.
The first word @var{Values} is for the least significant word.

If @var{sign} is not zero, its sign determines the sign of the bignum,
and @code{values} are taken as absolute values.  If @var{sign} is zero,
this routine assumes @code{values} contains 2's complement form of
the integer.
@end deftypefun

@deftypefun ScmObj Scm_MakeBignumFromDouble (double @var{val})
Returns a (possible denormalized) bignum that represents
the integral part of @var{val}.
@end deftypefun

@deftypefun {ScmBignum *} Scm_MakeBignumWithSize (int @var{size}, u_long @var{init})
@end deftypefun

@deftypefun ScmObj Scm_BignumCopy (ScmBignum *@var{bignum})
Copy the given @var{bignum}.  The return value can be
denormalized if @var{bignum} is denormalized.
@end deftypefun

@deftypefun ScmObj Scm_NormalizeBignum (ScmBignum *@var{bignum})
Returns a normalized Scheme integer from the given bignum.
That is, the returned value can be fixnum if @var{bignum}
is small enough.  This also adjust the size of bignum if
it contains leading zero words.

The routine that returns the number to the outside world should
always use this routine to ensure a denormalized bignum would
never be leaked out.
@end deftypefun

@deftypefun long Scm_BignumToSI (ScmBignum *@var{bignum}, ScmClampMode @var{clamp}, int *@var{oor})
@deftypefunx u_long Scm_BignumToUI (ScmBignum *@var{bignum}, ScmClampMode @var{clamp}, int *@var{oor})
Converts a bignum to C @code{long} and @code{u_long}, respectively.
The behavior when @var{bignum}
is out of range is determined by @var{clamp} argument.
The @code{bignum} argument must be a normalized bignum.
@end deftypefun

@deftypefun ScmInt64 Scm_BignumToSI64 (ScmBignum *@var{bignum}, ScmClampMode @var{clamp}, int *@var{oor})
@deftypefunx ScmUInt64 Scm_BignumToUI64 (ScmBignum *@var{bignum}, ScmClampMode @var{clamp}, int *@var{oor})
64-bit integer version of @code{Scm_BignumToSI} and
@code{Scm_BignumToUI}.
The @code{bignum} argument must be a normalized bignum.
@end deftypefun

@deftypefun double Scm_BignumToDouble (ScmBignum *@var{bignum})
Converts a bignum to C @code{double} value.
The @code{bignum} argument must be a normalized bignum.
@end deftypefun

@deftypefun ScmObj Scm_BignumNegate (ScmBignum *@var{bignum})
Returns @code{-@var{bignum}}.  The argument may be denormalized.
The returned value is a normalized Scheme integer.
@end deftypefun

@deftypefun int Scm_BignumCmp (ScmBignum *@var{bx}, ScmBignum *@var{by})
Compares two normalized bignums.  Returns -1 if @code{@var{bx} < @var{by}},
0 if @code{@var{bx} = @var{by}}, and 1 if @code{@var{bx} > @var{by}}.
@end deftypefun

@deftypefun int Scm_BignumAbsCmp (ScmBignum *@var{bx}, ScmBignum *@var{by})
Compares absolute values of two normalized bignums.
Returns -1 if @code{abs(@var{bx}) < abs(@var{by})},
0 if @code{abs(@var{bx}) = abs(@var{by})},
and 1 if @code{abs(@var{bx}) > abs(@var{by})}.
@end deftypefun

@deftypefun ScmObj Scm_BignumAdd (ScmBignum *@var{bx}, ScmBignum *@var{by})
@deftypefunx ScmObj Scm_BignumSub (ScmBignum *@var{bx}, ScmBignum *@var{by})
@deftypefunx ScmObj Scm_BignumMul (ScmBignum *@var{bx}, ScmBignum *@var{by})
Returns
@code{(+ @var{bx} @var{by})},
@code{(- @var{bx} @var{by})},
and @code{(* @var{bx} @var{by})}, respectively.
Both argument should be normalized.
The return value is a normalized Scheme integer.
@end deftypefun

@deftypefun ScmObj Scm_BignumAddSI (ScmBignum *@var{bx}, long @var{y})
@deftypefunx ScmObj Scm_BignumSubSI (ScmBignum *@var{bx}, long @var{y})
@deftypefunx ScmObj Scm_BignumMulSI (ScmBignum *@var{bx}, long @var{y})
Returns
@code{(+ @var{bx} @var{y})},
@code{(- @var{bx} @var{y})},
and @code{(* @var{bx} @var{y})}, respectively.
@var{Bx} should be normalized.
The return value is a normalized Scheme integer.
@end deftypefun

@deftypefun ScmObj Scm_BignumDivRem (ScmBignum *@var{dividend}, ScmBignum *@var{divisor})
Returns a cons of quotient and remainder of two bignums.
Both bignums should be normalized.  Returns normalized numbers.
@end deftypefun

@deftypefun ScmObj Scm_BignumDivSI (ScmBignum *@var{dividend}, long @var{divisor}, long *@var{remainder})
Returns a quotient of @var{dividend} divided by @var{divisor}.
The remainder is stored in *@var{remainder}.
@var{Dividend} should be normalized.  Returns normalized number.
@end deftypefun

@node Flonum operations, Compnum operations, Bignum operations, Subtype-specific number operations
@subsubsection Flonum operations

@deftypefn {Macro} int SCM_FLONUMP (ScmObj @var{obj})
Returns @code{TRUE} iff @var{obj} is a flonum.

Note: in most cases, you may want to use @code{SCM_REALP} instead
of this; @code{Scm_GetDouble} can treat integers transparently.
@end deftypefn

@deftypefun ScmObj Scm_DecodeFlonum (double @var{d}, int *@var{pexp}, int *@var{psign})
Decompose C double value @var{d} into its mantissa, exponent and sign values.

The mantissa is returned as a Scheme integer (since it is 53bits in IEEE
double-precision floating format, we cannot return it as C integer
portably).  Values of exponent and sign (-1 or 1) are stored in
@code{*pexp} and @code{psign}.

Two special cases: If @var{d} is infinity, @code{SCM_TRUE} is returned,
and @code{*psign} contains its sign (-1 or 1).  If @var{d} is @code{NaN},
@code{SCM_FALSE} is returned.
@end deftypefun


@node Compnum operations,  , Flonum operations, Subtype-specific number operations
@subsubsection Compnum operations

@deftypefn {Macro} int SCM_COMPLEXP (ScmObj @var{obj})
Returns @code{TRUE} iff @var{obj} is a compnum.
@end deftypefn

@deftypefn {Macro} double SCM_COMPLEX_REAL (ScmObj @var{compnum})
@deftypefnx {Macro} double SCM_COMPLEX_IMAG (ScmObj @var{compnum})
Access to real and imaginary part of the complex number
@var{compnum}, which must be a compnum.
@end deftypefn

@deftypefun ScmObj Scm_MakeCompnum (double @var{real}, double @var{imag})
Returns a (possibly denormalized) compnum, whose real part is
@var{real} and imaginary part is @var{imag}.
@end deftypefun



@node Reading and writing numbers,  , Subtype-specific number operations, Numbers
@subsection Reading and writing numbers

@deftypefun ScmObj Scm_StringToNumber (ScmString *str, int radix, u_long flags)
Scheme's @code{string->number}.   Parse external representation of a Scheme
number in @var{str}.  If the argument can't be parsed as a number,
@code{SCM_FALSE} is returned.

The @var{radix} argument specifies the default radix.  If it isn't between
between 2 to 36, inclusive, @code{SCM_FALSE} is returned.
This setting may be overridden if the input contains explicit radix
prefix (@code{#x} etc.)

The @var{flags} argument can be a logical or of the following bitmasks:

@table @code
@item SCM_NUMBER_FORMAT_EXACT
@itemx SCM_NUMBER_FORMAT_INEXACT
If no explicit exactness prefix is in input, force the input to
be parsed as an exact/inexact number.  If neither of these flags
is given, and no explicit exactness prefix is in input,
the exactness is automatically deduced as the same rule as Gauche's
reader---that is, if the input contains a decimal point and/or exponential
notation, or the input is non-real complex number, it becomes inexact;
otherwise, it becomes exact.

@item SCM_NUMBER_FORMAT_STRICT_R7RS
Reject input that's not strictly follow R7RS syntax.

@item SCM_NUMBER_FORMAT_ALT_RADIX
Do not allow @code{#@var{n}R} style radix prefix.
@end table
@end deftypefun

@deftypefun ScmObj Scm_NumberToString (ScmObj obj, int radix, u_long flags)
Scheme's @code{number->string}.  An error is thrown if @var{obj} isn't a
number, or @var{radix} isn't between 2 and 10.

The @var{flags} argument can be a logical or of the following bitmasks:

@table @code
@item SCM_NUMBER_FORMAT_USE_UPPER
Use uppercase letters for digits greater than 10.  The default is to use
lower case.

@item SCM_NUMBER_SHOW_PLUS
Prepend @code{+} sign in positive number.

@item SCM_NUMBER_FORMAT_ALT_RADIX
Add a radix prefix.

@item SCM_NUMBER_FORMAT_ROUND_NOTATIONAL
Use notational decimal rounding.  See the @code{format} entry
of Gauche's reference manual about notational rounding.
@end table
@end deftypefun


@node Pairs and lists, Symbols, Numbers, C API reference
@section Pairs and lists

@menu
* Pair type and null::
* List constructors::
* List predicates::
* List accessors and modifiers::
* List utilities::
@end menu

@node Pair type and null, List constructors, Pairs and lists, Pairs and lists
@subsection Pair type and null

@deftp {Scheme Object} ScmPair
Represents a Scheme pair.

It exposes @code{car} and @code{cdr} fields, but they should always be
accessed via accessor functions or macros.

Some pairs are special and may have hidden fields.
Also, Gauche may impose a special alignment requirements for pairs,
so you should never define a variable of type ScmPair in your C code.
Instead, use the constructor API such as @code{Scm_Cons()} to get
an instance of ScmPair.

@example
@{
  /* Don't do this, or a devil comes out of your nose. */
  ScmPair foo = @{ ... @};

  /* Instead, you can do this: */
  ScmObj foo = Scm_Cons(...);
@}
@end example
@end deftp

@deftypevr {Scheme Constant} ScmObj SCM_NIL
A Scheme empty list, @code{()}.
@end deftypevr

@node List constructors, List predicates, Pair type and null, Pairs and lists
@subsection List constructors

@deftypefun ScmObj Scm_Cons (ScmObj car, ScmObj cdr)
Allocates and returns a fresh pair of @var{car} and @var{cdr}.
@end deftypefun

@deftypefun ScmObj Scm_Acons (ScmObj caar, ScmObj cadr, ScmObj cdr)
Scheme's @code{acons}.  Returns @code{(cons (cons caar cadr) cdr)}.
@end deftypefun

@deftypefun ScmObj Scm_List (ScmObj elt, @dots{}, NULL)
Returns a Scheme list of @var{elt}, @dots{}.  The C argument must
be terminated by NULL (note that NULL can never be a valid Scheme
value).
@end deftypefun

@deftypefun ScmObj Scm_Conses (ScmObj elt, @dots{}, NULL)
Scheme's @code{cons*}.
@end deftypefun

@deftypefun ScmObj Scm_VaList (va_list elts)
@deftypefunx ScmObj Scm_VaCons (va_list elts)
Vararg version of @code{Scm_List} and @code{Scm_Conses}.
@end deftypefun

@deftypefun ScmObj Scm_ArrayToList (ScmObj *elts, ScmSize nelts)
Takes a C array of @code{ScmObj}s of size @var{nelts},
and returns a Scheme list that has @var{elts} as its elements.
@end deftypefun

@deftypefun ScmObj Scm_ArrayToListWithTail (ScmObj *elts, ScmSize nelts, ScmObj tail)
Takes a C array of @code{ScmObj}s of size @var{nelts}, and
creates a Scheme list that has @var{elts} as its elements,
and has @var{tail} in its tail.
@end deftypefun

@deftypefun ScmObj *Scm_ListToArray (ScmObj list, ScmSize *nelts, ScmObj *store, int alloc)
Converts a Scheme list to a C array of @code{ScmObj*}.  An error is thrown
if @var{list} is not a proper list.

You can pass in a storage to store the result, or let the function allocate.

If @var{store} is NULL, the function always allocate an @code{ScmObj*} array.
The size of the array is stored in @code{*nelts}.

If @var{store} is not NULL, it must point to a writable memory of at least
@code{sizeof(ScmObj) * (*nelts)}.  If the length of @var{list} is
smaller than or equal to @code{*nelts}, the result is stored in @code{*store},
and @code{store} is returned.  The value of @code{*nelts} is adjusted
to contain the actual number of elements.

If the length of @var{list} is greater than @var{*nelts},
the behavior depends on the @code{alloc} flag.  If it is @code{FALSE},
an error is thrown.  Otherwise, a new storage is allocated, filled, and
returned.  The value of @code{*nelts} is ajusted to contain the actual
number of elements.
@end deftypefun

@deftypefn {Macro} ScmObj SCM_LIST1 (ScmObj a)
@deftypefnx {Macro} ScmObj SCM_LIST1 (ScmObj a, b)
@deftypefnx {Macro} ScmObj SCM_LIST1 (ScmObj a, b, c)
@deftypefnx {Macro} ScmObj SCM_LIST1 (ScmObj a, b, c, d)
@deftypefnx {Macro} ScmObj SCM_LIST1 (ScmObj a, b, c, d, e)
Convenience macros to create a Scheme list of length 1 to 5.
@end deftypefn

@deftypefun ScmObj Scm_MakeImmutablePair (ScmObj car, ScmObj cdr)
Creates and returns an immutable pair.  Immutable pair is almost
indistinguishable from ordinary (mutable) pairs, except that it
returns false for @code{Scm_ImmutablePairP()}, and it raises an error
when its car or cdr is tried to be modified.

Immutable pairs take up more storage than ordinary pairs.  Unless you
have a specific reason to use immutable pairs, you don't need to
worry about them.
@end deftypefun

@deftypefn {Macro} void SCM_APPEND1 (ScmObj head, ScmObj tail, ScmObj obj)
This macro captures an idiom of constructing a list from left to right.

The @var{head} and @var{tail} arguments must be a variable, initialized
by @code{SCM_NIL}.   This macro works like this:

@itemize @bullet
@item
If @var{head} is @code{SCM_NIL}, create a new pair whose car is @var{obj},
and make @var{head} and @var{tail} both point to the pair.
@item
Otherwise, create a new pair whose car is @var{obj},
set the cdr of @var{tail} to the new pair, then set @var{tail} to point
the new pair.
@end itemize

That is, @var{head} points to the first pair of the constructed list,
and @var{tail} points to the last pair of the constructed list.
@end deftypefn

@deftypefn {Macro} void SCM_APPEND (ScmObj head, ScmObj tail, ScmObj lis)
This macro captures an idiom of constructing a list from left to right.
Similar to @code{SCM_APPEND1}, but @var{lis} must be a proper Scheme list.
It appends a list @var{lis} to the
cdr of @var{tail} and make @var{tail} point to the last pair of @var{lis}.
In other words, it splices @var{lis}.
@end deftypefn


@node List predicates, List accessors and modifiers, List constructors, Pairs and lists
@subsection List predicates

@deftypefn {Macro} int SCM_NULLP (ScmObj obj)
Return a true value iff @var{obj} is @code{SCM_NIL}.
@end deftypefn

@deftypefn {Macro} int SCM_PAIRP (ScmObj obj)
Return a true value iff @var{obj} is a Scheme pair.

Note: If @var{obj} is a lazy pair, it is forced by this macro.
So once this macro returns true, you can assume @var{obj} is @code{ScmPair}.
@end deftypefn

@deftypefn {Macro} int SCM_LISTP (ScmObj obj)
Returns a true value iff @var{obj} is a Scheme pair or a Scheme emptylist.
If @var{obj} is a lazy pair, it is forced.

Note that this doesn't check if @var{obj} is a proper list.
@end deftypefn

@deftypefn {Macro} int SCM_PROPER_LIST_P (ScmObj obj)
@deftypefnx {Macro} int SCM_DOTTED_LIST_P (ScmObj obj)
@deftypefnx {Macro} int SCM_CIRCULAR_LIST_P (ScmObj obj)
Returns a true value iff @var{obj} is a Scheme proper list,
a Scheme dotted list, or a Scheme circular list, respectively.

These macros traverses the spine of @var{obj}, so all the lazy pairs
are forced.  Notably, if @var{obj} is an infinite lazy sequence
these macros never returns.
@end deftypefn

@deftypefun int Scm_ImmutablePairP (ScmObj obj)
Returns a true value if @var{obj} is a pair and immutable.
@end deftypefun


@node List accessors and modifiers, List utilities, List predicates, Pairs and lists
@subsection List accessors and modifiers

@deftypefun ScmObj Scm_Car (ScmObj obj)
@deftypefunx ScmObj Scm_Cdr (ScmObj obj)
@deftypefunx ScmObj Scm_Caar (ScmObj obj)
@deftypefunx ScmObj Scm_Cadr (ScmObj obj)
@deftypefunx ScmObj Scm_Cdar (ScmObj obj)
@deftypefunx ScmObj Scm_Cddr (ScmObj obj)
Scheme's @code{car} etc.  If @var{obj} isn't a pair, an error is thrown.
@end deftypefun

@deftypefun ScmObj Scm_SetCar (ScmObj obj)
@deftypefunx ScmObj Scm_SetCdr (ScmObj obj)
Scheme's @code{set-car!} and @code{set-cdr!}.  If @var{obj} isn't a
mutable pair, an error is thrown.
@end deftypefun

@deftypefun ScmObj Scm_ListRef (ScmObj list, ScmSmallInt i, ScmObj fallback)
@end deftypefun

@deftypefun ScmObj Scm_ListTail (ScmObj list, ScmSmallInt i, ScmObj fallback)
@end deftypefun

@deftypefun ScmObj Scm_LastPair (ScmObj list)
@end deftypefun

@deftypefn {Macro} void SCM_FOR_EACH (ScmObj var, ScmObj list) body
This is a convenience macro to traverse a Scheme list.  It is expanded
into something like this:

@example
for (var = list; SCM_PAIRP(var); var = Scm_Cdr(var)) body
@end example

That is, @var{body} is executed while @var{var} holds each pair
in the list.
@end deftypefn

@node List utilities,  , List accessors and modifiers, Pairs and lists
@subsection List utilities

@deftypefun ScmSize Scm_Length (ScmObj obj)
If @var{obj} is a Scheme proper list, returns its length.  If
@var{obj} is an emptylist, the length is 0.

If @var{obj} is a Scheme dotted list (which includes
a non-pair, non-emptylist object), returns SCM_LIST_DOTTED, which
is a negative integer constant.

If @var{obj} is a Scheme circular list, returns @code{SCM_LIST_CIRCULAR},
which is a nevative integer constant.
@end deftypefun

@deftypefun ScmObj Scm_CopyList (ScmObj list)
Scheme's @code{copy-list}.
Return a fresh copy of a Scheme proper or dotted list @var{list}.
If @var{list} is circular, an error is thrown.
@end deftypefun

@deftypefun ScmObj Scm_MakeList (ScmSmallInt len, ScmObj fill)
Scheme's @code{make-list}.
Creates a fresh @var{len}-element list, whose elements are all @var{fill}.
@end deftypefun

@deftypefun ScmObj Scm_Append2 (ScmObj list, ScmObj obj)
@deftypefunx ScmObj Scm_Append2X (ScmObj list, ScmObj obj)
Concatenate @var{obj} after a Scheme proper list @var{list}.
@code{Scm_Append2X} may destructively modify @var{list}.
@end deftypefun

@deftypefun ScmObj Scm_Append (ScmObj args)
This is rather Scheme's @code{concatenate}.   Elements of @var{args}
must be proper lists except the last one.
@end deftypefun

@deftypefun ScmObj Scm_Reverse (ScmObj list)
@deftypefunx ScmObj Scm_ReverseX (ScmObj list)
@end deftypefun

@deftypefun ScmObj Scm_Reverse2 (ScmObj list, ScmObj tail)
@deftypefunx ScmObj Scm_Reverse2X (ScmObj list, ScmObj tail)
@end deftypefun

@deftypefun ScmObj Scm_Memq (ScmObj obj, ScmObj list)
@deftypefunx ScmObj Scm_Memv (ScmObj obj, ScmObj list)
Scheme's @code{memq} and @code{memv}.  These won't throw an error,
as long as @var{list} doesn't contain a lazy pair.
@end deftypefun

@deftypefun ScmObj Scm_Member (ScmObj obj, ScmObj list, int cmpmode)
Generalized member.  The @var{cmpmode} argument must be either one
of @code{SCM_CMP_EQ}, @code{SCM_CMP_EQV}, or @code{SCM_CMP_EQUAL},
specifying the comparison should be done by @code{eq?}, @code{eqv?},
or @code{equal}.
@end deftypefun

@deftypefun ScmObj Scm_Assq (ScmObj obj, ScmObj list)
@deftypefunx ScmObj Scm_Assv (ScmObj obj, ScmObj list)
Scheme's @code{assq} and @code{assv}.  These won't throw an error,
as long as @var{list} doesn't contain a lazy pair.
Non-pair elements in @var{list} are ignored.
@end deftypefun

@deftypefun ScmObj Scm_Assoc (ScmObj obj, ScmObj list, int cmpmode)
Generalized assoc.  The @var{cmpmode} argument must be either one
of @code{SCM_CMP_EQ}, @code{SCM_CMP_EQV}, or @code{SCM_CMP_EQUAL},
specifying the comparison should be done by @code{eq?}, @code{eqv?},
or @code{equal}.
@end deftypefun

@deftypefun ScmObj Scm_Delete (ScmObj obj, ScmObj list, int cmpmode)
@deftypefunx ScmObj Scm_DeleteX (ScmObj obj, ScmObj list, int cmpmode)
@end deftypefun

@deftypefun ScmObj Scm_AssocDelete (ScmObj obj, ScmObj list, int cmpmode)
@deftypefunx ScmObj Scm_AssocDeleteX (ScmObj obj, ScmObj list, int cmpmode)
@end deftypefun

@deftypefun ScmObj Scm_DeleteDuplicates (ScmObj list, int cmpmode)
@deftypefunx ScmObj Scm_DeleteDuplicatesX (ScmObj list, int cmpmode)
@end deftypefun

@deftypefun ScmObj Scm_MonotonicMerge (ScmObj sequences)
@end deftypefun


@node Symbols, Glocs, Pairs and lists, C API reference
@section Symbols

@deftp {Scheme Object} ScmSymbol
Represents a Scheme symbol.   Unlike Common Lisp,
Gauche's symbol is merely an interned string.  It keeps
no other information than its name.  Global binding
is realized by modules that associate a symbol to
a @emph{gloc}, which keeps the global value, defined
modules, etc.
@end deftp

@deftypevr {Scheme Class Constant} {ScmClass *} SCM_CLASS_SYMBOL
A constant pointer pointing Gauche's @code{<symbol>} class.
@end deftypevr

@deftypefn {Macro} {ScmSymbol *} SCM_SYMBOL (ScmObj @var{obj})
Converts @code{ScmObj} to the pointer to a symbol.
@end deftypefn

@deftypefn {Macro} int SCM_SYMBOLP (ScmObj @var{obj})
@code{TRUE} iff @var{obj} is a symbol.
Note: In recent Gauche, keywords are a subclass of symbols, and
satisfies @code{SCM_SYMBOLP} too.
@end deftypefn

@deftypefn {Macro} {ScmString *} SCM_SYMBOL_NAME (ScmObj @var{symbol})
Returns the name of the symbol.
@end deftypefn

@deftypefun ScmObj Scm_Intern (ScmString *@var{name})
Creates and returns a symbol whose name is @var{name} and registers it in the
internal hash table.  If there's already a symbol with @var{name},
new symbol isn't created, and the existing symbol is returned.
@end deftypefun

@deftypefun ScmObj Scm_Gensym (ScmString *@var{prefix})
Creates and returns an uninterned symbol, whose name is generated
from @var{prefix} followed by some numbers.  @var{Prefix} can be
@code{NULL}, in which case the default prefix is used.
@end deftypefun

@deftypefn {Macro} ScmObj SCM_INTERN (const char *@var{name})
A convenience macro to create a symbol with the name @var{name}.
Implemented as follows:
@example
Scm_Intern(SCM_STRING(SCM_MAKE_STR_IMMUTABLE(cstr)))
@end example
@end deftypefn

@node Keywords,  , Symbols, Symbols
@section Keywords

Keywords are almost the same as symbols; in fact,
@code{ScmKeyword} is just a type alias of @code{ScmSymbol}.
They do have different runtime types (@code{SCM_CLASS_KEYWORD} vs
@code{SCM_CLASS_SYMBOL}), but in recent Gauche the keyword class
is a subclass of the symbol class by default.

@deftp {Scheme Object} ScmKeyword
Represents the Scheme keyword objects.
@end deftp

@deftypevr {Scheme Class Constant} {ScmClass *} SCM_CLASS_KEYWORD
A constant pointer pointing Gauche's @code{<keyword>} class.
@end deftypevr

@deftypefn {Macro} {ScmKeyword *} SCM_KEYWORD (ScmObj @var{obj})
Converts @code{ScmObj} to the pointer to a keyword.
@end deftypefn

@deftypefn {Macro} int SCM_KEYWORDP (ScmObj @var{obj})
@code{TRUE} iff @var{obj} is a keyword.
@end deftypefn

@deftypefn {Macro} {ScmString *} SCM_KEYWORD_NAME (ScmObj @var{keyword})
Returns the name of the keyword.
@end deftypefn

@deftypefun ScmObj Scm_MakeKeyword (ScmString *@var{name})
Scheme's @code{make-keyword}.
Returns a keyword whose name is @var{name}.  Note that preceding
@code{:} is not a part of the keyword name.
@end deftypefun

@deftypefun ScmObj Scm_GetKeyword (ScmObj @var{key}, ScmObj @var{list}, ScmObj @var{fallback})
Scheme's @code{get-keyword}.
This is actually a misnomer; @var{key} doesn't need to be a keyword, but
can be any object.
@end deftypefun

@deftypefun ScmObj Scm_DeleteKeyword (ScmObj @var{key}, ScmObj @var{list})
Scheme's @code{delete-keyword}.
This is actually a misnomer; @var{key} doesn't need to be a keyword, but
can be any object.
@end deftypefun

@deftypefun ScmObj Scm_DeleteKeywordX (ScmObj @var{key}, ScmObj @var{list})
Scheme's @code{delete-keyword!}.  @var{list} may be modified desctructively.
This is actually a misnomer; @var{key} doesn't need to be a keyword, but
can be any object.
@end deftypefun

@deftypefn {Macro} ScmObj SCM_MAKE_KEYWORD (const char *@var{name})
A convenience macro to create a keyword from C string @var{name}.
Implemented as follows:
@example
Scm_MakeKeyword(SCM_STRING(SCM_MAKE_STR_IMMUTABLE(name)))
@end example
@end deftypefn

@deftypefn {Macro} ScmObj SCM_GET_KEYWORD (const char *@var{name}, ScmObj @var{list}, ScmObj @var{fallback})
A convenience macro to search a value marked by a keyword whose name
is specified by C string @var{name}.
Implemented as follows:
@example
Scm_GetKeyword(SCM_MAKE_KEYWORD(name), list, fallback)
@end example
@end deftypefn



@node Glocs, Modules, Symbols, C API reference
@section Glocs

A gloc, or global location, is a structure to keep the global
value.  A module maps a symbol to a gloc.   Glocs are not directly
used in the Scheme world (except in some introspection features),
and even in the C world you don't usually need to deal with them.
To get/set the value of a global variable, you can use
@code{Scm_GlobalVariableRef} and @code{Scm_Define}, respectively
(@pxref{Modules}).

@deftp {Scheme Object} ScmGloc
Represents a gloc object.
@end deftp

@deftypevr {Scheme Class Constant} {ScmClass *} SCM_CLASS_GLOC
A constant pointer pointing Gauche's @code{<gloc>} class.
@end deftypevr

@deftypefn {Macro} {ScmGloc *} SCM_GLOC (ScmObj @var{obj})
Converts @code{ScmObj} to the pointer to a gloc.
@end deftypefn

@deftypefn {Macro} int SCM_GLOCP (ScmObj @var{obj})
@code{TRUE} iff @var{obj} is a gloc.
@end deftypefn

@deftypefn {Macro} ScmObj SCM_GLOC_GET (ScmGloc *@var{gloc})
Returns the global value of @var{gloc}.  This may return
@code{SCM_UNBOUND}; in such a case, the C routine must
make sure it won't leak out to the Scheme world (usually
the expected behavior is to raise an "undefined variable"
error.
@end deftypefn

@deftypefn {Macro} void SCM_GLOC_SET (ScmGloc *@var{gloc}, ScmObj @var{val})
Sets the global value of @var{gloc} to @var{val}.
This may raise an error if @var{gloc} is marked as a constant.
@end deftypefn

@deftypefn {Macro} void SCM_GLOC_CONST_P (ScmGloc *@var{gloc})
@code{TRUE} iff @var{gloc} is marked as a constant.
@end deftypefn


@node Modules, Characters, Glocs, C API reference
@section Modules

@deftp {Scheme Object} ScmModule
Represents the Scheme module objects.
@end deftp

@deftypefun ScmModule *Scm_FindModule (ScmSymbol *name, int flags)
@end deftypefun

@deftypefun ScmObj Scm_MakeModule (ScmSymbol *name, int error_if_exists)
@end deftypefun

@deftypefun ScmObj Scm_GlobalVariableRef (ScmModule *module, ScmSymbol *symbol, int flags)
@end deftypefun

@deftypefun ScmObj Scm_Define (ScmModule *module, ScmSymbol *symbol, ScmObj value)
@deftypefunx ScmObj Scm_DefineConst (ScmModule *module, ScmSymbol *symbol, ScmObj value)
@end deftypefun



@node Characters, Character sets, Modules, C API reference
@section Characters

@deftp {Type} ScmChar
A word large enough to hold all characters Gauche can handle.
It is like @code{wchar_t}, but we chose to use our own type since
the actual implementation of @code{wchar_t} varies among platforms
which complicates implementation.

You can assume that within the range of ASCII characters, C's @code{char}
and @code{ScmChar} have the same value; that is, you can safely cast
C's ASCII character to @code{ScmChar}.
If Gauche is compiled with utf-8 as internal character encoding,
the value of @code{ScmChar} always matches unicode codepoint value.

Note that @code{ScmChar} is @emph{not} the representation of Scheme
character; you stil need to box @code{ScmChar} value to pass a
character to the Scheme world by the following macros.
@end deftp

@deftypefn {Macro} ScmChar SCM_CHAR (@var{val})
Typecast C value @var{val} to @code{ScmChar}.
@end deftypefn

@deftypefn {Macro} int SCM_CHARP (ScmObj @var{obj})
Predicate to check whether @var{obj} is a Scheme character or not.
@end deftypefn

@deftypefn {Macro} ScmChar SCM_CHAR_VALUE (ScmObj @var{obj})
Unbox @code{ScmChar} value from a Scheme character @var{obj}.
@end deftypefn

@deftypefn {Macro} ScmObj SCM_MAKE_CHAR (ScmChar @var{val})
Box @var{ScmChar} value to a Scheme character.
@end deftypefn

@deftypevr {Macro} ScmChar SCM_CHAR_INVALID
A value that can't be a valid character.  Used in various
situations to indicate there's no appropriate character.
@end deftypevr

@deftypevr {Macro} ScmChar SCM_CHAR_MAX
Maximum possible value of @code{ScmChar}.
@end deftypevr

@deftp {Enum} Scm_IllegalCharHandling
In some functions that have to deal with characters coming
from outside world, you need to specify how they should behave
when they meet a data chunk that does not consist a valid
character in Gauche's native encoding.  This enum specifies
the behavior.

@table @code
@item SCM_ILLEGAL_CHAR_REJECT
Refuse to handle illegal chars.
For ports this means raising an error.
For string conversion procedure, this makes it to return
some non-string value, such as @code{SCM_FALSE}.
@item SCM_ILLEGAL_CHAR_OMIT
Silently discard the illegal chars.
@item SCM_ILLEGAL_CHAR_REPLACE
Replace an illegal char to a substitute
char, specified elsewhere.
@end table
@end deftp


@deftypefn {Macro} int SCM_CHAR_ASCII_P (ScmChar @var{val})
@deftypefnx {Macro} int SCM_CHAR_UPPER_P (ScmChar @var{val})
@deftypefnx {Macro} int SCM_CHAR_LOWER_P (ScmChar @var{val})
Like @code{isascii()}, @code{isupper()}, and @code{islower()}.
We can't use standard functions on @code{ScmChar}, since
@code{ScmChar} representation may be different from what
the platform supports.  Note that @var{val} may be used
more than once in the expanded form.
@end deftypefn

@deftypefn {Macro} ScmChar SCM_CHAR_UPCASE (ScmChar @var{val})
@deftypefnx {Macro} ScmChar SCM_CHAR_DOWNCASE (ScmChar @var{val})
Converts @code{ScmChar} to upper case or lower case character,
respectively.  Note that @var{val} may be used
more than once in the expanded form.
@end deftypefn

As of 0.8.8, @code{SCM_CHAR_UPPER_P}, @code{SCM_CHAR_LOWER_P},
@code{SCM_CHAR_UPCASE} and @code{SCM_CHAR_DOWNCASE}
only work properly on ASCII characters.  For any other characters,
the predicates return @code{FALSE}, and the converters
return the passed value as is.
It'll be extended to support larger character
ranges according to Unicode character attributes.

@deftypefun int Scm_DigitToInt (ScmChar @var{ch}, int @var{radix})
If a character @var{ch} represents a digit of a number in @var{radix},
returns the value it represents.  Otherwise, returns @code{-1}.

The valid range of @var{radix} is between 2 and 36, inclusive.

@example
Scm_DigitToInt(SCM_CHAR('0'), 10) @result{} 0
Scm_DigitToInt(SCM_CHAR('5'), 10) @result{} 5
Scm_DigitToInt(SCM_CHAR('c'), 10) @result{} -1
Scm_DigitToInt(SCM_CHAR('c'), 16) @result{} 12
Scm_DigitToInt(SCM_CHAR('C'), 16) @result{} 12
Scm_DigitToInt(SCM_CHAR('z'), 36) @result{} 35
@end example
@end deftypefun

@deftypefun ScmChar Scm_IntToDigit (int @var{n}, int @var{radix})
Converts an integer to a character that represents that integer.
in radix @var{radix} number.   @var{Radix} must be between
2 and 36 inclusive.

If @var{n} is outside of valid range, @code{SCM_CHAR_INVALID}
is returned.

@example
Scm_IntToDigit(0, 10) @result{} SCM_CHAR('0')
Scm_IntToDigit(5, 10) @result{} SCM_CHAR('5')
Scm_IntToDigit(10, 10) @result{} SCM_CHAR_INVALID
Scm_IntToDigit(10, 16) @result{} SCM_CHAR('a')
Scm_IntToDigit(35, 36) @result{} SCM_CHAR('z')
@end example
@end deftypefun

@deftypefun ScmChar Scm_UcsToChar (int @var{n})
Converts unicode codepoint @var{n} to an @code{ScmChar} value.
Since Gauche uses only utf-8 as internal encoding now, this is an identify
function.

This function may return @code{SCM_CHAR_INVALID} if @var{n}
can't be converted to a valid character in the native encoding.
(Note that, however, this function does not perform exhaustive
checking; if Gauche's internal encoding is utf-8, you can
pass any value to @var{n} even if it is not a valid Unicode codepoint,
and this function still returns @var{n} as is.)
@end deftypefun

@deftypefun int Scm_CharToUcs (ScmChar @var{ch})
Converts @code{ScmChar} value to Unicode codepoint.   This function
may return @code{-1}
if @var{ch} can't be converted to Unicode codepoint.
@end deftypefun

@deftypefun ScmObj Scm_CharEncodingname (void)
Returns a Scheme symbol that represents Gauche's internal character encoding.
As of 0.8.8, it may be either one of @code{utf-8},
@code{euc-jp}, @code{sjis} or @code{none}.
@end deftypefun

@deftypefun {const char **} Scm_SupportedCharacterEncodings (void)
Returns a NULL-terminated array of C strings of character encoding names
that are supported natively.  Since an encoding can be upper-compatible
to another encoding, there can be multiple supported encodings; for example,
if Gauche is compiled with @code{utf-8} as native encoding, @code{ascii}
and @code{iso-8859-1} are also supported since they are subset of
Unicode.

An encoding can have several aliases (e.g. @code{iso-8859-1} is often
referred as @code{latin-1}).  To avoid complication, you should use
@code{Scm_SupportedCharacterEncodingP} below to test whether the
running Gauche supports a certain encoding or not.
@end deftypefun

@deftypefun int Scm_SupportedCharacterEncodingP (const char *@var{encoding})
Returns @code{TRUE} if a character encoding named by @var{encoding}
is natively supported on the running Gauche.  Returns @code{FALSE} otherwise.

@var{Encoding} is compared in case insensitive way, and certain
variations (e.g. with or without hyphen) are allowed.
@end deftypefun

@node Character sets, Strings, Characters, C API reference
@section Character sets

@node Strings, Regular expressions, Character sets, C API reference
@section Strings

@subheading Multibyte strings and thread safety

Gauche supports multibyte strings natively, so its C API just
hides most complexities that come with multibyte encodings.  You should
treat Scheme strings as opaque objects and use provided APIs and macros
to access their contents.

Because of multibyte nature, the size of the string measured in bytes
can be different from the number of characters the string contains.
In Gauche, we refer the size of a string in bytes as @emph{size},
while the number of characters in a string as @emph{length}.

One important fact: Internally, Gauche treats string as immutable objects,
@code{ScmStringBody}.  Scheme standard requires string to be mutable,
so we have a Scheme string (@code{ScmString}) keep a pointer to a
string body, and when the Scheme string is modified, we allocate
a new string body and switch the pointer in the Scheme string
to the new body.  You can now see it is disastrously inefficient to
call @code{string-set!} repeatedly on a string in Gauche.

Note that, with preemptive multithreads, a Scheme string (@code{ScmString})
can be mutated while another thread is accessing it.  It is a problem for
us, since string mutation can change the size (in bytes) of the string
because of multibyte characters.  If you obtain the size, then accesses
the string content using the size, you don't want the size of the
content to be changed in between.
(This is not so much a problem for the implementations that use an
array of fixed-size characters, since mutation is localized to a
single character at a time.)

It is too expensive to use mutex for every string access.
Immutability helps here;
retrieving @code{ScmStringBody} from @code{ScmString} is an atomic
operation, and once you get hold onto @code{ScmStringBody}, you don't
need to worry about other threads because it will never be changed.
All the properties of strings, such as its size, belong to
@code{ScmStringBody} and not @code{ScmString}.

@example
/* WRONG: Thread-unsafe code */
void f(ScmString *s)
@{
  int size = SCM_STRING_BODY_SIZE(SCM_STRING_BODY(s)); /* in bytes */
  const char *cstr = Scm_GetStringConst(s);

  /* do something with size and cstr */
@}

/* CORRECT: Thread-safe code */
void f(ScmString *s)
@{
  int size;
  const char *cstr = Scm_GetStringContent(s, &size, NULL, NULL);

  /* do something with size and cstr */
@}

/* CORRECT: This one is also thread-safe, though you need to
   scan the string twice. */
void f(ScmString *s)
@{
  const char *cstr = Scm_GetStringConst(s);
  int size = strlen(cstr);

  /* do something with size and cstr */
@}
@end example

@subheading Datatype

@deftp {Scheme Object} ScmString
Scheme string.  It is merely a header that contains a pointer
to @code{ScmStringBody}.
@end deftp

@deftp {Type} ScmStringBody
The body of the string.  It is immutable---that is, once it
is constructed, it should never be changed.
@end deftp

@deftypevr {Constant} int SCM_STRING_IMMUTABLE
@deftypevrx {Constant} int SCM_STRING_INCOMPLETE
@deftypevrx {Constant} int SCM_STRING_COPYING
Flags to specify the nature of the string and/or the behavior of
the string constructor.

@table @code
@item SCM_STRING_IMMUTABLE
When passed to the constructor, it creates an immutable Scheme string.
This flag is stored in the Scheme string and causes an error
if you try to attempt to modify it.

@item SCM_STRING_INCOMPLETE
When passed to the constructor, it creates an incomplete Scheme
string (even the string doesn't contain illegal byte sequences).
The Scheme string is also marked incomplete when the constructor
found illegal byte sequences.

@item SCM_STRING_COPYING
This is only used by the string constructor and not stored in
the string object.  This flag indicates the constructor to copy
the content of the passed byte array.  See @code{Scm_MakeString}
below for the detailed explanation.
@end table
@end deftypevr

@deftypefn {Macro} int SCM_STRINGP (ScmObj @var{obj})
Type predicate.
@end deftypefn

@deftypefn {Macro} {ScmString *} SCM_STRING (ScmObj @var{obj})
Typecast.
@end deftypefn

@deftypefn {Macro} {const ScmStringBody *} SCM_STRING_BODY (ScmObj @var{str})
Returns a pointer to the body of the Scheme string @var{str}.
Note that the returned body is immutable.
@end deftypefn

@deftypefn {Macro} int SCM_STRING_BODY_LENGTH (ScmStringBody *@var{body})
@deftypefnx {Macro} int SCM_STRING_BODY_SIZE (ScmStringBody *@var{body})
@deftypefnx {Macro} int SCM_STRING_BODY_FLAGS (ScmStringBody *@var{body})
Query the parameters of the string body.
@end deftypefn

@deftypefn {Macro} int SCM_STRING_BODY_HAS_FLAG (ScmStringBody *@var{body}, int @var{flag})
Query if the string body has a flag, which is a bitwise OR
of zero or more of the @code{SCM_STRING_*} flags.
@end deftypefn

@deftypefn {Macro} int SCM_STRING_BODY_IMMUTABLE_P (ScmStringBody *@var{body})
@deftypefnx {Macro} int SCM_STRING_BODY_INCOMPLETE_P (ScmStringBody *@var{body})
Returns true iff the string body is immutable or incomplete, respectively.
@end deftypefn

@deftypefn {Macro} int SCM_STRING_BODY_SYNGLE_BYTE_P (ScmStringBody *@var{body})
Returns true iff the string consists of only single byte characters.
@end deftypefn


@subheading Constructors

@deftypefun ScmObj Scm_MakeString (const char *@var{str}, int @var{size}, int @var{len}, int @var{flags})
Creates a new Scheme string, whose content, size (in bytes),
and length (in characters) are given by @var{str}, @var{size} and
@var{len}, respectively.

You can pass @code{-1} to @var{size}.  In such case, @code{Scm_MakeString}
assumes @var{str} is @code{NUL}-terminated string and calculates
the size.  If you pass an explicit size, @var{str} does not need
to be @code{NUL}-terminated.

You can pass @code{-1} to @var{len}.  In such case, @code{Scm_MakeString}
counts characters in @var{str}.  If you pass an explicit length,
@code{Scm_MakeString} trust it---passing wrong number will cause
lots of troubles.

C-string @var{str} is interpreted in the Gauche's native
multibyte encoding.  If you pass @code{-1} to @var{len},
and @var{str} contains an illegal byte sequence as the
native multibyte encoding, the created string becomes
incomplete.  You can also create an incomplete string
explicitly by passing @code{SCM_STRING_INCOMPLETE} flag
to @var{flags}.

@var{Flags} is a bitwise OR of the following bitmasks.

@table @code
@item SCM_STRING_INCOMPLETE
Creates an incomplete string, even if @var{str} contains
only valid characters.
@item SCM_STRING_IMMUTABLE
Creates an immutable string.  Immutable string would
raise an error if used by mutating procedures.
@item SCM_STRING_COPYING
The content pointed by @var{str} is copied, so that the caller
can free @var{str} after this call.
Without this flag, the created string directly points the
region passed by @var{str}, and it is managed by Gauche's garbage
collector.  That is, if @var{str} points a static data or the region
you get by Gauche's allocators, you don't need this flag; while
if @var{str} points the region you get by @code{malloc} or other
means, you have to specify this flag.
@end table
@end deftypefun

@deftypefn {Macro} ScmObj SCM_MAKE_STR (const char *@var{cstr})
A convenience macro, expanded as follows:
@example
Scm_MakeString(@var{cstr}, -1, -1, 0)
@end example
That is, the size and length are counted automatically, and
@var{cstr} is not copied.
@end deftypefn

@deftypefn {Macro} ScmObj SCM_MAKE_STR_COPYING (const char *@var{cstr})
A convenience macro, expanded as follows:
@example
Scm_MakeString(@var{cstr}, -1, -1, SCM_STRING_COPYING)
@end example
That is, the size and length are counted automatically, and
@var{cstr} is copied.
@end deftypefn

@deftypefn {Macro} ScmObj SCM_MAKE_STR_IMMUTABLE (const char *@var{cstr})
A convenience macro, expanded as follows:
@example
Scm_MakeString(@var{cstr}, -1, -1, SCM_STRING_IMMUTABLE)
@end example
@end deftypefn

@deftypefun ScmObj Scm_MakeFillString (int @var{len}, ScmChar @var{fill})
Creates a Scheme string consists of the character @var{fill}
repeated for @var{len} times.  Returned string is always
mutable and complete.
@end deftypefun

@deftypefun ScmObj Scm_CopyStringWithFlags (ScmString *@var{str}, int @var{flags}, int @var{mask})
Copy the content of the string @var{str}, with modifying the flags
as specified by the following expression:
@example
newflag = (@var{flags} & @var{mask}) | (oldflag & ~@var{mask})
@end example

Typically you want to drop immutable flag.
Gauche internal uses bits in the flags other than listed here,
so you shouldn't change those bits.

Note: to copy a part of a string, you can use @code{Scm_Substring()}.
@end deftypefun

@deftypefun ScmObj Scm_CopyString (ScmString *@var{str})
An convenience function, equivalent to the following:
@example
Scm_CopyStringWithFlags(str, 0, SCM_STRING_IMMUTABLE)
@end example
@end deftypefun

@deftypefn {Macro} {} SCM_STRING_CONST_INITIALIZER (const char *@var{str}, int @var{len}, int @var{siz})
This is expanded to a static initializer of @code{ScmStringRec} structure.
@var{Len} and @var{siz} must be the correct values (you can't pass @code{-1}).

This is mainly for programs that generates C source.  This can
be used to embed static Scheme strings in the C source.
@end deftypefn

@deftypefn {Macro} {} SCM_DEFINE_STRING_CONST (@var{name}, const char *@var{str}, int @var{len}, int @var{siz})
Expands to:
@example
ScmString @var{name} =
   SCM_STRING_CONST_INITIALIZER(@var{str}, @var{len}, @var{siz})
@end example
@end deftypefn

@subheading C-string extraction

@deftypefun {const char *} Scm_GetStringConst (ScmString *@var{str})
Retrieves string content as a C string (@code{NUL}-terminated).
This is the efficient way to convert a Scheme string to a C string.
@end deftypefun

@deftypefun {char *} Scm_GetString (ScmString *@var{str})
Use this when you need a mutable C string.  This function
copies the content every time and returns a freshly allocated
string.
@end deftypefun

@deftypefun {const char *} Scm_GetStringContent (ScmString *@var{str}, unsigned int *@var{psize}, unsigned int *@var{plen}, unsigned int *@var{pflags})
Use this function if you want to retrieve other attributes of
the strings at once.  The return value points to the beginning
of the string content, but it may not be @code{NUL}-terminated.

@var{Psize}, @var{plen}, and @var{pflags} are pointers to the
location where the size, the length, and the flags of the
string is returned.  Any of them
can be @code{NULL} if the caller doesn't need the information.
The retrieval of those information and string content is atomic,
so this is a thread safe way to get informations out of @code{ScmString}.
@end deftypefun

@subheading Conversions

@deftypefun ScmObj Scm_CStringArrayToList (const char **@var{array}, int @var{size}, int @var{flags})
Converts an array of C string to a list of Scheme strings.
If @var{size} is nonnegative, it specifies the size of @var{array}.
If @var{size} is negative, @var{array} is assumed to be @code{NULL}-terminated.
The @var{flags} argument is passed to @code{Scm_MakeString} as is.
@end deftypefun

@deftypefun {const char **} Scm_ListToConstCStringArray (ScmObj @var{list}, int @var{errp})
Converts a list of Scheme strings @var{list} into C const string array,
@code{NULL} terminated.  If @var{errp} is true, an error is
signaled if @var{list} contains other than Scheme strings.
If @var{errp} is false, @code{NULL} is returned in such cases.
@end deftypefun

@deftypefun {char **} Scm_ListToCStringArray (ScmObj @var{list}, int @var{errp}, void *@var{alloc}(size_t))
Converts a list of Scheme strings @var{list} into C string array,
@code{NULL} terminated.  Unlike @code{Scm_ListToConstCStringArray},
each C string is freshly allocated and mutable.  Furthermore,
if @code{alloc} is provided, it is used to allocate C strings
and the pointer array.
@end deftypefun

@deftypefun ScmObj Scm_StringToList (ScmString *@var{str})
Scheme's @code{string->list}.  Returns a list of characters.
Signals an error if @var{str} is an incomplete string.
@end deftypefun

@deftypefun ScmObj Scm_ListToString (ScmObj @var{chars})
Scheme's @code{list->string}.  Converts a list of characters
to a Scheme string.  Signals an error if @var{chars} is
not a list, or it contains other than Scheme character.
@end deftypefun

@deftypefun ScmObj Scm_StringCompleteToIncomplete (ScmString *@var{str})
Returns a newly created incomplete Scheme string whose content is
the same as given Scheme string @var{str}.
@end deftypefun

@deftypefun ScmObj Scm_StringIncompleteToComplete (ScmString *@var{str}, int @var{handling}, ScmChar @var{substitute})
Returns a newly created complete Scheme string whose content is
the same as given (possible incomplete) string @var{str}.

The @var{handling} argument must be one of the values of enum
@code{Scm_IllegalCharacterHandling}, and determines the behavior
when @var{str} contains an illegal byte sequences.
If it is @code{SCM_ILLEGAL_CHAR_REJECT}, @code{SCM_FALSE} is returned.
If it is @code{SCM_ILLEGAL_CHAR_OMIT}, illegal bytes are omitted
from the result string.
If it is @code{SCM_ILLEGAL_CHAR_REPLACE}, each illegal byte is
replaced for @var{substitute}.  The @var{substitute} argument
isn't used in other cases.
@end deftypefun

@subheading Comparisons

@deftypefun int Scm_StringEqual (ScmString *@var{x}, ScmString *@var{y})
Returns @code{TRUE} if two strings are equal (as by @code{string=?}),
@code{FALSE} otherwise.
A string is equal to another if both their completeness and contents
match.
@end deftypefun

@deftypefun int Scm_StringCmp (ScmString *@var{x}, ScmString *@var{y})
Returns a positive integer if string @var{x} is greater than
string @var{y}, a negative integer if string @var{x} is less than
string @var{y}, and zero if string @var{x} and string @var{y} are
the same.  Comparison is done in the codepoint order.
Unlike @code{Scm_StringEqual}, this function signals an error
if completeness of both string differ.
@end deftypefun

@deftypefun int Scm_StringCiCmp (ScmString *@var{x}, ScmString *@var{y})
Like @code{Scm_StringCmp}, but compares in case-insensitive way.

Currently Gauche only folds cases within ASCII range.  Soon it'll
follow Unicode case folding rules.
@end deftypefun

@subheading Accessors

@deftypefun ScmChar Scm_StringRef (ScmString *@var{str}, int @var{k}, int @var{range_error})
Scheme's @code{string-ref}.  Returns a character at the @var{k}-th position
of the string @var{str}.  When @var{k} is out of range,
returns @code{SCM_CHAR_INVALID} if @code{range_error} is @code{FALSE},
or raises an error if @code{range_error} is true.

For the time being, an error is raised if @var{str} is an incomplete
string.
@end deftypefun

@deftypefun int Scm_StringByteRef (ScmString *@var{str}, int @var{k}, int @var{range_error})
Returns @var{k}-th byte in the Scheme string @var{str} as a nonnegative
integer.  If @var{range_error} is true, an error is signalled
if @var{k} is out of range.  If @var{range_error} is false,
-1 is returned if @var{k} is out of range.
@var{Str} can be an incomplete string.
@end deftypefun

@deftypefun ScmObj Scm_Substring (ScmString *@var{str}, int @var{start}, int @var{end}, int @var{byterange})
Returns a substring of @var{str}, starting from @var{start}
(inclusive) and ending at @var{end} (exclusive).
If @var{byterange} is @code{FALSE} and @var{str} is complete,
@var{start} and @var{end} are character count and returned
string will be complete.  Otherwise, they are byte count and returned
string will be incomplete.

A negative value in the @var{end} argument is regarded as
the length/size of the input string.  After this treatment,
both @var{start} and @var{end} arguments must be in the valid range,
and @var{start} must be less than or equal to @var{end}, or an error
is signalled.

It is guaranteed that the returned string is newly created and
mutable, even if the @var{start} and @var{end} specifies the entire
string.
@end deftypefun

@subheading Mutator

@deftypefun ScmObj Scm_StringReplaceBody (ScmString *@var{target}, ScmStringBody *@var{newbody})
Replaces @var{target}'s body by @var{newbody}.  An error is signalled
if @var{target} is immutable.

This is the only C API that allows mutation of Scheme strings.
Scheme-level string mutators, such as @code{string-set!} and
@code{string-fill!}, are implemented in Scheme on top of
this API.  Since string body is immutable, such mutators
needs to allocate and fill a new string body anyway, there's
little merit in providing those mutators in C.
@end deftypefun


@subsubheading Concatenation

@deftypefun ScmObj Scm_StringAppend2 (ScmString *@var{x}, ScmString *@var{y})
Returns a new Scheme string whose content is concatenation of
strings @var{x} and @var{y}.
@end deftypefun

@deftypefun ScmObj Scm_StringAppendC (ScmString *@var{x}, const char *@var{s}, int @var{size}, int @var{len})
Returns a new Scheme string whose content is concatenation of
a Scheme string @var{x} and C-level string @var{s}.
Like @code{Scm_MakeString}, you can give -1 to @var{size} and/or @var{len}
to make the function calculates those values.  If you give -1 to @var{size},
@var{s} must be @code{NUL}-terminated; otherwise @var{s} doesn't need to be.
@end deftypefun

@deftypefun ScmObj Scm_StringAppend (ScmObj @var{strs})
The @var{strs} argument must be a list of Scheme strings.
Returns a new Scheme string whose content is concatenation
of all the strings.  An error is signalled if not all elements
in @var{strs} are strings.

If any element in @var{strs} is incomplete, the result string
becomes incomplete.
@end deftypefun

@deftypefun ScmObj Scm_StringJoin (ScmObj @var{strs}, ScmString *@var{delim}, int @var{grammar})
Scheme's @var{string-join}.  Concatenates a list of strings @var{strs}
with inserting a delimiter @var{delim} between them.  The @var{grammar}
argument must be one of the following enums:

@example
enum @{
    SCM_STRING_JOIN_INFIX,
    SCM_STRING_JOIN_STRICT_INFIX,
    SCM_STRING_JOIN_SUFFIX,
    SCM_STRING_JOIN_PREFIX
@};
@end example

They correspond to @code{infix}, @code{strict-infix}, @code{suffix},
and @code{prefix} as defined in @code{srfi-13}'s @code{string-join}.
@end deftypefun

@subheading Searching

@deftypefun ScmObj Scm_StringScan (ScmString *@var{s1}, ScmString *@var{s2}, int @var{retmode})
@deftypefunx ScmObj Scm_StringScanChar (ScmString *@var{s1}, ScmChar @var{ch}, int @var{retmode})
Scheme's @code{string-scan}.
Search a string @var{s2} or a character @var{ch} within a string @var{s1},
respectively.  Return value depends on the @var{retmode} argument, as follows:
@table @code
@item SCM_STRING_SCAN_INDEX
Returns an index of the first found instance of @var{s1}/@var{ch},
or @code{SCM_FALSE} if no instance is found.
@item SCM_STRING_SCAN_BEFORE
Returns a substring of @var{s1} between its beginning and just
before the first found instance of @var{s1}/@var{ch},
or @code{SCM_FALSE} if no instance is found.
@item SCM_STRING_SCAN_AFTER
Returns a substring of @var{s1} between just after the first found instance
of @var{s1}/@var{ch} and the end of @var{s1},
or @code{SCM_FALSE} if no instance is found.
@item SCM_STRING_SCAN_BEFORE2
Returns two values via @code{Scm_Values()},
the substring of @var{s1} before the found instance
and the rest, or two @code{SCM_FALSE}s if no instance found.
@item SCM_STRING_SCAN_AFTER2
Returns two values via @code{Scm_Values()},
the substring of @var{s1} before the end of the
found instance and the rest, or two @code{SCM_FALSE}s if no instance found.
@item SCM_STRING_SCAN_BOTH
Returns two values via @code{Scm_Values()},
the substring of @var{s1} before the found instance and
after the found instance, or two @code{SCM_FALSE}s if no instance found.
@end table

The last three return multiple values on the running Gauche VM.
See @ref{Calling back to Scheme}, for how to retrieve those values.
@end deftypefun

@deftypefun ScmObj Scm_StringSplitByChar (ScmString *@var{str}, ScmChar @var{ch})

@end deftypefun


@subheading Miscellaneous utilities

@deftypefun int Scm_MBLen (const char *@var{str}, const char *@var{stop})
A utility function to count the number of characters in a multibyte
string @var{str}, assuming it's in Gauche's native encoding.

If @var{stop} is given, it specifies the end point in the string;
bytes just before @var{stop} are counted.  The string may have
@code{NUL} character in this case.

If @var{stop} is @code{NULL}, @var{str} is assumed to be @code{NUL}
terminated.

If the string is complete, the number of characters is returned.
If the string is incomplete, -1 is returned.
@end deftypefun


@subheading Dynamic strings

Dynamic strings provide a convenient way to construct a string
of an unknown length.  It is a base of output string port, but
from C programs using dynamic strings is lightweight than output
string port (see @ref{Built-in ports}, for string ports).
It is OK to call dynamic string operations while locking a
mutex.

@deftp {Datatype} ScmDString
A structure to keep a string under construction.   It is not a
Scheme datatype (means: you can't cast it to @code{ScmObj}).
You can allocate it on the C stack for efficient operation.
@end deftp

The typical usage of dynamic strings looks like this:

@example
ScmDString ds;
ScmObj str;

Scm_DStringInit(&ds);            /* Initialization */
Scm_DstringPutc(&ds, 'a');       /* Adding content */
Scm_DstringPutz(&ds, "abc", -1); /* Adding content */
 ...

str = Scm_DStringGet(&ds, 0);   /* Obtains the result string */
@end example

@deftypefun void Scm_DStringInit (ScmDString *@var{dstr})
Initializes a dynamic string object.  A dynamic string object
must be initialized before used.
@end deftypefun

@deftypefun int Scm_DStringSize (ScmDString *@var{dstr})
Returns the size (number of bytes) accumulated in the dynamic string.
@end deftypefun

@deftypefun ScmObj Scm_DStringGet (ScmDString *@var{dstr}, int @var{flags})
Extracts the accumulated string as a Scheme string.  The accumulated
data remains in @var{dstr}.  By default, returned string is mutable,
and its completeness is determined by its content.  You may pass
@code{SCM_STRING_IMUUTABLE} and/or @code{SCM_STRING_INCOMPLETE} to
the @var{flags} argument to force the attributes of the result string.
@end deftypefun

@deftypefun {const char *} Scm_DStringGetz (ScmDString *@var{dstr})
Extracts the accumulated string as a @code{NUL}-terminated C string.
The accumulated data remains in @var{dstr}.
@end deftypefun

@deftypefun void Scm_DStringPutz (ScmDString *@var{dstr}, const char *@var{str}, int @var{siz})
Adds C string @var{str} to the dynamic string.  If @var{siz} is negative,
@var{str} is assumed to be @code{NUL}-terminated.  If @var{siz} is nonnegative,
it specifies the size of the string (in which case @var{str} may contain
@code{NUL} character in it.)
@end deftypefun

@deftypefun void Scm_DStringAdd (ScmDString *@var{dstr}, ScmString *@var{str})
Adds Scheme string @var{str} to the dynamic string.
@end deftypefun

@deftypefun void Scm_DStringPutb (ScmDString *@var{dstr}, char @var{byte})
Adds a single byte @var{byte} to the dynamic string.
@end deftypefun

@deftypefun void Scm_DStringPutc (ScmDString *@var{dstr}, ScmChar @var{ch})
Adds a single character @var{ch} to the dynamic string.
@end deftypefun


@node Regular expressions, Vectors, Strings, C API reference
@section Regular expressions

@node Vectors, Dictionaries, Regular expressions, C API reference
@section Vectors

@deftypefn {Macro} int SCM_VECTORP (ScmObj @var{obj})
Type predicate.
@end deftypefn

@deftypefn {Macro} {ScmVector *} SCM_VECTOR (ScmObj @var{obj})
Typecast.
@end deftypefn

@deftypefn {Macro} int SCM_VECTOR_SIZE (ScmObj @var{vec})
Returns the number of elements of the vector @var{vec}.
@end deftypefn

@deftypefn {Macro} {ScmObj *} SCM_VECTOR_ELEMENTS (ScmObj @var{vec})
Returns the pointer to the array of the vector contents.
@end deftypefn

@deftypefn {Macro} ScmObj SCM_VECTOR_ELEMENT (ScmObj @var{vec}, int @var{k})
Returns the @var{k}-th element of the vector.
No boundary check is done.  Use @code{Scm_VectorRef} for safer access.
@end deftypefn

@deftypefun ScmObj Scm_MakeVector (int @var{size}, ScmObj @var{fill})
Returns a vector of @var{size} elements.  Each element is
initialized by @var{fill}.
@end deftypefun

@deftypefun ScmObj Scm_ListToVector (ScmObj @var{list}, int @var{start}, int @var{end})
Creates a vector from @var{start}-th element (inclusive) to
@var{end}-th element (exclusive) of a list @var{list}.
@var{end} can be @code{-1} to indicate the end of the list.
@end deftypefun

@deftypefun ScmObj Scm_VectorToList (ScmVector *@var{vec}, int @var{start}, int @var{end})
Creates a list from @var{start}-th element (inclusive) to
@var{end}-th element (exclusive) of a vector @var{vec}.
@var{end} can be @code{-1} to indicate the end of the vector.
@end deftypefun

@deftypefun ScmObj Scm_VectorRef (ScmVector *@var{vec}, int @var{k}, ScmObj @var{fallback})
Returns @var{k}-th element of the vector.  If @var{k} is
out of range, the value passed to @var{fallback} is returned.
Note that this routine will never raise an error; argument check
of Scheme's @code{vector-ref} is done in the bridge stub.
@end deftypefun

@deftypefun ScmObj Scm_VectorSet (ScmVector *@var{vec}, int @var{k}, ScmObj @var{obj})
Sets @var{k}-th element of a vector @var{vec} by @var{obj}.
Always return @var{obj}.
If @var{k} is out of range, no operation is performed (no error
is signalled).  The boundary check for Scheme's @code{vector-set!}
is done in the bridge stub.
@end deftypefun


@deftypefun ScmObj Scm_VectorFill (ScmVector *@var{vec}, ScmObj @var{fill}, int @var{start}, int @var{end})
Sets @var{start}-th element (inclusive) to @var{end}-th element
(exclusive) of a vector @var{vec} by @var{fill}.
@var{end} can be @code{-1} to indicate the end of the vector.
@end deftypefun

@deftypefun ScmObj Scm_VectorCopy (ScmVector *@var{vec}, int @var{start}, int @var{end}, ScmObj @var{fill})
Creates a new vector, whose content is the same
as the content of @var{vec} beginning with @var{start}-th element
and ending with (@var{end}-1)-th element.  If @var{end} is -1,
it is taken as the length of @var{vec}.  Unlike other vector APIs,
@var{start} can be negative and @var{end} can be greater than
then length of @var{vec}; in such case, @var{vec} is regarded
as if it has implicit elements in both directions, whose value
is given by @var{fill}.
@end deftypefun

@deftypefn {Macro} int SCM_UVECTORP (ScmObj @var{obj})
Type predicate.
@end deftypefn

@deftypefn {Macro} {ScmUVector *} SCM_UVECTOR (ScmObj @var{obj})
Typecast.
@end deftypefn

@deftypefn {Macro} {void *} SCM_UVECTOR_OWNER (ScmObj @var{vec})
Returns the owner pointer of the uniform vector @var{vec}.
@end deftypefn

@deftypefn {Macro} {void *} SCM_UVECTOR_ELEMENTS (ScmObj @var{vec})
Returns the pointer to the array of the uniform vector contents.
@end deftypefn

@deftypefn {Macro} int SCM_UVECTOR_SIZE (ScmObj @var{vec})
Returns the number of elements of the uniform vector @var{vec}.
@end deftypefn

@deftypefn {Macro} int SCM_UVECTOR_IMMUTABLE_P (ScmObj @var{vec})
Returns non-zero if the uniform vector is immutable.
@end deftypefn

@deftypefn {Macro} void SCM_UVECTOR_IMMUTABLE_SET (ScmObj @var{vec}, @var{flags})
Sets immutable state of the uniform vector @var{vec}.
@end deftypefn

@deftypefn {Macro} void SCM_UVECTOR_CHECK_MUTABLE (ScmObj @var{vec})
Raise an error if the uniform vector @var{vec} is immutable.
@end deftypefn

@deftypefn {Macro} int SCM_UVECTOR_SUBTYPE_P (ScmObj @var{vec}, ScmUVectorType @var{type})
Returns true if the uniform vector @var{vec} is of type @var{type}.
@end deftypefn

@deftypefun ScmUVectorType Scm_UVectorType (ScmClass @var{klass})
Returns the vector type of the uniform vector class @var{klass}.
@end deftypefun

@deftypefun {const char *} Scm_UVectorTypeName (int @var{type})
Converts @var{type} (of type @code{ScmUVectorType} actually) to a
string.
@end deftypefun

@deftypefun int Scm_UVectorElementSize (ScmClass @var{klass})
Returns the element type in bytes of the uniform vector class
@var{klass}.
@end deftypefun

@deftypefun int Scm_UVectorSizeInBytes (ScmUVector *@var{vec})
Returns the size in bytes of the uniform vector @var{vec}.
@end deftypefun

@deftypefun ScmObj Scm_MakeUVector (ScmClass *@var{klass}, ScmSmallInt @var{size}, void *@var{init})
Returns a mutable uniform vector of type @var{klass}, @var{size}
elements and no owner. The vector data is contained in @var{init},
which must be properly prepared by the caller. This normally is
allocated in heap. But it could also be from other sources, e.g. mmap.
@end deftypefun

@deftypefun ScmObj Scm_MakeUVectorFull (ScmClass *@var{klass}, ScmSmallInt @var{size}, void *@var{init}, int @var{immutablep}, void *@var{owner})
Creates a new uniform vector. This is the extended version of
@code{Scm_MakeUVector} that lets you control both owner and immutable
state.
@end deftypefun

@deftypefun ScmObj Scm_ListToUVector (ScmClass *@var{klass}, ScmObj @var{list}, ScmSmallInt @var{start}, ScmSmallInt @var{end})
Creates a uniform vector of class @var{klass} from @var{start}-th
element (inclusive) to @var{end}-th element (exclusive) of a list
@var{list}.  @var{end} can be @code{-1} to indicate the end of the
list.
@end deftypefun

@deftypefun ScmObj Scm_UVectorSet (ScmUVector *@var{vec}, int @var{t}, int @var{k}, ScmObj @var{val}, int @var{clamp})
Sets @var{k}-th element of a vector @var{vec} (of type @var{type}) by
@var{val}. See @ref{Scheme number objects} for @var{clamp}.
Always return @var{obj}.
If @var{k} is out of range, no operation is performed and an error is
signalled.
@end deftypefun

@deftypefun ScmObj Scm_Make@var{tag}Vector (ScmSmallInt @var{size}, type @var{fill})
@deftypefunx ScmObj Scm_Make@var{tag}VectorFromArray (ScmSmallInt @var{size}, const type @var{array}[])
@deftypefunx ScmObj Scm_Make@var{tag}VectorFromArrayShared (ScmSmallInt @var{size}, type @var{array}[])
For all supported uniform vector types, there are three functions each
type to create a vector of the type in question.
@itemize
@item
The first variant creates a mutable vector automatically allocated on
heap.
@item
The second variant initializes heap allocated vector data with
@var{array}.
@item
The third variant directly uses @var{array} as the vector data.
@end itemize
@end deftypefun


@node Dictionaries, Weak pointers, Vectors, C API reference
@section Dictionaries

Dictionaries are data structures that maps a key object to
a value object.  Gauche provides two kinds of basic dictionaries:
hash tables and tree maps.

Each kind of dictionary has two layers of API: The 'core'
API (@code{ScmHashCore}, @code{ScmTreeCore}) works on a
C structure, and deals with raw C pointers.  On top of core
API, Scheme-level objects (@code{ScmHashTable}, @code{ScmTreeMap})
are defined.  There are other built-in structures that are built
on opt of core API; for example, @code{ScmCharSet} uses
@code{ScmTreeCore} internally, and there's a plan to provide
@code{ScmWeakHashTable} which will be built on top of @code{ScmHashCore}.

@menu
* Common dictionary interface::
* Hash tables::
* Tree maps::
@end menu

@node Common dictionary interface, Hash tables, Dictionaries, Dictionaries
@subsection Common dictionary interface

Since there are lots of similarities between hash tables and tree maps,
they share some common data structures and enums.

@deftp {Enum} ScmDictSetFlags
These are bitflags @code{Scm_HashTableSet} and @code{Scm_TreeMapSet} take.

@table @code
@item SCM_DICT_NO_OVERWRITE
If this flag is given, the function does not overwrite an existing entry;
it only adds a new entry if no existing entry has the given key.
@item SCM_DICT_NO_CREATE
If this flag is given, the function does not add a new entry;
it only changes the value of the existing entry.
@end table
@end deftp

If both @code{SCM_DICT_NO_OVERWRITE} and @code{SCM_DICT_NO_CREATE} are
given, the behavior is undefined.  In future it is possible that we have
more flags.

Each key-value pair in a dictionary is kept in
a @code{ScmDictEntry} structure.  The low-level access
functions (@code{Scm_HashCoreSearch} and @code{Scm_TreeCoreSearch}),
and iterators (@code{Scm_HashIterNext} and @code{Scm_TreeCoreNext} etc.)
returns a pointer to this structure.

@deftp {Struct} ScmDictEntry
@example
typedef struct ScmDictEntryRec @{
    const intptr_t  key;
    intptr_t  value;
@} ScmDictEntry;
@end example
@end deftp

Note that they can be used to keep non-@code{ScmObj}s, so the type of
key and value is @code{intptr_t}.  If you're accessing high-level
dictionaries @code{Scm_HashTable} and @code{Scm_TreeMap}, both
of which are designed to store @code{ScmObjs}, you should use the following
accessor macros to retrieve @code{ScmObj}s.

@deftypefn {Macro} ScmObj SCM_DICT_KEY (ScmDictEntry* @var{entry})
@deftypefnx {Macro} ScmObj SCM_DICT_VALUE (ScmDictEntry* @var{entry})
Accesses the key and the value fields of @code{ScmDictEntry} as
@code{ScmObj}s, respectively.
@end deftypefn

@deftypefn {Macro} ScmObj SCM_DICT_SET_VALUE (ScmdictEntry* @var{entry}, ScmObj @var{value})
Sets @var{value} to the value field of @var{entry} and returns
@var{value} itself.

The caller have to make sure @var{value} is a valid @code{ScmObj}.
Particularly, it is prohibited to pass @code{SCM_UNBOUND} as @var{value}.
@end deftypefn

Each core dictionary API provides a search function that takes
operation (@code{op}) argument, which must be one of the following
values:

@deftp {Enum} ScmDictOp
@table @code
@item SCM_DICT_GET
The search function returns @code{ScmDictEntry*} if found,
@code{NULL} otherwise.
@item SCM_DICT_CREATE
The search function creates a new entry if the given entry
is not found.  Always returns @code{ScmDictEntry*}.
@item SCM_DICT_DELETE
The search function deletes a found entry from the dictionary.
Returns @code{NULL} if no entry is found.
Otherwise returns @code{ScmDictEntry*}
which is just deleted from the dictionary.
@end table
@end deftp

@node Hash tables, Tree maps, Common dictionary interface, Dictionaries
@subsection Hash tables

@subsubheading Low-level API

@deftp {Enum} ScmHashType
Specifies the pre-defined hash table types.  Except @code{SCM_HASH_GENERAL},
each type implies specific hash and compare functions.
@table @code
@item SCM_HASH_EQ
@code{eq?}-type hashtables.  Compare function is @code{SCM_EQ},
and hash function is @code{Scm_EqHash}.
@item SCM_HASH_EQV
@code{eqv?}-type hashtables.  Compare function is @code{Scm_Eqv},
and hash function is @code{Scm_EqvHash}.
@item SCM_HASH_EQUAL
@code{equal?}-type hashtables.  Compare function is @code{Scm_Equal},
and hash function is @code{Scm_Hash}.
@item SCM_HASH_STRING
@code{string=?}-type hashtables.  Compare function is @code{Scm_StringEqual},
and hash function is @code{Scm_HashString}.
@item SCM_HASH_WORD
Non-@code{ScmObj} one-word hashtables.  Comparison is @code{==},
and hash is @code{Scm_EqHash}.  The table may keep arbitrary machine words,
not only @code{ScmObj}s.
@item SCM_HASH_GENERAL
A generic hashtable that uses user-provided comparison and hash functions.
Currently this type of hashtables is not well supported; more support is
planned in future.
@end table
@end deftp

@deftp {Struct} ScmHashCore
A C struct to hold a hash table.  This structure is not an @code{ScmObj},
and supposed to be used embedded in other structures.
@end deftp

@deftypefun void Scm_HashCoreInitSimple (ScmHashCore *@var{core}, ScmHashType @var{type}, unsigned int @var{initSize}, void *@var{data})
Initialize a hash core structure pointed by @var{core}, with predefined
hash and compare functions determined by the @var{type} argument.
You can pass one of the @code{ScmHashType} enums except
@code{SCM_HASH_GENERAL} to @var{type}.

If you know rough number of hashtable entries, you can tell it by
@var{initSize} argument so that the hashtable may be optimized for
that size.  Passing 0 makes the function to choose a reasonable value.

The @var{data} argument is an opaque pointer for the application.
@end deftypefun

@deftypefun void Scm_HashCoreCopy (ScmHashCore *@var{dst}, const ScmHashCore *@var{src})
Copies the content of @var{src} to @var{dst}, including the hash type,
hash function and compare function.  The original content of @var{dst}
is destroyed.  It is OK to pass uninitialized @code{ScmHashCore} as @var{dst}.
@end deftypefun

@deftypefun {ScmDictEntry *} Scm_HashCoreSearch (ScmHashCore *@var{core}, intptr_t @var{key}, ScmDictOp @var{op})
Searches an entry with the given @var{key}, and and perform the operation
specified by @var{op}, which must be either @code{SCM_DICT_GET},
@code{SCM_DICT_CREATE}, or @code{SCM_DICT_DELETE}.

Returns a pointer to the found, created or deleted entry.  For
get and delete operations it may return @code{NULL} if there's no
entry found for @var{key}.
@end deftypefun

@deftypefun int Scm_HashCoreNumEntries (ScmHashCore *@var{core})
Returns the current number of entries in the hash core.
@end deftypefun

@subsubheading Iterators

@deftp {Struct} ScmHashIter
An opaque structure to iterate over a hash table.
This is not an @code{ScmObj}.

You can modify the value of the entries while iterating over
a hash table; however, once an entry is added or deleted,
the behavior of existing iterators become undefined.
@end deftp

@deftypefun void Scm_HashIterInit (ScmHashIter *@var{iter}, ScmHashCore *@var{core})
Initializes an iterator @var{iter} to iterate through a hash core @var{core}.
At the beginning, the iterator points to an imaginary entry just before
the first entry, so that the first call of @code{Scm_HashIterNext} returns
the first entry.
@end deftypefun

@deftypefun {ScmDictEntry *} Scm_HashIterNext (ScmHashIter *@var{iter})
Updates the iterator @var{iter} to point to the next entry, then
returns it.  If the iterator has visited all entries, @code{NULL}
is returned.
@end deftypefun

@subsubheading Hash functions

Other than @code{Scm_EqHash} and @code{Scm_EqvHash}, which returns
a value that depends on the run-time address of the objects,
hash values depend on the @emph{salt} value, which is initialized
randomly at the process initialization time.

@deftypefun {u_long} Scm_EqHash (ScmObj @var{obj})
Calculates hash value of the object suitable for @code{eq?}-type
hash table.
@end deftypefun

@deftypefun {u_long} Scm_EqvHash (ScmObj @var{obj})
Calculates hash value of the object suitable for @code{eqv?}-type
hash table.
@end deftypefun

@deftypefun {u_long} Scm_HashString (ScmString *@var{str}, unsigned long @var{bound})
@end deftypefun

@deftypefun {u_long} Scm_PortableHash (ScmObj @var{obj}, u_long salt)
@end deftypefun

@deftypefun {ScmSmallInt} Scm_DefaultHash (ScmObj @var{obj})
@end deftypefun

@deftypefun {ScmSmallInt} Scm_RecursiveHash (ScmObj @var{obj}, ScmSmallInt salt, u_long flags)
@end deftypefun

@deftypefun {ScmSmallInt} Scm_SmallIntHash (ScmSmallInt val, ScmSmallInt salt, u_long flags)
@end deftypefun

@deftypefun {ScmSmallInt} Scm_Int64Hash (int64_t val, ScmSmallInt salt, u_long flags)
@end deftypefun

@deftypefun u_long Scm_CombineHashValue (u_long a, u_long b)
@end deftypefun

@deftypefun ScmSmallInt Scm_HashSaltRef (void)
@deftypefunx ScmSmallInt Scm_HashSaltSet (ScmSmallInt salt)
@end deftypefun

@deftypefun ScmSmallInt Scm_PortableHashSalt (ScmObj newval)
@end deftypefun


@subsubheading Scheme HashTable object

@deftp {ScmObj} ScmHashTable
@end deftp

@deftypefn {Macro} int SCM_HASH_TABLE_P (ScmObj @var{obj})
Type predicate.
@end deftypefn

@deftypefn {Macro} {ScmHashTable *} SCM_HASH_TABLE (ScmObj @var{obj})
Typecast macro.
@end deftypefn

@deftypefn {Macro} {ScmHashCore *} SCM_HASH_TABLE_CORE (ScmHashTable *@var{ht})
Returns a pointer to the @code{ScmHashCore} in the hash table @var{ht}.
@end deftypefn

@deftypefn {Macro} {ScmHashCore *} SCM_HASH_TABLE_CORE (ScmHashTable *@var{ht})
Returns a pointer to the @code{ScmHashCore} in the hash table @var{ht}.
@end deftypefn

@deftypefun ScmObj Scm_MakeHashTableSimple (ScmHashType @var{type}, int @var{initSize})
@end deftypefun



@node Tree maps,  , Hash tables, Dictionaries
@subsection Tree maps

A tree map uses balanced binary tree to store the key-value pair.
Entry retrieval and modification is O(log(n)).

@subsubheading Low-level API

@deftp {Struct} ScmTreeCore
A C struct to hold a tree map.  This structure is not an @code{ScmObj},
and supposed to be used embedded in other structures.
@end deftp

@deftp {Function Prototype} ScmTreeCompareProc
@example
typedef int ScmTreeCoreCompareProc(ScmTreeCore* tc,
                                   intptr_t k1,
                                   intptr_t k2);
@end example
Called when the tree map routine need to compare keys, @var{k1}
and @var{k2}.  The function must return @code{-1} if @var{k1}
is before @var{k2}, @code{0} if @var{k1} and @var{k2} is the same,
and @var{1} if @var{k1} is after @var{k2}.
@end deftp

@deftypefun void Scm_TreeCoreInit (ScmTreeCore *@var{tc}, ScmTreeCoreCompareProc *@var{cmp}, void *@var{data})
Initializes @code{ScmTreeCore} structure @var{tc}, using @var{cmp}
as the compare procedure.  Whatever information @var{tc} has been
carrying will be lost.
@end deftypefun

@deftypefun void Scm_TreeCoreCopy (ScmTreeCore *@var{dst}, const ScmTreeCore *@var{src})
Copies the content of @var{src} into @var{dst}.  Whatever information
in @var{dst} will be lost.
@end deftypefun

@deftypefun {ScmDictEntry *} Scm_TreeCoreSearch (ScmTreeCore *@var{tc}, intptr_t @var{key}, ScmDictOp @var{op})
Searches an entry with the given @var{key}, and perform the operation
specified by @var{op}, which must be either @code{SCM_DICT_GET},
@code{SCM_DICT_CREATE}, or @code{SCM_DICT_DELETE}.

Returns a pointer to the found, created or deleted entry.  For
get and delete operations it may return @code{NULL} if there's no
entry found for @var{key}.
@end deftypefun

@deftypefun {ScmDictEntry *} Scm_TreeCoreClosestEntries (ScmTreeCore *@var{tc}, intptr_t @var{key}, ScmDictEntry **@var{lo}, ScmDictEntry **@var{hi})
Searches an entry with the given @var{key} and returns an exact match,
or @code{NULL} if there's no exact match.  Besides that, it stores
the pointers of entries closest to the given key, from below the key
and above the key, in the location pointed by @var{lo} and @var{hi},
respectively.  If the tree core has exact match, @var{*lo} and @var{*hi}
will have pointers to the immediately previous and next entries.
If the tree core doesn't have exact match, the given key is
between the keys of two entries pointed by @var{*lo} and @var{*hi}.

As a boundary case, if the given key is smaller than the smallest
key in @var{tc}, @var{*lo} is @code{NULL}; if the given key is greater
than the greatest, @var{*hi} is @code{NULL}; and if @var{tc} is empty,
both @var{*lo} and @var{*hi} is @code{NULL}.
@end deftypefun

@deftp {Enum} ScmTreeCoreBoundOp
Specify which side you're operating of the call to
@code{ScmTreeCoreGetBound} and @code{ScmTreeCorePopBound}.

@table @code
@item SCM_TREE_CORE_MIN
Operate on the entry of the minimum (smallest) key.
@item SCM_TREE_CORE_MAX
Operate on the entry of the maximum (greatest) key.
@end table
@end deftp

@deftypefun {ScmDictEntry *} Scm_TreeCoreGetBound (ScmTreeCore *@var{tc}, ScmTreeCoreBoundOp @var{op})
Returns the entry in @var{tc} with the minimum or maximum key, as
specified by @var{op} argument.  May return @code{NULL} if @var{tc}
is empty.
@end deftypefun

@deftypefun {ScmDictEntry *} Scm_TreeCorePopBound (ScmTreeCore *@var{tc}, ScmTreeCoreBoundOp @var{op})
Finds the entry in @var{tc} with the minimum or maximum key, as
specified by @var{op} argument, and removes the entry from @var{tc},
then returns the entry.  If @var{tc} is empty, no operation is
performed and @code{NULL} is returned.
@end deftypefun

@deftypefun int Scm_TreeCoreNumEntries (ScmTreeCore *@var{tc})
Returns the number of entries in @var{tc}.
@end deftypefun

@subsubheading Iterators

@deftp {Struct} ScmTreeIter
An iterator over a tree map.  This is not an @code{ScmObj}.
Must be treated as opaque structure.

An iterator can point to one of the entries in a tree core,
or @code{NULL}.  The @code{NULL} indicates the iterator is
outside of the tree---it's both below the minimum key and above
the maximum key simultaneously.  That is, when an iterator points
to @code{NULL}, when you call @code{Scm_TreeIterNext} you'll get
the minimum key entry, while you call @code{Scm_TreeIterPrev} and
you'll get the maximum key entry.

You can modify the value of the entries while iterating over
a tree map; however, once an entry is added or deleted,
the behavior of existing iterators become undefined.
@end deftp

@deftypefun void Scm_TreeIterInit (ScmTreeIter *@var{iter}, ScmTreeCore *@var{tc}, ScmDictEntry *@var{start})
Initializes an iterator @var{iter} over a tree core @var{tc}.
If @var{start} is NULL, the iterator is set just before the smallest
entry in @var{tc} (i.e. the next call to @var{Scm_TreeCoreNext} will
return the smallest entry); otherwise, the iterator points the given entry
(i.e. the next call to @var{Scm_TreeCoreNext} will return the next
entry of @var{start}).
In the latter case, @var{start} must points to an entry in @var{tc},
otherwise an error is signalled.
@end deftypefun

@deftypefun {ScmDictEntry *} Scm_TreeIterCurrent (ScmTreeIter *@var{iter})
Returns the entry the iterator currently pointing.  Can be @code{NULL}.
@end deftypefun

@deftypefun int Scm_TreeIterAtEnd (ScmTreeIter *@var{iter})
Returns @code{TRUE} iff the iterator has been pointing inside the tree
and now pointing @code{NULL} after calling either @code{ScmTreeIterNext}
or @code{ScmTreeIterPrev}.

If you call @code{ScmTreeIterNext} on an iterator that is "at end",
it starts from the minimum key entry; likewise, @code{ScmTreeIterPrev}
makes it starts from the maximum key entry.  In either case, "at end"
flag is cleared.
@end deftypefun

@deftypefun {ScmDictEntry *} Scm_TreeIterNext (ScmTreeIter *@var{iter})
@deftypefunx {ScmDictEntry *} Scm_TreeIterPrev (ScmTreeIter *@var{iter})
Moves the iterator to the next or previous entry and returns it,
respectively.
If the iterator was pointing the maximum (minimum) key entry
before calling @code{Scm_TreeIterNext} (@code{Scm_TreeIterPrev}),
@code{NULL} is returned and the iterator becomes "at end" state
(i.e. @code{Scm_TreeIterAtEnd} returns @code{TRUE}).
@end deftypefun

@subsubheading Scheme TreeMap object

@deftp {ScmObj} ScmTreeMap
This is the Scheme's @code{<tree-map>} object.  It contains
@code{ScmTreeCore}, whose pointer can be obtained
by the macro @code{SCM_TREE_MAP_CORE}.
@end deftp

@deftypefn {Macro} {ScmTreeMap *} SCM_TREE_MAP (ScmObj @var{obj})
Cast macro.
@end deftypefn

@deftypefn {Macro} int SCM_TREE_MAP_P (ScmObj @var{obj})
Type predicate.
@end deftypefn

@deftypefn {Macro} {ScmTreeCore *} SCM_TREE_MAP_CORE (ScmTreeMap *@var{obj})
Returns the pointer to the @code{ScmTreeCore} part in a tree map.
@end deftypefn

@deftypefn {Macro} {void *} SCM_TREE_MAP_DATA (ScmTreeMap *@var{obj})
Returns the opaque data in a tree map.
@end deftypefn

@deftypefun ScmObj Scm_MakeTreeMap (ScmTreeCoreCompareProc *@var{cmp}, void *@var{data})
Creates an instance of @code{<tree-map>} object, using the given
comparison function and the opaque data.  Although it is built on
top of @code{ScmTreeCore}, it is supposed that @code{ScmTreeMap}'s
entry always have @code{ScmObj} in both key and value.  If C code
violates that, the outcome will be undefined.

(If you need to have a tree map with raw C pointers exposed to Scheme
world, create your own type using @code{ScmTreeCore}.)
@end deftypefun

@deftypefun ScmObj Scm_TreeMapCopy (const ScmTreeMap *@var{src})
Returns a newly created tree map, whose content is a copy
of the given tree map.
@end deftypefun

@deftypefun ScmObj Scm_TreeMapRef (ScmTreeMap *@var{tm}, ScmObj @var{key}, ScmObj @var{fallback})
Searches an entry with the given @var{key}, and returns its value.
If there's no entry that has @var{key}, a value passed to @var{fallback}
is returned (unlike Scheme-level @code{tree-map-get}, it doesn't
signals an error).

A standard way to take a specific action when no entry is found is
to pass @code{SCM_UNBOUND} as @var{fallback}, since @code{SCM_UNBOUND}
should never appear as the valid value.

@example
ScmObj v = Scm_TreeMapRef(tm, key, SCM_UNBOUND);
if (SCM_UNBOUNDP(v)) /* no entry for the key */
@end example
@end deftypefun

@deftypefun ScmObj Scm_TreeMapSet (ScmTreeMap *@var{tm}, ScmObj @var{key}, ScmObj @var{val}, ScmObj @var{flags})
Sets @var{val} as the value of the entry that has @var{key}.
@code{Flags} is a bitwise-OR of @code{ScmDictSetFlags}.
Passing 0 to @var{flags} achieves the common action
to modify the entry if it exists, and to create a new one otherwise.
If @var{flags} has @code{SCM_DICT_NO_OVERWRITE} bit set, it won't
modify the existing entry, and only adds a new one if the entry
hasn't existed.  If @var{flags} has @code{SCM_DICT_NO_CREATE},
it modifies if the entry exists, but do not add a new one otherwise.
(The effect of specifying both bits is undefined).

Returns the value of the entry of @var{key} after the operation,
or @code{SCM_UNBOUND} iff @code{SCM_DICT_NO_CREATE} is given to the
@var{flags} and no new entry is created.
@end deftypefun

@deftypefun ScmObj Scm_TreeMapDelete (ScmTreeMap *@var{tm}, ScmObj @var{key})
Deletes the entry that has @var{key}.  If the entry has existed,
returns its value.  Otherwise, returns @code{SCM_UNBOUND}.
@end deftypefun

@deftypefun void Scm_TreeMapDump (ScmTreeMap *@var{tm}, ScmPort *@var{out})
This is for debugging.  Dumps the content of tree map with
its internal structure to the given port @var{out}.
@end deftypefun




@node Weak pointers, Exceptions, Dictionaries, C API reference
@section Weak pointers

@node Exceptions, Calling back to Scheme, Weak pointers, C API reference
@section Exceptions

@node Calling back to Scheme, Input and output, Exceptions, C API reference
@section Calling back to Scheme

@node Input and output, Loading programs, Calling back to Scheme, C API reference
@section Input and output

@menu
* Built-in ports::
* Custom ports::
* Input::
* Output::
@end menu

@node Built-in ports, Custom ports, Input and output, Input and output
@subsection Built-in ports

@subsubheading Opening and closing ports

@deftypefun ScmObj Scm_OpenFilePort (const char *path, int flags, int buffering, int perm)
Open a file named by @var{path}, and returns a newly created Scheme port
associated with the file.   The @code{name} slot of the created port
is set as @var{path}.

The @var{flags} and @var{perm} arguments are passed to @code{open(2)}
as the second and third argument, respectively.  The @var{buffering}
argument may be either one of @code{SCM_PORT_BUFFER_FULL},
@code{SCM_PORT_BUFFER_LINE} or @code{SCM_PORT_BUFFER_NONE},
specifying the buffering mode.

If a file couldn't be opened, @code{SCM_FALSE} is returned.  The
reason can be obtained from @code{errno}.
@end deftypefun

@deftypefun ScmObj Scm_MakePortWithFd (ScmObj name, int direction, int fd, int bufmode, int ownerp)
Creates a Scheme port that read from or write to the specified file
descriptor @var{fd}.  The @var{name} argument is used for the
port's @var{name} slot.  You need to specify either
@code{SCM_PORT_INPUT} or @code{SCM_PORT_OUTPUT} as the direction.
The @var{buffering}
argument may be either one of @code{SCM_PORT_BUFFER_FULL},
@code{SCM_PORT_BUFFER_LINE} or @code{SCM_PORT_BUFFER_NONE},
specifying the buffering mode.

If @var{ownerp} is @code{TRUE}, the created Scheme port becomes the owner
of the file descriptor; that is, when the Scheme port is closed,
it closes the file descriptor, too.
@end deftypefun

@deftypefun ScmObj Scm_MakeInputStringPort (ScmString *@var{str}, int @var{privatep})
Returns a Scheme string port that reads from the given Scheme string.
Corresponds to Scheme's @code{open-input-string}.

If @var{privatep} is @code{TRUE}, the port is pre-locked by the
current thread; i.e. no other threads can access this port, and
the current thread avoids locking overhead.
@end deftypefun

@deftypefun ScmObj Scm_MakeOutputStringPort (int @var{privatep})
Returns a Scheme output string port that collects the stuff written to it.
You can retrieve the result string by @code{Scm_GetOutputString()} below.
Corresponds to Scheme's @code{open-output-string}.

The @var{privatep} flag is the same as @code{Scm_MakeInputStringPort}.
@end deftypefun

@deftypefun ScmObj Scm_GetRemainingInputString (ScmPort *@var{port}, int @var{flags})
@var{port} must be an input string port created by
@code{Scm_MakeInputStringPort}.
Returns a newly-created Scheme string which contains the stuff
in the original string which hasn't been read.

By default, the result string is mutable, and complete as long as
it doesn't contain illegal byte sequences.  You may explicitly
make it immutable and/or incomplete by giving
string constructor flags (@code{SCM_STRING_IMMUTABLE}
and/or @code{SCM_STRING_INCOMPLETE}) to the @var{flags} argument
(@pxref{Strings}).
@end deftypefun

@deftypefun ScmObj Scm_GetOutputstring (ScmPort *@var{port}, int @var{flags})
Returns a newly-created Scheme string from the output string port @var{port},
created by @code{Scm_MakeOutputStringPort}.

By default, the result string is mutable, and complete as long as
it doesn't contain illegal byte sequences.  You may explicitly
make it immutable and/or incomplete by giving
string constructor flags (@code{SCM_STRING_IMMUTABLE}
and/or @code{SCM_STRING_INCOMPLETE}) to the @var{flags} argument
(@pxref{Strings}).
@end deftypefun

@deftypefun void Scm_ClosePort (ScmPort *@var{port})
Close the port.  If it is already closed, nothing is done.
Closing port invokes a cleanup handler associated to the port.
For example, buffered output port may flush its buffer in the
handler.  The cleanup handler may run a Scheme code, if the port
is a procedural port.  An error caused in a cleanup handler will
raises Scheme exception (i.e. Scm_ClosePort may not return if an error
is raised); such errors should be handled by Scheme error handling
framework.
@end deftypefun

@subsubheading General port information

@deftypefun ScmObj Scm_PortName (ScmPort *@var{port})
Returns the value of @code{name} slot of the port.
If the port is a file port, its name contains the original pathname
of the file.  For other ports, the name field contains some
description of ports only useful for debug messages.
@end deftypefun

@deftypefun int Scm_PortLine (ScmPort *@var{port})
Returns the value of @var{line} slot of the port.
Most built-in port types keeps track of the line count,
as far as (1) only character I/O is performed, and
(2) no random-access operation is performed, on the port.
If either of such operation is done on the port, the number
returned from this function doesn't have meaning.

Port line count begins with 1.
@end deftypefun

@deftypefun int Scm_PortFileNo (ScmPort *@var{port})
Returns the port's associated file descriptor number, if any.
Returns -1 otherwise.
@end deftypefun

@subsubheading Locking ports

@subsubheading Pre-created ports

@deftypefn {Macro} ScmPort* SCM_CURIN
@deftypefnx {Macro} ScmPort* SCM_CUROUT
@deftypefnx {Macro} ScmPort* SCM_CURERR
These macro returns the current input, output, and error port
of the current VM, respectively.  Corresponds to Scheme's
@code{(current-input-port)}, @code{(current-output-port)},
and @code{(current-error-port)}.
@end deftypefn


@deftypefun ScmObj Scm_Stdin (void)
@deftypefunx ScmObj Scm_Stdout (void)
@deftypefunx ScmObj Scm_Stderr (void)
These functions returns ports associated to file descriptor
0, 1, or 2, respectively.  Generally you should use
@code{SCM_CURIN} macro etc., described above, since they're
in sync with Scheme-world's current ports.  However, if you
have a reason to access to stdio specifically, you may use
these functions.
@end deftypefun


@node Custom ports, Input, Built-in ports, Input and output
@subsection Custom ports

There are two ways to extend port functionalities and creates
your own port types.  A @emph{fully virtual port} basically has
all basic port I/O operations as virtual functions, so you
can override those functionalities as you like.
A @emph{virtual buffered port}, on the other hand, implements
buffering by itself, and calls back your routines when it needs
more data to read or it needs to flush the buffer.

(See the @code{gauche.vport} entry of the Gauche Users' Reference
for the Scheme counterparts of these custom ports)

@subsubheading Fully virtual ports

@deftypefun ScmObj Scm_MakeVirtualport (ScmClass *@var{klass}, int @var{direction}, const ScmPortVTable *@var{vtable})
Returns a newly created fully virtual port of class @var{klass},
which must be a subclass of @code{SCM_CLASS_PORT}.

You need prepare the structure @var{vtable} to specify the behavior
of the port.   You can leave some of the fields NULL, if the
functionality is not needed in the port's operation.
The content of the @var{vtable} will be copied,
so you don't need to keep it after the call of @code{Scm_MakeVirtualPort}.

@example
typedef struct ScmPortVTableRec @{
    int       (*Getb)(ScmPort *p);
    int       (*Getc)(ScmPort *p);
    int       (*Getz)(char *buf, int buflen, ScmPort *p);
    int       (*Ready)(ScmPort *p, int charp);
    void      (*Putb)(ScmByte b, ScmPort *p);
    void      (*Putc)(ScmChar c, ScmPort *p);
    void      (*Putz)(const char *buf, int size, ScmPort *p);
    void      (*Puts)(ScmString *s, ScmPort *p);
    void      (*Flush)(ScmPort *p);
    void      (*Close)(ScmPort *p);
    off_t     (*Seek)(ScmPort *p, off_t off, int whence);
    void      *data;
@} ScmPortVTable;
@end example

For a character input port, you must provide at least @code{Getc}
procedure.  For a binary input port, you must provide at least
@code{Getb} and @code{Getz} procedures.  For a general input port,
on which binary or character input can be done, you must provide
at least those three procedures.

@code{Getb} should return an 8bit unsigned integer value read from
the port, or @code{EOF} if the port has already reached EOF.
@code{Getc} should return an @code{ScmChar} read from the port,
or @code{SCM_CHAR_INVALID} if the port has already reached EOF.
@code{Getz} should read at most @var{buflen} bytes from the port
and store it in @var{buf}, then returns the number of bytes
actually read.   Returning @code{0} indicates the port has
already reached EOF.

For a character output port you must provide at least @code{Putc}
and @code{Puts} procedures.  For a binary output port you must
provide at least @code{Putb} and @code{Putz} procedures.
For a general output port you must provide at least those four
procedures.

@code{Putb} and @code{Putc} write a byte or a character
to the port, respectively.  @code{Putz} writes @var{size} bytes
in @var{buf} to the port.  @code{Puts} writes the content of
the given Scheme string to the port.

The @code{Ready} procedure is optional for an input port.
If provided, it is called when @code{char-ready?} or @code{byte-ready?}
Scheme procedure is called on the port (the @var{charp} is @code{TRUE}
for @code{char-ready?}, and @code{FALSE} for @code{byte-ready?}).
It must return @code{TRUE} if a character or a byte is ready to
be read from the port, @code{FALSE} otherwise.
If @code{Ready} procedure is not provided, the port is assumed to
be always ready.

The @code{Close} procedure is optional for a both input and output port.
It is called when the port is closed (either explicitly by
@code{Scm_ClosePort}, or implicitly by the port being garbage-collected).
For output port, @code{Flush} procedure is called just before @code{Close},
so you don't need to care about flushing in this procedure.

The @code{Flush} procedure is optional for an output port.
It is called when an explicit flushing is requested to the port
(such as @code{flush} Scheme procedure), or just before the
@code{Close} procedure when the port is closed.

It is important to note that @code{Close} and @code{Flush} procedures can
be called in finalization stage of the port.  That means (1) you
cannot predict in which thread these procedures are called, and
(2) at the time these procedures are called, the objects visible
from these procedures may already be finalized.  Extra care needs
to be taken to deal with those irregular situations.

The @code{Seek} procedure is called for seek operation (such as
@code{port-seek} Scheme procedure).   If you don't provide
this, the port becomes unseekable.

For all those procedures, error conditions should be reported
by Scheme exception mechanism.  Care should be taken not to leave
the port in inconsistent state in case an exception is thrown.

The @code{data} field may contain opaque data to be used in your
custom port operations.   Once the procedure port is created,
the value of this data pointer can be accessed by the macro
@code{SCM_PORT_VIRTUAL_DATA}.
@end deftypefun

@subsubheading Virtual buffered ports




@node Input, Output, Custom ports, Input and output
@subsection Input


@node Output,  , Input, Input and output
@subsection Output


@node Loading programs, System interface, Input and output, C API reference
@section Loading programs

@deftypefun ScmObj Scm_VMLoadFromPort (ScmPort *@var{port}, ScmObj @var{next_paths}, ScmObj @var{env}, int flags)
This is a CPS API.

The most basic function in the @code{load}-family.  Read an expression
from the given port and evaluates it repeatedly, until it reaches
EOF.  Then the port is closed.   The port is locked by the calling
thread until the operation terminates.

The result of the last evaluation remains on VM.

No matter how the load terminates, either normal or abnormal,
the port is closed, and the current module is restored to the
one when load is called.

@var{Flags} argument is ignored for now, but reserved for future
extension.  @code{SCM_LOAD_QUIET_NOFILE} and
@code{SCM_LOAD_IGNORE_CODING}
won't have any effect for @code{Scm_LoadFromPort};
see @code{Scm_Load} below.
@end deftypefun

@deftypefun ScmObj Scm_FindFile (ScmString *@var{filename}, ScmObj *@var{paths}, ScmObj @var{suffixes}, int @var{flags})
Core function to search specified file from the search paths *@var{path}.
Search rules are:

@enumerate
@item
If given filename begins with @file{/}, @file{./} or @file{../},
the file is searched.
@item
If given filename begins with @file{~}, unix-style username
expansion is done, then the resulting file is searched.
@item
Otherwise, the file is searched for each directory in
*@var{paths}.
@end enumerate

If a file is found, it's pathname is returned.  *@var{Path} is modified
to contain the remains of load paths, which can be used again to
find next matching filename.

If @var{suffixes} is given, filename is assumed not to have suffix,
and suffixes listed in @var{suffixes} are tried one by one.
The elements in @var{suffixes} is directly appended to the @var{filename};
so usually it begins with dot.

The following flag is effective in @var{flags}.  Other flags are ignored.
@table @code
@item SCM_LOAD_QUIET_NOFILE
If this flag is set, @code{Scm_FindFile} returns @code{SCM_FALSE}
when it cannot find the file.  If this flag is not set (default),
@code{Scm_FindFile} raises an error.
@end table
@end deftypefun


@node System interface,  , Loading programs, C API reference
@section System interface

Gauche provides a few wrapper APIs for operating system interface
to allow applications written without concerning

@c ======================================================================
@node Creating new Scheme datatypes, Helper program reference, C API reference, Top
@chapter Creating new Scheme datatypes





@c ======================================================================
@node Helper program reference, Indices, Creating new Scheme datatypes, Top
@chapter Helper program reference

Several executable scripts are installed along Gauche.
They are to help build and installation process.

@menu
* Managing packages::
* Simplifying build process::
* Gauche-config - configuration parameters::
* Gauche-install - alternative install script::
* Gauche-package - package manager::
@end menu

@node Managing packages, Simplifying build process, Helper program reference, Helper program reference
@section Managing packages

@deffn {Command} gauche-package @var{operation} [@var{option} @dots{}] [@var{arg} ...]

The @code{gauche-package} command is the front-end of managing
Gauche extension packages.  It can perform the various operations
according to @var{operation} argument.

@table @asis
@item Download, compile and install packages
@code{install}, @code{build}, @code{compile}
@item Retrieve info about installed packages
@code{list}, @code{reconfigure}, @code{make-gpd}
@item Help package development
@code{generate}
@item Instruct @code{gauche-package} usage
@code{help}
@end table

Among those operations, usually @code{install}, @code{build},
@code{list}, @code{generate} and @code{help} are used directly from
the shell.
Other operations are mainly invoked by @code{make} command.
@end deffn

@menu
* gauche-package operations::
* Customizing gauche-package ::
@end menu

@node gauche-package operations, Customizing gauche-package , Managing packages, Managing packages
@subsection gauche-package operations

@deffn {Package Operation} gauche-package install [@var{options}] @var{tarball-path/url}

This operation obtains the package source specified by @var{tarball-path/url},
then extracts the source, configures and builds,
runs the tests, and installs the built package.
Most of the time this is the only command required to install a Gauche
extension package.

The argument @var{tarball-path/url} may be a URL (http, https, and ftp
are supported), or a path to the local file of gzip-compressed tarball
of the package source.   If it is a URL, @code{gauche-package} downloads
it first.  By default @code{gauche-package} uses the current working
directory, but you can make it use specific directory by customizing
@file{~/.gauche-package} (@pxref{Customizing gauche-package}).

The following options are recognized by this operation.

@deffn {Option} -n, --dry-run
Shows shell commands to be executed, without running them.
@end deffn

@deffn {Option} -C, --configure-options=@var{options}
Pass @var{options} to the @code{./configure} script.  Overrides @code{-r}.
The following command configures the package with the option
@code{--prefix=/opt}.
@example
gauche-package install -C='--prefix=/opt' package.tgz
@end example

Those configure options are recorded in the package description
file
@end deffn


@end deffn


@node Customizing gauche-package ,  , gauche-package operations, Managing packages
@subsection Customizing gauche-package



@node Simplifying build process, Gauche-config - configuration parameters, Managing packages, Helper program reference
@section Simplifying build process



@deffn {Command} gauche-cesconv [options] [inputfile]
@end deffn

@node Gauche-config - configuration parameters, Gauche-install - alternative install script, Simplifying build process, Helper program reference
@section @code{gauche-config} - configuration parameters

@node Gauche-install - alternative install script, Gauche-package - package manager, Gauche-config - configuration parameters, Helper program reference
@section @code{gauche-install} - alternative install script




@node Gauche-package - package manager,  , Gauche-install - alternative install script, Helper program reference
@section @code{gauche-package} - package manager




@c ======================================================================
@node Indices,  , Helper program reference, Top
@appendix Indices
@c NODE 索引

@menu
* Function and Macro Index::
* Type Index::
* Variable Index::
@end menu

@node Function and Macro Index, Type Index, Indices, Indices
@appendixsec Function and Macro Index
@printindex fn


@node Type Index, Variable Index, Function and Macro Index, Indices
@appendixsec Type Index
@printindex tp

@node Variable Index,  , Type Index, Indices
@appendixsec Variable Index
@printindex vr

@contents
@bye

;; Local variables:
;; outline-regexp: "@chap\\|@\\(sub\\)*section"
;; end:
