# The Binding Generator &C2hs;

Manuel Chakravarty chak@cse.unsw.edu.au
November 2007

&C2hs; is an interface generator that simplifies the development of Haskell bindings to C libraries. The tool processes existing C header files that determine data layout and function signatures on the C side in conjunction with Haskell modules that specify Haskell-side type signatures and marshaling details. Hooks embedded in the Haskell code signal access to C structures and functions -- they are expanded by the interfacing tool in dependence on information from the corresponding C header file. Another noteworthy property is the lightweight nature of the approach.

More background information is available in a research paper discussing &C2hs;, which is at . However, this paper does not cover the more recent advanced features such as function hooks and conditional compilation.

## Installation

It follows a brief discussion of the installation from source. There is, however, a file `INSTALL` in the source distribution, which is more frequently updated and should be consulted in any case.

### Where is the Source?

The master site of &C2hs; is at . It has all the latest information and sources. Furthermore, it explains how to get access to the &C2hs; Darcs repository and has references to pre-compiled binaries.

### What Else Do I Need?

You need a Haskell system supported by &C2hs;. Currently, this is only the Glasgow Haskell Compiler (GHC), which you can obtain from . Furthermore, you need the Haskell package system Cabal. See the `INSTALL` file for details on supported versions.

To build the documentation, you will also need the SGML Tools, which you find at your nearest sunsite or Linux mirror or at . On an up-to-date Linux system, the tools are probably already installed.

### I Got Everything, and Now?

The short answer is

    $ tar -xzf package.tar.gz      # unpack the sources
    $ cd package                   # change to the toplevel directory
    $ runghc Setup.hs configure    # configure the build system
    $ runghc Setup.hs build        # build everything
    [ Become root if necessary ]
    $ runghc Setup.hs install      # install c2hs

In the `INSTALL` file, there are more details.

Optionally, you can build the documentation by issuing `make doc` and install it with `make install-doc`.

## Usage of &C2hs;

Let's have a brief look at how to call the tool and how to use the generated interfaces.

### Usage of &c2hs;

&C2hs; is implemented by the executable &c2hs;. The simplest form of usage is

    c2hs Lib.chs

where Lib`.chs` is the Haskell binding module defining the Haskell interface to a C library together with the required marshalling code. If &c2hs; is invoked in this manner, the binding module must contain a cpp `#include` directive to determine the C-side interface of the library. Alternatively, a C header file can be specified on the command line, as in

    c2hs lib.h Lib.chs

However, the latter option is only preserved for backwards compatibility and not recommended. If no errors occur, &c2hs; generates three files:

1. a pure Haskell module Lib`.hs`, which implements the Haskell API of the library

2. a C header file Lib`.h` which some Haskell systems need to compile the generated Haskell code.

3. a &c2hs; interface file Lib`.chi` that is used by other binding modules that import Lib`.hs` using an import hook (see the section on import hooks for details).

The executable &c2hs; has a couple more options:

    Usage: c2hs [ option... ] [header-file] binding-file

      -C CPPOPTS   --cppopts=CPPOPTS    pass CPPOPTS to the C preprocessor
      -c CPP       --cpp=CPP            use executable CPP to invoke C preprocessor
      -d TYPE      --dump=TYPE          dump internal information (for debugging)
      -h, -?       --help               brief help (the present message)
      -i INCLUDE   --include=INCLUDE    include paths for .chi files
      -k           --keep               keep pre-processed C header
      -l           --copy-library       copy `C2HS' library module in
      -o FILE      --output=FILE        output result to FILE (should end in .hs)
      -p PLATFORM  --platform=PLATFORM  platform to use for cross compilation
      -t PATH      --output-dir=PATH    place generated files in PATH
      -v           --version            show version information
                   --numeric-version    show version number

    The header file must be a C header file matching the given binding file.
    The dump TYPE can be
      trace   -- trace compiler phases
      genbind -- trace binding generation
      ctrav   -- trace C declaration traversal
      chs     -- dump the binding file (adds `.dump' to the name)
    PLATFORM can be x86_64-linux, i686-linux, m68k-palmos

