grain-lang / binaryen.ml

OCaml bindings for Binaryen.
Apache License 2.0
49 stars 5 forks source link

Can we make expression operations more typesafe #190

Open phated opened 1 year ago

phated commented 1 year ago

I'm looking at our Expression module and I notice that a lot of naming is to guide the usage of the APIs. Can we use our type system to guard some APIs like BinaryenRefFuncGetFunc to only accept a BinaryenRefFunc instead of any BinaryenExpressionRef? Would that require GADTs?

ospencer commented 1 year ago

I think it's probably more trouble than it's worth. The problem will always be with APIs like BinaryenLoopGetBody, where you don't know the kind of expression you're going to get back. GADTs don't help here because that function will still return a generic BinaryenExpression type. Of course, you could make a special BinaryenLoopGetBodyRefFunc that gave you back a well-typed BinaryenRefFunc, but it'd have to throw if the body wasn't a ref func. Or return a Result.

Leaning on that, the other solution is to add casts for those situations. Functions that do runtime assertions (or maybe give you a Result) depending on the input expression and give you a well-typed output expression. I suppose you'd gain a little bit nicer of an error message, but that's about it.