\input texinfo  @c -*- mode: texinfo; coding: utf-8; -*-
@comment %**start of header
@c 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
@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

@iftex
@finalout
@parskip 4pt plus 1pt
@end iftex

@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 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, simplicity and safety are sometimes compromized
by efficiency.  For example, sometimes you have to choose
from similar APIs to achieve a goal, where each API is designed
to be efficient for a particular case.  The API also assumes
the caller takes care not to break internal structure; there's
no much safety net that protects you from shooting your foot.
(By saying "safety is compromized" I don't mean @file{libgauche}
has security holes; I mean it assumes the programmer knows what
he's doing.)

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 programer'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 chapetr 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 arises 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.8.8 or later
@item
GNU autoconf 2.54 or later
@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}).

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

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 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{trivial.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 generates
a C file from a stub file, and compiles 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.

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

@item Files to build the package (@file{configure.ac}, @file{Makefile.in}, @file{DIST})
Gauche relies on GNU @code{autoconf} and @code{make} to build
the package, that is, the package user can use the simple
@code{./configure}, @code{make} and @code{make install} sequence
to build and install the package.  

@file{DIST} is a small shell script that automates creating
a distribution tarball.

@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 @file{autoconf} to generate a @file{configure}
script.

@example
% @b{cd trivial}
% @b{autoconf}
% @b{ls}
DIST	     autom4te.cache  configure.ac  trivial.c  trivial.scm
Makefile.in  configure	     test.scm	   trivial.h  triviallib.stub
@end example

The directory @file{autom4te.cache} is a temporary structure used
by autoconf.  You can safely remove it if it bothers you.

Once @file{configure} script is generated, you can run it to
generate @file{Makefile}, then run @code{make}.

@example
% @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 ./config.status
config.status: creating Makefile
% @b{make}
/usr/bin/gauche-package compile --verbose trivial trivial.c triviallib.stub
@i{(... message truncated ...)}
% @b{ls}
DIST		config.log     trivial.c    trivial.so	    triviallib.o
Makefile	config.status  trivial.gpd  trivial_head.c  triviallib.stub
Makefile.in	configure      trivial.h    trivial_head.o
VERSION		configure.ac   trivial.o    trivial_tail.c
autom4te.cache	test.scm       trivial.scm  trivial_tail.o
@end example

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.

@example
% @b{gosh -I.}
gosh> @b{(use trivial)}
#<undef>
gosh> @b{(test-trivial)}
"trivial is working"
gosh>
@end example

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}.

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

For now, it just checks if the compiled extention 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}.

@example
% 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 example

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






@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


@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::                     
* Keywords::                    
* 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 objcts, 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.

@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 call @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 shoudn'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 messate, 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 desctipor 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 clanup 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 do 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


@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 anthing
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})
Compare 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 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; 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

@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})
Convert C @code{long} and @code{unsigned long} to a Scheme integer.
Always returns a normalized number.
@end deftypefun

@deftypefun long Scm_GetInteger (ScmObj obj)
@deftypefunx u_long Scm_GetIntegerU (ScmObj obj)
Convert a Scheme number to C @code{long} and @code{unsigned long},
respectively.  If @var{obj} is a flonum, it is rounded
to the nearest integer.  If @var{obj} is too small or too large to
fit in the C integer, it is clamped to the smallest or largest
integer representable in the result type; i.e. @code{LONG_MIN} and
@code{LONG_MAX} in @code{Scm_GetInteger}, and 
@code{0} and @code{ULONG_MAX} in @code{Scm_GetIntegerU}.

If @var{obj} is not a Scheme real number, an error is signalled.

These routines are actually the case that you specify @code{SCM_CLAMP_BOTH}
in the following routines.
@end deftypefun

@deftypefun long Scm_GetIntegerClamp (ScmObj @var{obj}, int @var{clamp}, int *@var{oor})
@deftypefunx u_long Scm_GetIntegerUClamp (ScmObj @var{obj}, int @var{clamp}, int *@var{oor})
More precise conversion routines, where you can specify the behavior
when the input value isn't in the valid range.

The @var{clamp} argument can be one of the @code{ScmClampMode} constants.
If @var{clamp} is @code{SCM_CLAMP_NONE} and @var{oor} is not @code{NULL},
the pointed location is set to @code{FALSE} if the input argument is within
the valid range, and @code{TRUE} otherwise; for the latter case, 0 is
returned as the result.
@end deftypefun

@subsubheading 32bit and 64bit integers

