简体   繁体   中英

ocamlbuild with Toploop/TopLevel

I'm looking to implement an eval function like in this answer here: https://stackoverflow.com/a/33293116/

However, when I go to compile my code sample:

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 rec sum_until n =
  if n = 0
  then 0
  else n + sum_until (n - 1);;

let a = print_string "Enter sum_until x where x = an int: "; read_line ();;
print_int eval a;;

with the following:

ocamlbuild UserInputEval.native -pkgs compiler-libs,compiler-libs.toplevel

I am getting the error:

File "_none_", line 1: Error: Cannot find file
/usr/lib/ocaml/compiler-libs/ocamltoplevel.cmxa Command exited with
code 2.

I have checked the compiler-libs directory and I don't have an ocamltoplevel.cmxa file but I do have an ocamltoplevel.cma file.

I'm wondering if this is a simple fix? I'm a bit new to ocaml so I'm not sure how to go about fixing this. Thanks!

The toplevel library is only available in bytecode mode:

ocamlbuild UserInputEval.byte -pkgs compiler-libs,compiler-libs.toplevel

Note also that the compiler-libs package may need to be installed separately (this is at least the case for archlinux).

Nevertheless, your code is probably not doing what are you expecting: you are only feeding the user input to the toplevel interpreter without reading anything from the toplevel state.

If you just want to read an integer, you can do it with simply:

let a = print_string "Enter sum_until x where x = an int: \n"; read_int ();;
print_int (sum_until a);;

without any need for compiler-libs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM