Compiling .ml containing toplevel directives


Is there a systematic approach to preprocess .ml containing toplevel directives so that the preprocessed .ml output file can be compiled with ocaml compilers?
Toplevel directives like #directory would require some commandline arguments to be added to the ocaml compiler, but we are willing to take the complexity.


You didn’t say much about your use case so the following suggestion may be off.

Did you maybe consider doing the converse ?

That is augument your sources with directives as floating attributes e.g.

[ "my/dir"]

and extract the directives via compiler libs. These files will compile without surgery.


The background is that we have a few big .ml files that contain top directives. They are supposed to be used with #use "";; in OCaml REPL, but as the ml files are getting larger, running #use is now taking a significant time (around a minute). To make loading it faster, I am looking for a method to compile into .cmo/.cmi/.cma and load it.

Does using the floating attribute generate new .ml files that can be compiled with ocamlopt or ocamlc, or am I understanding wrong?

if you don’t mind jiggling the compiler to ignore #-directives

cd opam var ocaml-variants:build
vi parsing/lexer.mll
the compiler lexer has a clause for handling just # <line> "<file name>"

and directive = parse

add this 2nd case to ignore any other # directive:

  |  [^ '\010' '\013'] * { token lexbuf }

make ocamlc.opt ocamlopt.opt install

Custom attributes are ignored by the compiler. You can put there whatever you want.

You may also want to have a look at ocamlscript (or b0caml, but it’s unreleased and again one of these projects I had that was assuming we were going towards a simplification of the notion of library and needs to be reviewed now that this did not happen).

Hi all,
It turns out that the number of toplevel directives was pretty small so I could manually deal with them. :). Thanks for your all answers.

I have a new question though. The .ml file is using Topdirs and Toplevel modules, and when I compile the .ml using ocamlc I am seeing:

$ ocamlfind ocamlc -linkpkg -package compiler-libs
Error: Required module `Topdirs' is unavailable

Does anyone have idea about this error message?

Topdirs is in the compiler-libs.toplevel library.

1 Like