well-typed / hs-bindgen

Automatically generate Haskell bindings from C header files
20 stars 0 forks source link

Construct high-level datatypes for C `enum`s #40

Open edsko opened 3 months ago

edsko commented 3 months ago

This is the high-level counterpart to #15. This is probably relatively simple, turning the C enum into a Haskell ADT. We do need to think about error handling here though: C enums are just ints; what if a function returns something about of the declared range of the enum? This is uncommon; Wikipedia says

Some compilers warn if an object with enumerated type is assigned a value that is not one of its constants. However, such an object can be assigned any values in the range of their compatible type, and enum constants can be used anywhere an integer is expected. For this reason, enum values are often used in place of preprocessor #define directives to create named constants. Such constants are generally safer to use than macros, since they reside within a specific identifier namespace.

(Emphasis not in original.) Thus, turning an enum into an ADT with a strictly limited range must be opt-in.

Moreover, not all enums correspond to ADTs at all; tracking "bitmap enums" separately at https://github.com/well-typed/hs-bindgen/issues/65.

edsko commented 3 months ago

As an example, given

typedef enum
{
    AS_X,
    AS_Y,
    AS_Z
} acme_sum;

we might want to generate

data AcmeSum = ASX | ASY | ASZ
phadej commented 2 months ago

Also enums can contain duplicate values:

enum foo { fail = 1, bad = 1, good = 0 };