mirage / ocaml-cstruct

Map OCaml arrays onto C-like structs
ISC License
106 stars 50 forks source link

Nested structures support #207

Open XVilka opened 6 years ago

XVilka commented 6 years ago

To be able to do

[%%cstruct type struct_type1 = {
         a: uint8_t;
         b: uint32_t;
         c: uint8_t [@len 16];
} [@@little_endian]
]

[%%cstruct type struct_type2 = {
         d: uint64_t;
         q: uint32_t;
         r: struct_type1;
         s: uint32_t;
} [@@little_endian]
]
XVilka commented 6 years ago

This one is harder... Do you have any ideas how it should look then?

samoht commented 6 years ago

What would be the difference between [%%cstruct struct_type1 = ... and [%%cstruct type t1 = { ... ]?

XVilka commented 6 years ago

Ah, there is no difference, it is just a skipped type word. Should be [%%cstruct type struct_type = {...

samoht commented 6 years ago

So I am not sure to understand that feature. I though it was already working. What it the error that you get if you try that?

More generally, "deriving"-like extension only work at the syntax level: e.g. I would expect a generator to call truct_type1_of_xxx of truct_type1_to_xxx and that symbol should be in scope.

XVilka commented 6 years ago

@samoht no, it doesn't. In this case it will give

Error: ppx_cstruct error: Unknown type struct type1
samoht commented 6 years ago

Ha yes indeed this is not supported.

The usual mechanism to make that work is to extend the supported type with "external" type, relying on some symbols to be defined in the environment. For instance, I would extend the ty type (in ppx/ppx_cstruct.ml) with an Ext of string definition -- or something similar, and see what else needs to be changed. You could assume that that the associated functions already exist in scope and so the generator just has to call them correctly.

Not sure how this will work with the BE and LE nested modules, as usually deriving-like extension just generate foo_of_t and t_of_foo function for the type foo. Maybe we can check if the external type are inside the current module or not to decide if the functions needs to be prefixed by BE or LE.