The most useful of these is probably `--cppopts=` (or `-C`). If the C header file needs any special options (like `-D` or `-I`) to go through the C pre-processor, here is the place to pass them. A call may look like this:

    c2hs --cppopts='-I/some/obscure/dir' --cppopts=-DEXTRA' Lib.chs

If you have more than one option that you want to pass to the pre-processor it is best to use multiple `--cppopts=` flags. That way there is no need to worry about quoting.

Often, lib`.h` will not be in the current directory, but in one of the header file directories. &c2hs; leaves locating the header file to the standard C preprocessor, which usually looks in two places for the header: first, in the standard include directory of the used system, this is usually `/usr/include` and `/usr/local/include`; and second, it will look in every directory that is mentioned in a `-IDIR` option passed to the pre-processor via `--cppopts`.

If the compiled binding module contains import hooks, &C2hs; needs to find the `.chi` (&C2hs; interface files) produced while compiling the corresponding binding modules. By default, they will be searched for in the current working directory. If they are located elsewhere, the `--include=INCLUDE` option has to be used to indicate the location, where INCLUDE is a colon-separated list of directories. Multiple such options are admissible. Paths specified later are searched first.

### Compilation of a Generated Haskell API

&C2hs; comes with a marshalling library, called `C2HS`, which needs to be explicitly imported into Haskell binding modules. The library contains functions that users might use explicitly, but also functions that &C2hs; will generate for some classes of bindings. The library takes the form of a single Haskell module, which &c2hs; places in the same directory as the generated binding whenever it is given the `--copy-library` (or `-l`) option.

## Implementation of Haskell Binding Modules

A discussion of binding modules, the principles behind the tool, and a discussion of related work can be found in a research paper located at . All features described in the paper, except `enum define` hooks are implemented in the tool, but since the publication of the paper, the tool has been extended further. The library interface essentially consists of the new Haskell FFI Marshalling Library. More details about this library are provided in the next section.

The remainder of this section describes the hooks that are available in binding modules.

