"Eval" OCaml 中的一个字符串

"Eval" a string in OCaml

我正在尝试 "eval" 表示 OCaml 中的 OCaml 表达式的字符串。我正在寻找与 Python 的 eval.

相同的东西

到目前为止我找不到太多。 Parsing 模块看起来很有用,但我找不到只评估字符串的方法。

OCaml 是一种编译型(非解释型)语言。所以没有简单的方法可以做到这一点。当然,没有支持它的语言特性(因为几乎所有解释语言都有)。你能做的最好的事情是 link 你的程序针对 OCaml 顶层(这是一个 OCaml 解释器)。

这里是如何做的,但我没有告诉你。 (另外Parsing模块是关于Parsing的,不是执行代码的)

#require "compiler-libs" (* Assuming you're using utop, if compiling then this is the package you need *)
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)

示例:

eval "let () = print_endline \"hello\";;"

注意代码示例中的尾随 ;;

要使用 ocamlbuild,您需要同时使用 compiler-libscompiler-libs.toplevel