<!doctype linuxdoc system> <!-- C->Haskell documentation --> <article> <title>The Binding Generator C->Haskell <author>Manuel M. T. Chakravarty, <tt/chak@cse.unsw.edu.au/ <date>v0.7, 18 June 2001 <abstract> C->Haskell is an interface generator that simplifies the development of <htmlurl url="http://haskell.org" name="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 C->Haskell, which is at <url url="http://www.cse.unsw.edu.au/~chak/papers/papers.html#c2hs">. </abstract> <toc> <p> <bf>Copyright & Distribution</bf> <p> Copyright (c) [1999..2001] by <htmlurl url="http://www.cse.unsw.edu.au/~chak/" name="Manuel M. T. Chakravarty">. The manual is distributed under the terms GNU Free Documentation License available from <url url="http://www.fsf.org/copyleft/fdl.html">. <p> The master copy of this document is at <url url="http://www.cse.unsw.edu.au/~chak/haskell/c2hs/">; the source is in SGML, which allows you to produce a selection of standard formats, including HTML and Postscript. <p> <bf>Contributions</bf> <p> If you have any comments, suggestions, or contributions, please send them to <htmlurl url="mailto:chak@cse.unsw.edu.au" name="chak@cse.unsw.edu.au">. <sect>Installation <p> It follows a brief discussion of the installation from source. There is, however, a file <tt/INSTALL/ in the source distribution, which is more frequently updated and should be consulted in any case. <sect1>Where is the Source? <p> The master site of C->Haskell is at <url url="http://www.cse.unsw.edu.au/~chak/haskell/c2hs/">. It has all the latest information and sources. Furthermore, it explains how to get anonymous CVS access to C->Haskell's repository and may have pre-compiled binaries for easier installation. <sect1>What Else Do I Need? <p> You need a Haskell system supported by C->Haskell. Currently this is only the <em/Glasgow Haskell Compiler (GHC)/, which you can obtain from <url url="http://haskell.org/ghc/">. You need a fairly recent version of the Haskell compiler. C->Haskell uses a compiler support library called the <em/Compiler Toolkit/. In the main distribution, the Compiler Toolkit is already contained in the source tar ball -- be sure to download a file named <tt/c2hs-/<em/x/<tt/./<em/y/<tt/./<em/z/<tt/.tar.gz/, were <em/x/<tt/./<em/y/<tt/./<em/z/ is the version number of the package. To build the documentation, you will also need the <em/SGML Tools/, which you find at your nearest sunsite or Linux mirror or at <url url="ftp://ftp.lip6.fr/pub/sgml-tools/">. On an up-to-date Linux system, the tools are probably already installed. <sect1>I Got Everything, and Now? <p> The short answer is <tscreen><verb> % gzip -cd c2hs.X.Y.Z.tar.gz | tar xvf - # unpack the sources % cd c2hs.X.Y.Z # change to the toplevel directory % ./configure # run the `configure' script % make # build everything [ Become root if necessary ] % make install # install the tool </verb></tscreen> <p> In the <tt/INSTALL/ file, there are more details. Optionally, you can build the documentation by issuing <tt/make doc/. <sect>Usage of C->Haskell <p> Let's have a brief look at how to call the tool and how to use the generated interfaces. <sect1>Usage of <tt/c2hs/ <p> C->Haskell is implemented by the executable <tt/c2hs/. It is usually called as <p> <quote> <tt/c2hs /<em/lib/<tt/.h /<em/Lib/<tt/.chs/ </quote> <p> where <em/lib/<tt/.h/ is the header file and <em/Lib/<tt/.chs/ the Haskell binding module, which define the C- and Haskell-side interface, respectively. If no errors occur, the result is a pure Haskell module <em/Lib/<tt/.hs/, which implements the Haskell API of the library. The executable <tt/c2hs/ has a couple more options: <p> <tscreen><verb> 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 -o FILE --output=FILE output result to FILE (should end in .hs) -v --version show version information --old-ffi[=OLDFFI] use the FFI without `Ptr a' 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) </verb></tscreen> <p> The most useful of these is probably <tt/--cppopts=/ (or <tt/-C/). If the C header file needs any special options (like <tt/-D/ or <tt/-I/) to go through the C pre-processor, here is the place to pass them. A call may look like this: <p> <quote> <tt>c2hs --cppopts='-I/some/obscure/dir -DEXTRA' </tt><em/lib/<tt/.h /<em/Lib/<tt/.chs/ </quote> <p> Do not forget the quotes if you have more than one option that you want to pass to the pre-processor. <p> Often, <em/lib/<tt/.h/ will not be in the current directory, but in one of the header file directories. Apart from the current directory, C->Haskell looks in two places for the header: first, in the standard include directory of the used system, this is usually <tt>/usr/include</tt> and <tt>/usr/local/include</tt>; and second, it will look in every directory that is mentioned in a <tt/-IDIR/ option passed to the pre-processor via <tt/--cppopts/. <p> If the compiled binding module contains import hooks, C->Haskell needs to find the <tt/.chi/ (C->Haskell 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 <tt/--include=INCLUDE/ option has to be used to indicate the location, where <tt/INCLUDE/ is a colon-separated list of directories. Multiple such options are admissible. Later paths are searched first. <sect1>Compilation of a Generated Haskell API <p> C->Haskell comes with a marshalling library, called <tt/C2HS/, which is imported by virtually all library bindings. Consequently, you will have to tell the Haskell compiler where to find the interface files when you compile a generated interface and you have to tell the linker where to find the library archive of <tt/C2HS/. To simplify this usually operating and compilation system-dependent process, C->Haskell comes with a simple configuration manager, in the form of the executable <tt/c2hs-conf/. It can be used to inquire information for compilation and linking and pass that information on to the Haskell compiler. The call <p> <tscreen> c2hs-config --cflags </tscreen> <p> returns all flags that need to be given to the Haskell compiler for compilation and <p> <tscreen> c2hs-config --lib </tscreen> <p> returns all flags necessary for linking. Overall, you may want to use a call like the following to compile a generated library module: <p> <quote> <tt/ghc `c2hs-config --cflags` -c /<em/Lib/<tt/.hs/ </quote> <p> The backquotes cause the shell to call <tt/c2hs-config/ and substitute the call by the flags returned. This, of course, also works in a makefile. Furthermore, <tt/c2hs-config/ can also be used to locate the executable of the tool itself, by calling <p> <tscreen> c2hs-config --c2hs </tscreen> <p> This slightly simplifies configuration management of libraries generated by C->Haskell, as it is sufficient to know the location of <tt/c2hs-config/ to access all other components of C->Haskell. <sect>Implementation of Haskell Binding Modules <p> 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 <url url="http://www.cse.unsw.edu.au/~chak/papers/papers.html#c2hs">. All features described in the paper, except <tt/enum define/ hooks are implemented in the tool, but since the publication of the paper, the tool has been extended further. Furthermore, the distribution contains examples that illustrate the use of C->Haskell. In the source distribution, these examples are located below the directories <tt/tests/ and <tt/examples/. The latter contains a binding for the <url url="http://www.gnome.org" name="Gnome"> HTTP 1.1 library <tt/ghttp/. The sources of the marshalling library <tt/C2HS/ are in the directory <tt/lib/ and contain a fair amount of comments, which should help getting you started. Since version 0.8.1 the interface of the marshalling library <tt/C2HS/ changed. The new interface essentially consists of the new Haskell FFI Marshalling Library. More details about this library are provided in the next section. For backward compatibilitym the old interface (i.e., the pre-0.8.1 interface) can still be used by importing <tt/C2HSDeprecated/ instead of <tt/C2HS/. The remainder of this section describes the hooks that are available in binding modules. <sect1>Import Hooks <p> <tscreen> {#import [qualified] <it/modid/#} </tscreen> <p> 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 <it/modid/ is also generated by C->Haskell and instructs the tool to read the file <it/modid/<tt/.chi/. <p> If an explicit output file name is given (<tt/--output/ option), this name determines the basename for the <tt/.chi/ file of the currently translated module. <p> Currently, only pointer hooks generate information that is stored in a <tt/.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 C->Haskell. <sect1>Context Hooks <p> <tscreen> {#context [header = <it/header/] [lib = <it/lib/] [prefix = <it/prefix/]#} </tscreen> <p> Context hooks define a set of global configuration options. Currently, there are three parameters all of which are strings: <itemize> <item><em/header/ is the C header file containing the definitions, which are bound in the current binding module. <item><em/lib/ is a dynamic library that contains symbols needed by the present binding. <item><em/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 <tt/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. </itemize> <p> All three parameters are optional. An example of a context hook is the following: <tscreen> {#context header = "gtkwidget.h" prefix = "gtk"#} </tscreen> <p> If a binding module contains a binding hook, it must be the first hook in the module. <sect1>Type Hooks <p> <tscreen> {#type <it/ident/#} </tscreen> <p> A type hooks maps a C type to a Haskell type. As an example, consider <p> <tscreen> type GInt = {#type gint#} </tscreen> <p> The type must be a defined type, primitive types, such as <tt/int/, are not admissible. <sect1>Sizeof Hooks <p> <tscreen> {#sizeof <it/ident/#} </tscreen> <p> A sizeof hooks maps a C type to its size in bytes. As an example, consider <p> <tscreen> gIntSize :: Int<br> gIntSize = {#sizeof gint#} </tscreen> <p> The type must be a defined type, primitive types, such as <tt/int/, are not admissible. The size of primitive types can always be obtained using <tt/Storable.sizeOf/. <sect1>Enumeration Hooks <p> <tscreen> {#enum <it/cid/ [as <it/hsid/] {<it/alias1/ , ... , <it/aliasn/} [with prefix = <it/pref/] [deriving (<it/clid1/ , ... , <it/clidn/)]#} </tscreen> <p> Rewrite the C enumeration called <it/cid/ into a Haskell data type declaration, which is made an instance of <tt/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 <it/hsid/ is given, this is the name of the Haskell data type. The identifiers <it/clid1/ to <it/clidn/ are added to the deriving clause of the Haskell type. <p> By default, the names of the C enumeration are used for the constructors in Haskell. If <it/alias1/ is <tt/underscoreToCase/, the original C names are capitalised and the use of underscores is rewritten to caps. Moreover, <it/alias1/ to <it/aliasn/ may be aliases of the form <it/cid/ <tt/as/ <it/hsid/, which map individual C names to Haskell names. Instead of the global prefix introduced by a context hook, a local prefix <it/pref/ can optionally be specified. <p> As an example, consider <p> <tscreen> {#enum WindowType {underscoreToCase} deriving (Eq)#} </tscreen> <p> <bf/Note:/ The <tt/enum define/ hooks described in the C->Haskell are not implemented yet. <sect1>Call Hooks <p> <tscreen> {#call [fun] [unsafe] <it/cid/ [as <it/hsid/]#} </tscreen> <p> A call hook rewrites to a call to the C function <it/cid/ and also ensures that the appropriate foreign import declaration is generated. The tags <tt/fun/ and <tt/unsafe/ specify that the external function is purely functional and cannot re-enter the Haskell runtime, respectively. If <it/hsid/ is present, it is used as the identifier for the foreign declaration, which otherwise defaults to the <it/cid/. As an example, consider <p> <tscreen><verb> sin :: Float -> Float sin = {#call fun sin as "_sin"#} </verb></tscreen> <sect1>Get Hooks <p> <tscreen> {#get <it/apath/#} </tscreen> <p> 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 <it/apath/. Access paths are formed as follows (following a subset of the C expression syntax): <itemize> <item>The root of any access path is a simple identifier, which denotes either a type name or <tt/struct/ tag. <item>An access path of the form <tt/*/<it/apath/ denotes dereferencing of the pointer yielded by accessing the access path <it/apath/. <item>An access path of the form <it/apath/<tt/./<it/cid/ specifies that the value of the <tt/struct/ member called <it/cid/ should be accessed. <item>Finally, an access path of the form <it/apath/<tt/->/<it/cid/, as in C, specifies a combination of dereferencing and member selection. </itemize> <p> For example, we may have <p> <tscreen><verb> visualGetType :: Visual -> IO VisualType visualGetType (Visual vis) = liftM cToEnum $ {#get Visual->type#} vis </verb></tscreen> <sect1>Set Hooks <p> <tscreen> {#get <it/apath/#} </tscreen> <p> 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 <p> <tscreen> {#set sockaddr_in.sin_family#} addr_in (cFromEnum AF_NET) </tscreen> <sect1>Pointer Hooks <p> <tscreen> {#pointer [*] <it/cid/ [as <it/hsid/] [foreign | stable] [newtype | -> <it/hsid2/]#} </tscreen> <p> A pointer hook facilitates the mapping of C to Haskell pointer types. In particular, it enables the use of <tt/ForeignPtr/ and <tt/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 <it/cid/ or <tt/*/<it/cid/ and the Haskell type <it/hsid/, where the latter defaults to <it/cid/ if not explicitly given. The identifier <it/cid/ will usually be a type name, but in the case of <tt/*/<it/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 <tt/ForeignPtr/ or <tt/StablePtr/ instead of a plain <tt/Ptr/. If the <tt/newtype/ tag is given, the Haskell type <it/hsid/ is defined as a <tt/newtype/ rather than a transparent type synonym. In case of a <tt/newtype/, the type argument to the Haskell pointer type will be <it/hsid/, which gives a cyclic definition, but the type argument is here really only used as a unique type tag. Without <tt/newtype/, the default type argument is <tt/()/, but another type can be specified after the symbol <tt/->/. <p> For example, we may have <p> <tscreen><verb> {#pointer *GtkObject as Object foreign newtype#} </verb></tscreen> <p> This will generate a new type <tt/Object/ as follows: <p> <tscreen><verb> newtype Object = Object (ForeignPtr Object) </verb></tscreen> <p> which allows to export <tt/Object/ as an abstract type and facilitates type checking at call sites of imported functions using the encapsulated foreign pointer. The latter is achieved by C->Haskell as follows. The tool remembers the association of the C type <tt/*GtkObject/ with the Haskell type <tt/Object/, and so, it generates for the C function <p> <tscreen><verb> void gtk_unref_object (GtkObject *obj); </verb></tscreen> <p> the import declaration <p> <tscreen><verb> foreign import gtk_unref_object :: Object -> IO () </verb></tscreen> <p> 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. <p> However, as the Haskell FFI does not allow to return <tt/ForeignPtr/s from function calls, the tool will use the type <tt/Ptr HsName/ in this case, where <tt/HsName/ is the Haskell name of the type. In the above example, that would be <tt/Ptr Object/. <p> As an example that does not represent the pointer as an abstract type, consider the C type declaration: <p> <tscreen><verb> typedef struct {int x, y;} *point; </verb></tscreen> <p> We can represent it in Haskell as <p> <p> <tscreen><verb> data Point = Point {x :: Int, y :: Int} {#pointer point as PointPtr -> Point#} </verb></tscreen> <p> which will translate to <p> <tscreen><verb> data Point = Point {x :: Int, y :: Int} type PointPtr = Ptr Point </verb></tscreen> <p> and establish a type association between <tt/point/ and <tt/PointPtr/. <p> <em/Restriction:/ The name <it/cid/ cannot be a basic C type (such as <tt/int/), it must be a defined name. <sect1>Grammar Rules <p> The following grammar rules define the syntax of binding hooks: <tscreen> <verb> hook -> `{#' inner `#}' inner -> `import' ['qualified'] ident | `context' ctxt | `type' ident | `sizeof' ident | `enum' idalias trans [`with' prefix] [deriving] | `call' [`fun'] [`unsafe'] idalias | `get' apath | `set' apath | `pointer' ['*'] idalias ptrkind ctxt -> [`header' `=' string] [`lib' `=' string] [prefix] idalias -> ident [`as' ident] prefix -> `prefix' `=' string deriving -> `deriving' `(' ident_1 `,' ... `,' ident_n `)' apath -> ident | `*' apath | apath `.' ident | apath `->' ident trans -> `{' alias_1 `,' ... `,' alias_n `}' alias -> `underscoreToCase' | ident `as' ident ptrkind -> [`foreign' | `stable'] ['newtype' | '->' ident] </verb> </tscreen> <sect>The Haskell FFI Marshalling Library <p> The Haskell FFI Marshalling Library is a proposed standard library for foreign function interoperability. The interface of the <tt/C2HS/ marshalling library as of version 0.8.1 of the tool is a slight extension of the Haskell FFI Marshalling Library, which is documented in the following. <p> The library is partitioned into a language independent and a C specific component. All features of the former are available from the module <tt/Foreign/ and all features of the later from <tt/CForeign/. Nevertheless, the following module hierarchy is part of the interface definition: <itemize> <item><htmlurl url="lib/Foreign.hs" name="Foreign"> <itemize> <item><htmlurl url="lib/Int.hs" name="Int"> <item><htmlurl url="lib/Word.hs" name="Word"> <item><htmlurl url="lib/Ptr.hs" name="Ptr"> <item><htmlurl url="lib/ForeignPtr.hs" name="ForeignPtr"> <item><htmlurl url="lib/StablePtr.hs" name="StablePtr"> <item><htmlurl url="lib/Storable.hs" name="Storable"> <item><htmlurl url="lib/MarshalAlloc.hs" name="MarshalAlloc"> <item><htmlurl url="lib/MarshalArray.hs" name="MarshalArray"> <item><htmlurl url="lib/MarshalError.hs" name="MarshalError"> <item><htmlurl url="lib/MarshalUtils.hs" name="MarshalUtils"> </itemize> <item><htmlurl url="lib/CForeign.hs" name="CForeign"> <itemize> <item><htmlurl url="lib/CTypes.hs" name="CTypes"> <item><htmlurl url="lib/CTypesISO.hs" name="CTypesISO"> <item><htmlurl url="lib/CError.hs" name="CError"> <item><htmlurl url="lib/CString.hs" name="CString"> </itemize> </itemize> It is recommended to access this functionality in C->Haskell binding modules by merely importing <tt/C2HS/. <sect>Bug Reports and Suggestions <p> Please address any bug reports and suggestions to <htmlurl url="mailto:chak@cse.unsw.edu.au" name="chak@cse.unsw.edu.au">. A good bug report contains information on the used operating system and Haskell compiler as well as the version of C->Haskell that you have been using. You can obtain the version information by running <tt/c2hs-config --version/. If possible a concise example illustrating your problem would be appreciated. <sect>Copyright <p> C->Haskell is Copyright (C) [1999..2001] Manuel M. T. Chakravarty 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. This manual is Copyright (c) [2000..2001] 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". <sect>GNU Free Documentation License <p> The GNU Free Documentation License is available at <url url="http://www.fsf.org/copyleft/fdl.html">. <sect>Release Notes <p> Important changes (especially those affecting the semantics of the tool) are documented in the following. <sect1>Version 0.9.9 "Blue Ginger" <p> <itemize> <item>Bug fixes <item>Library names in <tt/foreign import/s have been removed until the convention of the new FFI is implemented (they are currently <em/silently/ omitted) <item>Added <tt/sizeof/ hooks; sizeof of type names is now also supported in constant expressions <item>Local prefix for <tt/enum/ hooks; courtesy of Armin Sander <item>Added <tt/import/ hooks <item>The documentation includes a description of binding hooks <item>Added <tt/pointer/ hooks, which were derived from code for a similar feature by Axel Simon; this includes proper treatment of parametrised pointers <item>Integrated <tt/deriving/ option for <tt/enum/ hooks, which was contributed by Axel Simon <item>Adapted to GHC 5.0 </itemize> <sect1>Version 0.8.2 "Gentle Moon" <p> <itemize> <item>Adaptation layer for legacy <tt/StablePtr/ interface <item>Forgot to export <tt/FunPtr/ and associated functions from <tt/C2HS/ <item>Forgot to export some names in <tt/C2HSDeprecated/ <item>Added support for gcc's <tt/__builtin_va_list/ </itemize> <sect1>Version 0.8.1 "Gentle Moon" <p> <itemize> <item>Library adapted to New FFI; the old interface can still be used by importing <tt/C2HSDeprecated/ <item>FFI Library specification added to the documentation </itemize> <sect1>Version 0.7.10 "Afterthought" <p> <itemize> <item>CygWin support; based on suggestions by Anibal Maffioletti Rodrigues de DEUS <anibaldedeus@email.com> <item><tt/IntConv/ instances for <tt/Int8/, <tt/Word8/, and <tt/Char/ </itemize> <sect1>Version 0.7.9 "Afterthought" <p> <itemize> <item>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 <item>Comma now correctly required after <tt/underscoreToCase/. <bf>WARNING: This breaks source compatibility with previous versions.</bf> </itemize> <sect1>Version 0.7.8 <p> <itemize> <item>Provisional support for GHC 4.08 <item>Corrected constant folding </itemize> <sect1>Version 0.7.7 <p> Ignores any occurrence of <tt/#pragma/. <sect1>Version 0.7.6 <p> Bug fixes and support for <tt/long long/. <sect1>Version 0.7.5 <p> This is mainly a bug fix release. In particular, the space behaviour of C->Haskell has been significantly improved. <p> IMPORTANT NOTE: From this release on, library names in <tt/lib/ tags in <tt/context/ hooks should <em/not/ contain a suffix (i.e., omit <tt/.so/ etc). </article>