Sometimes you need to be aware of the width of integers
(for example, when you're working on uniform integer vectors).
Sometimes you even need to deal with 64-bit integers explicitly.

Since the widths of @code{int} and @code{long} are platform-dependent,
and support of 64bit integers varies among platforms,
Gauche provides an abstraction layer to them.

@deftp {Type} ScmInt32
@deftpx {Type} ScmUInt32
@deftpx {Type} ScmInt64
@deftpx {Type} ScmUInt64
These are typedef-ed to the platform-specific 32bit signed integer,
32bit unsigned integer, 64bit signed integer and 64bit unsigned 
integer, respectively.   If the platform doesn't support 64bit
integer at all, @code{ScmInt64} and @code{ScmUInt64} are a struct
type consist of two 32bit integers.
@end deftp

@deftypefun ScmInt32 Scm_GetInteger32Clamp (ScmObj @var{obj}, int @var{clamp}, int *@var{oor})
@deftypefunx ScmUInt32 Scm_GetIntegerU32Clamp (ScmObj @var{obj}, int @var{clamp}, int *@var{oor})
@deftypefunx ScmInt64 Scm_GetInteger64Clamp (ScmObj @var{obj}, int @var{clamp}, int *@var{oor})
@deftypefunx ScmUInt64 Scm_GetInteger64UClamp (ScmObj @var{obj}, int @var{clamp}, int *@var{oor})
These work like their generic counterparts, @code{Scm_GetIntegerClamp}
and @code{Scm_GetIntegerUClamp}, except they specifically work on
32-bit and 64-bit integers.
@end deftypefun

@deftypefun ScmObj Scm_MakeInteger64 (ScmInt64 @var{i})
@deftypefunx ScmObj Scm_MakeIntegerU64 (ScmUInt64 @var{i})
Create Scheme integers from 64bit signed and unsigned integers,
respectively.
@end deftypefun

@deftypefun ScmInt64 Scm_GetInteger64 (ScmObj obj)
@deftypefunx ScmUInt64 Scm_GetIntegerU64 (ScmObj obj)
Convenience procedures for @code{Scm_GetInteger64Clamp} and
@code{Scm_GetIntegerU64Clamp}, where the clamp parameter is
fixed to @code{SCM_CLAMP_BOTH}.
@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 as well).
If @var{obj} is not a Scheme real number, 0.0 is returned.
If @var{obj} is a bignum that can't be represented by @code{double},
an infinity (positive or negative, depends on @var{obj}'s sign)
is returned.
@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

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


@subsubheading Exact integer operations 

The folowing 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 siginificant 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.
@end deftypefun

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

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

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

@deftypefun ScmObj Scm_InexactToExact (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.
@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} int 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 (int @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








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

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

@deftp {Scheme Object} ScmSymbol
Represents the Scheme symbols.   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.
@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 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
(@xref{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, Keywords, Glocs, C API reference
@section Modules





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

@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})
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}.
@end deftypefun

@deftypefun ScmObj Scm_DeleteKeyword (ScmObj @var{key}, ScmObj @var{list})
Scheme's @code{delete-keyword}.
@end deftypefun

@deftypefun ScmObj Scm_DeleteKeywordX (ScmObj @var{key}, ScmObj @var{list})
Scheme's @code{delete-keyword!}.
@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 maked 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 Characters, Character sets, Keywords, 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 compilied 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 on ASCII characters properly.  For any other characters,
the predicates return @code{FALSE}, and the convertes
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.
It is just an identity function if Gauche's internal encoding
is utf-8.  Otherwise, it uses @code{gauche.charconv} module
to map the Unicode codepoint to a character code in the native encoding.

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 inbetween.
(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 constucted, 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}, unsignd 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{lis}, int @var{errp})
Converts a list of Scheme strings @var{lis} into C const string array,
@code{NULL} terminated.  If @var{errp} is true, an error is
signaled if @var{lis} 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{lis}, int @var{errp}, void *@var{alloc}(size_t))
Converts a list of Scheme strings @var{lis} 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; othewise @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{grammer})
Scheme's @var{string-join}.  Concatenates a list of strings @var{strs}
with inserting a delimiter @var{delim} between them.  The @var{grammer}
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 depens 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 opertaion.
@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{lis}, int @var{start}, int @var{end})
Creates a vector from @var{start}-th element (inculsive) to
@var{end}-th element (exclusive) of a list @var{lis}.
@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 (inculsive) 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})
Create 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


@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}.
Particulary, 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

A hash function calculates 32bit hash value from the given object.
(It is fixed to 32bits even on 64bit architectures, to guarantee
the same hash value across platforms).  Some of the functions 
used in built-in hash table types are provided as API.

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

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

@deftypefun {unsigned long} Scm_Hash (ScmObj @var{obj})
Calculates hash value of the object suitable for @code{equal?}-type
hash table.
@end deftypefun

@c @deftypefun {unsigned long} Scm_HashString (ScmString *@var{str}, unsigned long @var{bound})
@c @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 simulaneously.  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 prevoius 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 (unlinke 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
(@xref{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
(@xref{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 opertaion 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 virutal 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
accoring 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 opertaion 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} (@xref{Customizing gauche-package}).

The following options are recognized by this opertaion.

@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 -A索引$)B

@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:
