Compiling .ml containing toplevel directives

Hi,

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.

Thanks!

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.

[@@@top.directory "my/dir"]

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

Hi,

The background is that we have a few big .ml files that contain top directives. They are supposed to be used with #use "x.ml";; 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 x.ml 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>"
at

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 x.ml -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