[MLton] bool and MLton FFI

Matthew Fluet fluet@cs.cornell.edu
Thu, 22 Jun 2006 18:08:36 -0400 (EDT)


>> Maybe you are suggesting that we have
>>
>>     typedef bool Bool_t;
>
> Yes.  I think we should define SML bool to be the same as C bool.

There may be some trickiness with that.  The C spec simply states:

      An object declared as type _Bool is large enough to store the values
      0 and 1.

and

      When any scalar value is converted to _Bool, the result is 0 if the
      value compares equal to 0; otherwise, the result is 1.

So, unlike int32_t and friends, there is no required size for a bool.  On 
my system, I get the following:

[fluet@localhost temp]$ cat z.c
#include <stdbool.h>
#include <stdio.h>

int main (int argc, char* arg[]) {
   printf ("sizeof(bool) = %zu\n", sizeof(bool));
   printf ("sizeof(bool[5]) = %zu\n", sizeof(bool[5]));
   return 1;
}
[fluet@localhost temp]$ gcc -o z z.c
[fluet@localhost temp]$ ./z
sizeof(bool) = 1
sizeof(bool[5]) = 5

Though, Wesley's comment seemed to suggest that there are systems where 
the sizeof(bool) is 4 and/or sizeof(bool[5]) is 20 (which would be 
consistent with the spec).

Point being that there may not be a universal choice for the 
representation of 'bool'.  Furthermore, equating ML 'bool' with C 'bool' 
would seem to rule out a bit array implementation, though it does admit a 
word8 array implementation.

> 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.

>>> I looked at all the uses of Bool_t in basis-ffi.h to see if the
>>> functions exported by the runtime were confusing bools and ints.  I
>>> found a few that I'm not sure about.
>>
>> Yeah, I added looking for uses of Bool_t to my todo.
>
> According to your responses then, it looks like all of the following
> are broken, because we don't convert C int-as-bool to SML bool.
>
>  PosixFileSys_ST_is{Blk,Chr,Dir,FIFO,Link,Reg,Sock}
>  Posix_ProcEnv_isatty
>  Posix_Process_if{Exited,Signaled,Stopped}
>
> For now I guess we should fix these by passing ints and manually
> comparing to zero.

Correct.