How can I Toploop inside a script?

Hello Folks, I hope everyone is doing good =]

I’m very new Ocaml and I’m having trouble trying to use Toploop from the compiler-libs in a script, maybe someone here could help.

Even tho I’m providing the my dune config with (libraries compiler-libs) I still get this error when trying to call Toploop functions: Error: No implementations provided for the following modules: Toploop referenced from bin/.main.

Using the same switch env I’m able to use the Toploop functions inside utop by using #require compiler-libs so the library exists in my env, dune just doesn’t seem be able to find it or something like this.

In case this helps, this is the function I’m trying to achieve, jus simply evaluating code as a string:

let eval code =
  let as_buf = Lexing.from_string code in
  let parsed = !Toploop.parse_toplevel_phrase as_buf in
  ignore (Toploop.execute_phrase true Format.std_formatter parsed)

– Update

I was able to make some changes that made possible to run the dune build step successfully, by changing the libraries on dune config to use compiler-libs.toplevel (as was recommended on the thread) and by adding (modes byte) to the dune config. But then now I got the this error while running dune exec: Fatal error: exception Env.Error(_)

Can you provide the exact dune file you are using? I believe you should use (libraries compiler-libs.toplevel), but it is hard to say without more details.

Cheers,
Nicolas

1 Like

Hello Nicolas. Sadly, And If I change to (libraries compiler-libs.toplevel) I got the same error. And of course, I’ve isolated into a new project, here’s the config:

bin/dune

(executable
 (public_name repl)
 (name main)
 (libraries repl compiler-libs))

dune-project

(lang dune 3.16)
(name repl)
(generate_opam_files true)
(source
 (github username/reponame))
(authors "Author Name")
(maintainers "Maintainer Name")
(license LICENSE)
(documentation https://url/to/documentation)
(package
 (name repl)
 (synopsis "A short synopsis")
 (description "A longer description")
 (depends ocaml dune)
 (tags
  (topics "to describe" your project)))

bin/main.ml

let () = print_endline "Hello, World!"

let eval code =
  let as_buf = Lexing.from_string code in
  let parsed = !Toploop.parse_toplevel_phrase as_buf in
  ignore (Toploop.execute_phrase true Format.std_formatter parsed)

let () = eval "10 + 10;;"

The toplevel library is indeed only available in bytecode mode. The toplevel environment must be initialized first by calling Toploop.initialize_toplevel_env.

1 Like

It worked!! Thanks a lot.