> On 1 Dec 2022, at 14:22, Christian Lindig <christian.lin...@citrix.com> wrote:
> 
> 
> 
>> On 1 Dec 2022, at 14:16, Edwin Torok <edvin.to...@citrix.com> wrote:
>> 
>> The disadvantage is that we can't pattern match on it anymore.
>> 
>> Although we could have some OCaml code that does the pattern matching on 
>> another type and maps it to these private integer types.
>> However at that point we've manually reinvented what ctypes would already 
>> do, and we have an additional mapping step (which may not matter from a 
>> performance point of view but would be nice if we could avoid it).
> 
> I agree that this is a severe disadvantage. My method is only useful if they 
> are mostly passed around but not when they have an algebra defined over them 
> where you want to combine and match them.


It might be possible to use your method to implement a pure-OCaml ABI checker 
though.

Consider:
```
external constant_A : unit -> int = "caml_constant_A"
external constant_B : unit -> int = "caml_constant_B"
external constant_C : unit -> int = "caml_constant_C"

let check_match = List.iter @@ fun (ocaml_variant, c_constant) ->
   let r = Obj.repr ocaml_variant in
   assert (Obj.is_int r);
   assert ((Obj.magic r : int) = c_constant ())

type t = A | B | C
let () =
   [A, constant_A
   ;B, constant_B
   ;C, constant_C]
   |> check_match
```

(although perhaps with the 2nd assertion replaced by something that includes 
the constant in the exception raised to aid debugging)

This'd only detect the ABI mismatch at runtime (although it would detect it 
right on startup), so it'd need to be accompanied by a small unit test
that would link just this module to make any mismatches a build time failure.

Then there would be no runtime overhead when using these variants in function 
calls, and we'd know they match 1:1.
Although there is still a possibility of mismatching on names (the bug I 
originally had in my patch, which although wouldn't cause any runtime issues,
would be good to catch at build time too).

I'll keep thinking about this to see whether there is another easy approach we 
can use that doesn't require using Cstubs and doesn't rely on manually keeping
code in different files in sync.

Best regards,
--Edwin


Reply via email to