[MLton] bool and MLton FFI

Stephen Weeks sweeks@sweeks.com
Thu, 22 Jun 2006 15:44:28 -0700


> So, unlike int32_t and friends, there is no required size for a bool.
...
> Point being that there may not be a universal choice for the 
> representation of 'bool'.  

Like Wesley, I don't see that we need a universal choice.  It's no
different than C int, which varies from platform to platform.  All we
need is to express the size on each platform so that we get the
calling convention right.

> Furthermore, equating ML 'bool' with C 'bool' would seem to rule out
> a bit array implementation, though it does admit a word8 array
> implementation.

How we represent bool vector is a separate issue.  I think we should
have bool in the FFI, but not bool vector.  That lets us represent
bool vector however we want.

> > Along these lines, we should add C_Bool to c-types.sml and recommend
> > people use that for importing/exporting bool.
> 
> If we autogenerate the C_Bool binding in c-types.sml with gen-types.c it 
> will probably come out as
>    structure C_Bool = Word8
> That won't enforce the 0/1 invariant on elements of C_Bool, nor will it be 
> the case that C_Bool.t is equal to datatype bool.

C_Bool could be autogenerated as

   structure C_Bool = WordAsBool(Word8)

where WordAsBool is a simple hand-written functor that does what we
want.  Something like:

------------------------------------------------------------
functor WordAsBool (S: sig
                          eqtype t
                          val one: t
                          val zero: t
                       end) =
   struct
      open S

      val fromBool: bool -> t = fn b => if b then zero else one
      val toBool: t -> bool = fn w => w <> zero
   end
------------------------------------------------------------

This is heading down the road of making SML bool different than C
bool, and requiring manual conversions on the SML side.  That's not so
bad, and having the types be different means that the user can't
forget the comparison with zero.  But it could be simpler to drop
C_Bool, use SML bool in the FFI, and do the conversion automatically.
Although we still need some way to tell the codegen about the size of
bool so it can use the right calling convention.