>Procedure specifications

6. Procedure specifications

The most common Green Card directive is a procedure specification. It describes the interface to a C procedure. A procedure specification has four parts:

Type signature %fun Section 7.

The %fun statement starts a new procedure specification, giving the name and Haskell type of the function.

Parameter marshalling: %call Section 7.1.

The %call statement tells Green Card how to translate the Haskell parameters into their C representations.

The body: %code, %end -- Section 7.2.

The %code statement gives the body and it can contain arbitrary C code. Sometimes the body consists of a simple procedure call, but it may also include variable declarations, multiple calls, loops, and so on.

The %end statement is used to specify C code that should be performed after having performed the code in %code.

Result marshalling: %result, %fail -- Section 7.3

The result-marshalling statements tell Green Card how to translate the result(s) of the call back into Haskell values.

Any of these parts may be omitted except the type signature. If any part is missing, Green Card will fill in a suitable statement based on the type signature given in the %fun statement. For example, consider the sin procedure specification again:

%fun sin :: Float -> Float

Green Card fills in the missing statements like this: [1]

%fun sin :: Float -> Float
%call (float arg1)
%code res1 = sin(arg1);
%result (float res1)

The rules that guide this automatic fill-in are described in Section 8.

A procedure specification can define a procedure with no input parameter, or even a constant (a ``procedure'' with no input parameters and no side effects). In the following example, printBang is an example of the former, while grey is an example of the latter: [2]

%fun printBang :: IO ()
%code printf( "!" );

%fun grey :: Colour
%code r = GREY;
%result (colour r)

All the C variables bound in the %call statement or mentioned in the %result statement, are declared by Green Card and in scope throughout the body. In the examples above, Green Card would have declared arg1, res1 and r.



The details of the filled-in statements will make more sense after reading the rest of Section 6


When there are no parameters, the %call line can be omitted. The second example can also be shortened by writing a C expression in the %result statement; see Section 7.3.