Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obj module documentation

Tags:

ocaml

Is there any documentation about the Obj module? I could only find a list of functions without any description...

(BTW: I know these are low-level functions not meant to be generally used)

like image 590
Mauricio Scheffer Avatar asked May 18 '11 21:05

Mauricio Scheffer


1 Answers

Yes, it is clearly undocumented on purpose. For five uses of Obj I see (or write myself, which is more disturbing), two of them are unjustified, two of them are a way to avoid a cleaner design change that would be useful anyway, and one of them is a genuine "good solution" to a complicated problem.

Obj only expose type-breaking operations that allow to explore and manipulate the runtime representation of OCaml data. You don't need documentation for these functions, they're obvious, but you need to know about OCaml data representation (I learned it using this document, but the ocaml manual also documents it), and if you want to hack into it you should know about the runtime to know what's safe and what isn't. As a general rule: don't.

Here are a few legitimate uses of Obj:

  • when compiling Coq programs to OCaml programs; the Coq type system being more powerful, it can type things that OCaml would reject, hence the Coq->Ocaml translator inserts Obj.magic calls to force OCaml into accepting its output.

  • when encoding GADTs in OCaml 3.x, which didn't support it -- they were added to 4.00. There is one encoding with module-level equality and functors (see this post or this work), but the more common one (used in the menhir parser generator which is a great replacement for ocamlyacc, see this paper (PDF)) uses Obj.magic

  • when marshalling data using some kind of (home-made) runtime type information. The Marshal module of OCaml is already not type-safe (for obvious reason), and if you need a different kind of marshalling in a different context (eg. to/from queries and results for a SQL server, as I did in my macaque project) you will need some kind of unsafe cast.

like image 69
gasche Avatar answered Oct 22 '22 00:10

gasche