### Import Hooks

    {#import [qualified] modid#}

Is translated into the same syntactic form in Haskell, which implies that it may be followed by an explicit import list. Moreover, it implies that the module modid is also generated by &C2hs; and instructs the tool to read the file modid`.chi`.

If an explicit output file name is given (`--output` option), this name determines the basename for the `.chi` file of the currently translated module.

Currently, only pointer hooks generate information that is stored in a `.chi` file and needs to be incorporated into any client module that makes use of these pointer types. It is, however, regarded as good style to use import hooks for any module generated by &C2hs;.

Restriction

&C2hs; does not use qualified names. This can be a problem, for example, if two pointer hooks are defined to have the same unqualified Haskell name in two different modules, which are then imported by a third module. To partially work around this problem, it is guaranteed that the declaration of the textually later import hook dominates.

### Context Hooks

    {#context [lib = lib] [prefix = prefix]#}

Context hooks define a set of global configuration options. Currently, there are two parameters which are both strings

- lib is a dynamic library that contains symbols needed by the present binding.

- prefix is an identifier prefix that may be omitted in the lexemes of identifiers referring to C definitions in any binding hook. The is useful as C libraries often use a prefix, such as `gtk_`, as a form of poor man's name spaces. Any occurrence of underline characters between a prefix and the main part of an identifier must also be dropped. Case is not relevant in a prefix. In case of a conflict of the abbreviation with an explicitly defined identifier, the explicit definition takes preference.

Both parameters are optional. An example of a context hook is the following:

    {#context prefix = "gtk"#}

If a binding module contains a binding hook, it must be the first hook in the module.

### Type Hooks

    {#type ident#}

A type hooks maps a C type to a Haskell type. As an example, consider

    type GInt = {#type gint#}

The type must be a defined type, primitive types, such as `int`, are not admissible.

### Sizeof Hooks

    {#sizeof ident#}

A sizeof hooks maps a C type to its size in bytes. As an example, consider

    gIntSize :: Int
    gIntSize  = {#sizeof gint#}

The type must be a defined type, primitive types, such as `int`, are not admissible. The size of primitive types can always be obtained using `Storable.sizeOf`.

### Enumeration Hooks

    {#enum cid [as hsid] {alias1 , ... , aliasn}
      [with prefix = pref] [deriving (clid1 , ... , clidn)]#}

Rewrite the C enumeration called cid into a Haskell data type declaration, which is made an instance of `Enum` such that the ordinals match those of the enumeration values in C. This takes explicit enumeration values in the C definitions into account. If hsid is given, this is the name of the Haskell data type. The identifiers clid1 to clidn are added to the deriving clause of the Haskell type.

By default, the names of the C enumeration are used for the constructors in Haskell. If alias1 is `underscoreToCase`, the original C names are capitalised and the use of underscores is rewritten to caps. If it is `upcaseFirstLetter` or `downcaseFirstLetter`, the first letter of the original C name changes case correspondingly. It is also possible to combine `underscoreToCase` with one of `upcaseFirstLetter` or `downcaseFirstLetter`. Moreover, alias1 to aliasn may be aliases of the form cid `as` hsid, which map individual C names to Haskell names. Instead of the global prefix introduced by a context hook, a local prefix pref can optionally be specified.

As an example, consider

    {#enum WindowType {underscoreToCase} deriving (Eq)#}

### `enum define` hooks

Many C libraries do not use enum types, but macro definitions to implement constants. c2hs provides `enum define` hooks generate a haskell datatype from a collection of macro definitions.

    {#enum define hsid {alias1 , ... , aliasn} [deriving (clid1 , ... , clidn)]#}

Create a haskell datatype hsid, with nullary constructors as given by the aliases alias1 through aliasn. Each alias has to be of the form macrodef as hsid, where hsid is the name of the nullary haskell constructor, and macrodef the C macro which the haskell constructor should map to. The deriving part is handled as in ordinary `enum` hooks.

Here's an example

    #define X 0
    #define Y 1

    {#enum define Axis {X as Axis0, Y as Axis1} deriving (Eq,Ord) #}

### Call Hooks

    {#call [pure] [unsafe] cid [as (hsid | ^)]#}

A call hook rewrites to a call to the C function cid and also ensures that the appropriate foreign import declaration is generated. The tags `pure` and `unsafe` specify that the external function is purely functional and cannot re-enter the Haskell runtime, respectively. If hsid is present, it is used as the identifier for the foreign declaration, which otherwise defaults to the cid. When instead of hsid, the symbol `^` is given, the cid after conversion from C's underscore notation to a capitalised identifier is used.

As an example, consider

    sin :: Float -> Float
    sin  = {#call pure sin as "_sin"#}

### Function Hooks

    {#fun  [pure] [unsafe] cid [as (hsid | ^)]
    [ctxt =>] { parm1 , ... , parmn } -> parm

Function hooks are call hooks including parameter marshalling. Thus, the components of a function hook up to and including the `as` alias are the same as for call hooks. However, an `as` alias has a different meaning; it specifies the name of the generated Haskell function. The remaining components use literals enclosed in backwards and foward single quotes (``` and `'`) to denote Haskell code fragments (or more precisely, parts of the Haskell type signature for the bound function). The first one is the phrase ctxt preceding `=>`, which denotes the type context. This is followed by zero or more type and marshalling specifications parm1 to parmn for the function arguments and one parm for the function result. Each such specification parm has the form

    [inmarsh [* | -]] hsty[&] [outmarsh [*] [-]]

where hsty is a Haskell code fragment denoting a Haskell type. The optional information to the left and right of this type determines the marshalling of the corresponding Haskell value to and from C; they are called the in and out marshaller, respectively.

Each marshalling specification parm corresponds to one or two arguments of the C function, in the order in which they are given. A marshalling specification in which the symbol `&` follows the Haskell type corresponds to two C function arguments; otherwise, it corresponds only to one argument. The parm following the left arrow `->` determines the marshalling of the result of the C function and may not contain the symbol `&`.

The `*-` output marshal specification is for monadic actions that must be executed but whose results are discarded. This is very useful for e.g. checking an error value and throwing an exception if needed.

Both inmarsh and outmarsh are identifiers of Haskell marshalling functions. By default they are assumed to be pure functions; if they have to be executed in the `IO` monad, the function name needs to be followed by a star symbol `*`. Alternatively, the identifier may be followed by a minux sign `-`, in which case the Haskell type does not appear as an argument (in marshaller) or result (out marshaller) of the generated Haskell function. In other words, the argument types of the Haskell function is determined by the set of all marshalling specifications where the in marshaller is not followed by a minus sign. Conversely, the result tuple of the Haskell function is determined by the set of all marshalling specifications where the out marshaller is not followed by a minus sign. The order of function arguments and components in the result tuple is the same as the order in which the marshalling specifications are given, with the exception that the value of the result marshaller is always the first component in the result tuple if it is included at all.

For a set of commonly occuring Haskell and C type combinations, default marshallers are provided by &C2hs; if no explicit marshaller is given. The out marshaller for function arguments is by default `void-`. The defaults for the in marshallers for function arguments are as follows:

- `Bool` and integral C type (including chars): `cFromBool`

- Integral Haskell and integral C type: `cIntConv`

- Floating Haskell and floating C type: `cFloatConv`

- `String` and `char*`: `withCString*`

- `String` and `char*` with explicit length: `withCStringLen*`

- T and T`*`: `with*`

- T and T`*` where T is an integral type: `withIntConv*`

- T and T`*` where T is a floating type: `withFloatConv*`

- `Bool` and T`*` where T is an integral type: `withFromBool*`

The defaults for the out marshaller of the result are the converse of the above; i.e., instead of the `with` functions, the corresponding `peek` functions are used. Moreover, when the Haskell type is `()`, the default marshaller is `void-`.

As an example, consider

    {#fun notebook_query_tab_label_packing as ^
      `(NotebookClass nb, WidgetClass cld)' =>
      {notebook `nb'                ,
       widget   `cld'               ,
       alloca-  `Bool'     peekBool*,
       alloca-  `Bool'     peekBool*,
       alloca-  `PackType' peekEnum*} -> `()'#}

which results in the Haskell type signature

    notebookQueryTabLabelPacking :: (NotebookClass nb, WidgetClass cld)
    			     => nb -> cld -> IO (Bool, Bool, PackType)

which binds the following C function:

    void gtk_notebook_query_tab_label_packing (GtkNotebook *notebook,
    					   GtkWidget   *child,
    					   gboolean    *expand,
    					   gboolean    *fill,
    					   GtkPackType *pack_type);

### Get Hooks

    {#get apath#}

A get hook supports accessing a member value of a C structure. The hook itself yields a function that, when given the address of a structure of the right type, performs the structure access. The member that is to be extracted is specified by the access path apath. Access paths are formed as follows (following a subset of the C expression syntax):

- The root of any access path is a simple identifier, which denotes either a type name or `struct` tag.

- An access path of the form `*`apath denotes dereferencing of the pointer yielded by accessing the access path apath.

- An access path of the form apath`.`cid specifies that the value of the `struct` member called cid should be accessed.

- Finally, an access path of the form apath`->`cid, as in C, specifies a combination of dereferencing and member selection.

For example, we may have

    visualGetType              :: Visual -> IO VisualType
    visualGetType (Visual vis)  = liftM cToEnum $ {#get Visual->type#} vis

### Set Hooks

    {#set apath#}

Set hooks are formed in the same way as get hooks, but yield a function that assigns a value to a member of a C structure. These functions expect a pointer to the structure as the first and the value to be assigned as the second argument. For example, we may have

    {#set sockaddr_in.sin_family#} addr_in (cFromEnum AF_NET)

### Pointer Hooks

    {#pointer [*] cid [as hsid] [foreign | stable] [newtype | ->
    hsid2] [nocode]#}

A pointer hook facilitates the mapping of C to Haskell pointer types. In particular, it enables the use of `ForeignPtr` and `StablePtr` types and defines type name translations for pointers to non-basic types. In general, such a hook establishes an association between the C type cid or `*`cid and the Haskell type hsid, where the latter defaults to cid if not explicitly given. The identifier cid will usually be a type name, but in the case of `*`cid may also be a struct, union, or enum tag. If both a type name and a tag of the same name are available, the type name takes precedence. Optionally, the Haskell representation of the pointer can be by a `ForeignPtr` or `StablePtr` instead of a plain `Ptr`. If the `newtype` tag is given, the Haskell type hsid is defined as a `newtype` rather than a transparent type synonym. In case of a `newtype`, the type argument to the Haskell pointer type will be hsid, which gives a cyclic definition, but the type argument is here really only used as a unique type tag. Without `newtype`, the default type argument is `()`, but another type can be specified after the symbol `->`.

For example, we may have

    {#pointer *GtkObject as Object newtype#}

This will generate a new type `Object` as follows:

    newtype Object = Object (Ptr Object)

which enables exporting `Object` as an abstract type and facilitates type checking at call sites of imported functions using the encapsulated pointer. The latter is achieved by &C2hs; as follows. The tool remembers the association of the C type `*GtkObject` with the Haskell type `Object`, and so, it generates for the C function

    void gtk_unref_object (GtkObject *obj);

the import declaration

    foreign import gtk_unref_object :: Object -> IO ()

This function can obviously only be applied to pointers of the right type, and thus, protects against the common mistake of confusing the order of pointer arguments in function calls.

However, as the Haskell FFI does not permit to directly pass `ForeignPtr`s to function calls or return them, the tool will use the type `Ptr HsName` in this case, where `HsName` is the Haskell name of the type. So, if we modify the above declaration to be

    {#pointer *GtkObject as Object foreign newtype#}

the type `Ptr Object` will be used instead of a plain `Object` in import declarations; i.e., the previous `import` declaration will become

    foreign import gtk_unref_object :: Ptr Object -> IO ()

To simplify the required marshalling code for such pointers, the tool automatically generates a function

    withObject :: Object -> (Ptr Object -> IO a) -> IO a

As an example that does not represent the pointer as an abstract type, consider the C type declaration:

    typedef struct {int x, y;} *point;

We can represent it in Haskell as

    data Point = Point {x :: Int, y :: Int}
    {#pointer point as PointPtr -> Point#}

which will translate to

    data Point = Point {x :: Int, y :: Int}
    type PointPtr = Ptr Point

and establish a type association between `point` and `PointPtr`.

If the keyword `nocode` is added to the end of a pointer hook, &C2hs; will not emit a type declaration. This is useful when a &C2hs; module wants to make use of an existing type declaration in a binding not generated by &C2hs; (i.e., where there are no `.chi` files).

Restriction

The name cid cannot be a basic C type (such as `int`), it must be a defined name.

### Class Hooks

    {#class [hsid1 =>] hsid2 hsid3#}

Class hooks facilitate the definition of a single inheritance class hierachy for external pointers including up and down cast functionality. This is meant to be used in cases where the objects referred to by the external pointers are order in such a hierachy in the external API - such structures are encountered in C libraries that provide an object-oriented interface. Each class hook rewrites to a class declaration and one or more instance declarations.

All classes in a hierarchy, except the root, will have a superclass identified by hsid1. The new class is given by hsid2 and the corresponding external pointer is identified by hsid3. Both the superclass and the pointer type must already have been defined by binding hooks that precede the class hook.

The pointers in a hierachy must either all be foreign pointers or all be normal pointers. Stable pointers are not allowed. Both pointer defined as `newtype`s and those defined by type synonyms may be used in class declarations and they may be mixed. In the case of synonyms, Haskell's usual restrictions regarding overlapping instance declarations apply.

The newly defined class has two members whose names are derived from the type name hsid3. The name of first member is derived from hsid3 by converting the first character to lower case. This function casts from any superclass to the current class. The name of the second member is derived by prefixing hsid3 with the `from`. It casts from the current class to any superclass. A class hook generates an instance for the pointer in the newly defined class as well as in all its superclasses.

As an example, consider

    {#pointer *GtkObject newtype#}
    {#class GtkObjectClass GtkObject#}

    {#pointer *GtkWidget newtype#}
    {#class GtkObjectClass => GtkWidgetClass GtkWidget#}

The second class hook generates an instance for `GtkWidget` for both the `GtkWidgetClass` as well as for the `GtkObjectClass`.

### CPP Directives and Inline C Code

A Haskell binding module may include arbitrary C pre-processor directives using the standard C syntax. The directives are used in two ways: Firstly, they are included in the C header file generated by &C2hs; in exactly the same order in which they appear in the binding module. Secondly, all conditional directives are honoured by &C2hs; in that all Haskell binding code in alternatives that are discarded by the C pre-processor are also discarded by &C2hs;. This latter feature is, for example, useful to maintain different bindings for multiple versions of the same C API in a single Haskell binding module.

In addition to C pre-processor directives, vanilla C code can be maintained in a Haskell binding module by bracketing this C code with the pseudo directives `#c` and `#endc`. Such inline C code is emitted into the C header generated by &C2hs; at exactly the same position relative to CPP directives as it occurs in the binding module. Pre-processor directives may encompass the `#include` directive, which can be used instead of specifying a C header file as an argument to `c2hs`. In particular, this enables the simultaneous use of multiple header files without the need to provide a custom header file that binds them together. If a header file lib`.h` is specified as an argument to `c2hs`, the tool will emit the directive `#include"`lib`.h"` into the generated C header before any other CPP directive or inline C code.

As an artificial example of these features consider the following code:

    #define VERSION 2

    #if (VERSION == 1)
    foo :: CInt -> CInt
    foo = {#call pure fooC#}
    #else
    foo :: CInt -> CInt -> CInt
    foo = {#call pure fooC#}
    #endif

    #c
    int fooC (int, int);
    #endc

One of two versions of the Haskell function `foo` (having different arities) is selected in dependence on the value of the CPP macro `VERSION`, which in this example is defined in the same file. In realistic code, `VERSION` would be defined in the header file supplied with the C library that is made accessible from Haskell by a binding module. The above code fragment also includes one line of inline C code that declares a C prototype for `fooC`.

Current limitation of the implementation

Inline C code can currently not contain any code blocks; i.e., only declarations as typically found in header files may be included.

### Grammar Rules

The following grammar rules define the syntax of binding hooks:

    hook     -> `{#' inner `#}'
    inner    -> `import' ['qualified'] ident
              | `context' ctxt
              | `type' ident
              | `sizeof' ident
              | `enum' idalias trans [`with' prefix] [deriving]
              | `call' [`pure'] [`unsafe'] idalias
              | `fun' [`pure'] [`unsafe'] idalias parms
              | `get' apath
              | `set' apath
              | `pointer' ['*'] idalias ptrkind
              | `class' [ident `=>'] ident ident

    ctxt     -> [`lib' `=' string] [prefix]
    idalias  -> ident [(`as' ident | `^')]
    prefix   -> `prefix' `=' string
    deriving -> `deriving' `(' ident_1 `,' ... `,' ident_n `)'
    parms    -> [verbhs `=>'] `{' parm_1 `,' ... `,' parm_n `}' `->' parm
    parm     -> [ident_1 [`*' | `-']] verbhs [`&'] [ident_2 [`*'] [`-']]
    apath    -> ident
              | `*' apath
              | apath `.' ident
              | apath `->' ident
    trans    -> `{' alias_1 `,' ... `,' alias_n `}'
    alias    -> `underscoreToCase' | `upcaseFirstLetter' | `downcaseFirstLetter'
              | ident `as' ident
    ptrkind  -> [`foreign' | `stable'] ['newtype' | '->' ident]

Identifier `ident` follow the lexis of Haskell. They may be enclosed in single quotes to disambiguate them from C->Haskell keywords.

## Bug Reports and Suggestions

There is a tracker for bugs and feature requests: . Alternatively if you prefer email please send your bug reports and suggestions to the C->Haskell List c2hs@haskell.org.

A good bug report contains information on the used operating system and Haskell compiler as well as the version of &C2hs; that you have been using. You can obtain the version information by running `c2hs --version`. If possible a concise example illustrating your problem would be appreciated.

## Copyright

&C2hs; is Copyright (C) [1999..2005] Manuel M. T. Chakravarty

### &C2hs; License

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

### Documentation License

    This manual is Copyright (c) [2000..2005] by Manuel M. T. Chakravarty.
    Permission is granted to copy, distribute and/or modify this document under
    the terms of the GNU Free Documentation License, Version 1.1 or any later
    version published by the Free Software Foundation; with no Invariant Sections,
    with no Front-Cover Texts, and with the no Back-Cover Texts.  A copy of the
    license is included in the section entitled "GNU Free Documentation License".

### Possible Licenses of Generated Code

All code included into generated bindings is under a BSD-style license that does not place any restrictions on the license of the inteface produced with &C2hs; (ie, closed proprietary licenses are possible, too). In other words, I do not care what you use &C2hs; for or to whom you are giving &C2hs; or any interfaces generated with &C2hs;, only if you modify or improve &C2hs; itself, you have to contribute your changes back to the community. Nevertheless, I will of course be particularly delighted if you choose to make your work freely available.

## GNU Free Documentation License

The GNU Free Documentation License is available at .

## Release Notes

Important changes (especially those affecting the semantics of the tool) are documented in the following.

### Version 0.15.1 "Rainy Days"

- New C parser that can parse all of C99 and GNU C

- Make c2hs integrate better with Cabal (1.2 and later)

- Adapted to GHC 6.8.

- Now requires Cabal 1.2.

- Lots and lots of old code removal

- Several bug fixes and improvements from Udo Stenzel:

  - allowing variadic functions in structures

  - allowing call and fun hooks for FunPtrs in C structs

  - embedded arrays size calculated correctly

### Version 0.14.5 "Travelling Lightly"

- Added `nocode` directive to pointer hooks

- Can use structs properly in pointer hooks now (contributed by Jelmer Vernooij)

- `upcaseFirstLetter` and `downcaseFirstLetter`

- Cross-compiling with `--platform` flag

- Gcc's `asm` construct is supported (contributed by Duncan Coutts)

- Hierarchical modules syntax in `import` hooks supported

- No separately installed marshaling library anymore; as a result binary &C2hs; packages and installations are now independent of the targeted Haskell system

- New lexer and parser generated with Alex and Happy (contributed by Duncan Coutts)

- Cabal build system

### Version 0.13.6 "Pressing Forward"

- Works with GHC 6.4 and Cabal packages

- Strings may contain 8-bit characters (e.g., umlauts).

- Identifier may optionally be put in single quotes. (This is useful if they would otherwise collide with a &C2hs; keyword.)

- Some smaller bug fixes

- C chars are treated as integral types for marshalling purposes.

- If there is no explicit output file specified, the generated header file is put in the same directory as the binding file; otherwise, it goes in the directory where the output file is put. Moreover, the `--output-dir` option enables the specification of directory where all generated files are to be put.

- Foreign import declarations include the name of the header file generated by &C2hs; (ie, it needs neither be passed to the Haskell compiler at the command line nor in an OPTIONS pragma).

- We allow structs and unions with no declarations.

- Headers including function bodies are now parsed correctly.

- Duncan Coutts identified a space leak in the parser whose removal improved performance significantly.

### Version 0.12.1 "Springtime"

- Removed support for deprecated `C2HS` interface and for old versions of the FFI libraries

- Improved line pragma generation

- Works with GHC 6.3

- Builds on Mac OS X thanks to a patch by Sean Seefried

### Version 0.11.5 "Powder Snow"

- Bug fixes

- Constant expression can now contain enumerators

- `header` label removed from `context` hooks

- This version of `c2hs` may overwrite C header files in the current directory. More precisely, if a binding module with the name `Foo.chs` is processed, a header file with the name `Foo.h` is generated and will overwrite any file of the same name in the current directory or the directory specified via the `-o` option.

- Added support for CPP directives, including special treatment of conditions, and for inline C code; specification of a header file as an argument to `c2hs` is now option.

- GHC line pragmas are emitted into generated Haskell code

- Swap the order of reading the binding module and the C header (i.e., we now read the binding module first)

### Version 0.10.17 "Altocumulus Stratiformis Perlucidus Undulatus"

- Worked around a bug in GHC 5.04.1

- Solaris-related fix

- Marshalling support for bit masks represented as enumeration types

- Added `fun` hooks

- `as` aliases can use `^` convert the orignal identifier with underscore2case

- In call hooks, the attributes `fun' was replaced by `pure' (`fun' is will still be recognised for a while to ensure backwards compatibility, but it's use is deprecated)

- GHC's package system is now supported

- If two import hooks add a type mapping for a pointer hook with the same name, the textual later one dominates.

- Bug fixes

- Support for bitfields (they are correctly handled when computing struct offsets and they can be accessed using `set` and `get` hooks)

- Some more support for GNU C extensions ("alignof" and better support "__attribute__")

- Added `class` hooks

### Version 0.9.9 "Blue Ginger"

- Bug fixes

- Library names in `foreign import`s have been removed until the convention of the new FFI is implemented (they are currently silently omitted)

- Added `sizeof` hooks; sizeof of type names is now also supported in constant expressions

- Local prefix for `enum` hooks; courtesy of Armin Sander

- Added `import` hooks

- The documentation includes a description of binding hooks

- Added `pointer` hooks, which were derived from code for a similar feature by Axel Simon; this includes proper treatment of parametrised pointers

- Integrated `deriving` option for `enum` hooks, which was contributed by Axel Simon

- Adapted to GHC 5.0

### Version 0.8.2 "Gentle Moon"

- Adaptation layer for legacy `StablePtr` interface

- Forgot to export `FunPtr` and associated functions from `C2HS`

- Forgot to export some names in `C2HSDeprecated`

- Added support for gcc's `__builtin_va_list`

### Version 0.8.1 "Gentle Moon"

- Library adapted to New FFI; the old interface can still be used by importing `C2HSDeprecated`

- FFI Library specification added to the documentation

### Version 0.7.10 "Afterthought"

- CygWin support; based on suggestions by Anibal Maffioletti Rodrigues de DEUS anibaldedeus@email.com

- `IntConv` instances for `Int8`, `Word8`, and `Char`

### Version 0.7.9 "Afterthought"

- Debugged the stripping of prefixes from enumerators; prefixes are now generally stripped, independent of whether they can be stripped from all enumerators of a given enumeration type

- Comma now correctly required after `underscoreToCase`.

  This breaks source compatibility with previous versions.

### Version 0.7.8

- Provisional support for GHC 4.08

- Corrected constant folding

### Version 0.7.7

Ignores any occurrence of `#pragma`.

### Version 0.7.6

Bug fixes and support for `long long`.

### Version 0.7.5

This is mainly a bug fix release. In particular, the space behaviour of &C2hs; has been significantly improved.

IMPORTANT NOTE: From this release on, library names in `lib` tags in `context` hooks should not contain a suffix (i.e., omit `.so` etc).