Jas*_*Yeo 5 ocaml abstract-syntax-tree camlp4
我有这段包含camlp4报价的代码.
let f_name = "my_func"
<:str_item< value $lid:f_name$ a = a * 2 >>
Run Code Online (Sandbox Code Playgroud)
经过这个camlp4of,它产生了这个:
Ast.StExp (_loc,
(Ast.ExApp (_loc,
(Ast.ExApp (_loc, (Ast.ExId (_loc, (Ast.IdLid (_loc, "=")))),
(Ast.ExApp (_loc,
(Ast.ExApp (_loc,
(Ast.ExId (_loc, (Ast.IdLid (_loc, "value")))),
(Ast.ExId (_loc, (Ast.IdLid (_loc, f_name)))))),
(Ast.ExId (_loc, (Ast.IdLid (_loc, "a")))))))),
(Ast.ExApp (_loc,
(Ast.ExApp (_loc, (Ast.ExId (_loc, (Ast.IdLid (_loc, "*")))),
(Ast.ExId (_loc, (Ast.IdLid (_loc, "a")))))),
(Ast.ExInt (_loc, "2")))))))
Run Code Online (Sandbox Code Playgroud)
我的问题是,无论如何打印生成的ocaml代码?我camlp4of应该使用什么命令或选项来显示代码?我希望从上面的例子中看到的是:
value my_func a = a * 2
Run Code Online (Sandbox Code Playgroud)
那可能吗?原因是因为我想做一些调试,看看生成的ocaml代码是怎样的.
这是几天前我问自己的一个很好的问题.
您可以使用具有该类型的`Camlp4.PreCast.Printers.OCaml.print_implem
value print_implem : ?input_file:string -> ?output_file:string ->
Ast.str_item -> unit;
Run Code Online (Sandbox Code Playgroud)
例如,在toplevel中(仅显示最后一个命令的输出):
# #use "topfind";;
# #require "camlp4";;
# #load "camlp4of.cma";;
# open Camlp4.PreCast;;
# let _loc = Loc.ghost;;
# let test =
let f_name = "my_func" in
<:str_item< value $lid:f_name$ a = a * 2 >>;;
# Printers.OCaml.print_implem test;;
let _ = (value my_func a) = (a * 2);;
- : unit = ()
Run Code Online (Sandbox Code Playgroud)
另一个解决方案是创建一个语法扩展,它将产生您正在寻找的输出.例如,一个Camlp4AstFilter只会忽略它的输入,并返回你的东西作为输出,所以你可以camlp4of my_filter.cmo -str ''用来获得你正在寻找的AST.