Idiomatic ocaml/dune setup, does lib/ contain directories?

In idiomatic oaml/dune setup, does lib/ contain directories ?

Argument for yes: In almost all other languages, lib/ contains sub directories.

Argument for no: it appears lib/dune by default, for modules, is just lib/*.ml; Also, if there is an additional lib/foo/ or lib/bar/ it appears either (1) they each have their own dune file or (2) things get messy at the top level lib/dune file

Question: in idiomatic dune/ocaml, does lib/ contain sub directories ?

OCaml and Dune are separate projects - Dune is (intentionally) opinionated, so things which form an idiomatic Dune do not necessarily form an idiomatic OCaml setup.

Dune recommends one library per directory, yes. In Dune, if you adhere to this rule, then there is less information needed in your dune files - in particular, you don’t have to list the source files which make up each library. You can put them in the same directory, but then you have to list them explicitly.

However, for both Dune and OCaml in general, it is strongly recommended to have one library per directory for a different reason. There are two steps to using a library in OCaml:

  1. Reading its .cmi files to get the typing information for its modules
  2. Linking with its .cma/.cmxa file to get the code for those modules

Linking is achieved by explicitly adding the file to the linking command line (see the OCaml manual or run Dune with --display=verbose to see the commands). However, the first is done by adding the directory to the compiler’s search search path, which allows OCaml to read all the .cmi files found in that directory. Suppose you have libraries Foo and Bar in the same directory, when you add Foo’s directory to the search path, you’ll be also be able to use the interfaces of Bar (because they’re in that directory) but you’ll get an error only when linking the program. If you keep both Foo and Bar in separate directories, then you can’t accidentally use Bar’s interface (the error were occur when compiling the modules - i.e. much earlier), which is why one library per directory is generally recommended.

5 Likes

Indeed that’s the recommendation - a directory should have at most one library. But note that the converse does not hold and dune allows for a library to have more than one directory. Therefore if you want to organize your library with sub directories you’re fee to do so:

$ ls lib/
dune
foo/
bar/
$ cat dune
(include_subdirs unqualified) ;; this is the magic incantation to enable sub directories
(library
 (name mylib))
2 Likes