bare-ocaml icon indicating copy to clipboard operation
bare-ocaml copied to clipboard

C codegen

Open rizo opened this issue 4 years ago • 3 comments

Hey! :)

Just came across the BARE format (thanks to your project!) and was surprised by how similar it is to a custom format I created for my company's product. I'm immediately sold and started thinking about integrating BARE.

We currently use it between C and OCaml apps, so my natural question is can we add C codegen? I haven't looked extensively but it doesn't seem like there's currently a C code generator out there.

Thoughts?

rizo avatar Sep 04 '20 15:09 rizo

Hola!

I think it's an interesting idea, if you're willing to implement it (reusing the parser and AST, of course). There are lots of questions around the best way to represent some of these constructs in C (map, optional, unions), but why not.

Bonus points if you also generate conversions OCaml<->C for the types :wink:

c-cube avatar Sep 04 '20 15:09 c-cube

Yeah maps might be tricky. I don't need them for my use-case at the moment, but I'll try to think of something.

I'm definitely happy to contribute this if we get to implement it (CC @rigon)!

Bonus points if you also generate conversions OCaml<->C for the types 😉

Yes! Man, I wish there was a DSL to write C in OCaml! 😄

rizo avatar Sep 04 '20 16:09 rizo

Great!

For maps (or even lists), I imagine it's reasonable to allow the generated code to allocate at least a bit (this is not flatbuffers/capnproto!).

So I think something like that could work (forgive me, my C is a bit… rusty):

BARE:

type Complex {
  im: f64
  re: f64
}

type Foo {
  a: int
  b: []string
  c: []Complex
  d: map[int]bool
}

generated C (types):

struct Complex {
  double re;
  double im;
};

struct ComplexArray {
  data: Complex*;
  len: size_t;
};


struct StringArray {
  data: char**;
  len: size_t;
};

struct MapIntBool {
  keys: int*;
  values: bool*; // or some bitvector…
  len: size_t;
}

struct Foo {
  long a;
  StringArray b;
  ComplexArray c;
  MapIntBool d;
};

and then use malloc to create the arrays/association lists?

c-cube avatar Sep 04 '20 16:09 c-cube