Tuesday, March 30, 2010

Tool for generating algebraic types in C

I've spent a few evenings crafting a tool to automatically generate C code implementing algebraic data types (or discriminated union types) from short specification files. For example, the following specification
@ type a_b_tree
@ constructor a
@ constructor b
@ constructor branch
l : a_b_tree *
r : a_b_tree *
@{
    if (l == NULL || r == NULL) {
        fprintf(stderr, "a_b_tree: branch cannot have NULL arguments.\n");
 exit(1);
    }
}@
@ end
expands to 144 lines of C (counting the .h and .c files).

The transformation supports
  • generation of constructor, deconstructor, and freeing functions;
  • optimised handling of constructors with no arguments (memory is not allocated for separate instances of these);
  • optimised handling of types with only a single constructor (there is no need in this case to distinguish between the type and its constructor);
  • user specifiable malloc and free functions;
  • user specifiable header and footer code for the generated .h and .c files.
You can download this tool here.

No comments: