[英]Printing OCaml AST as OCaml Code
I have this piece of code that contains a camlp4 quotation. 我有一段包含camlp4引用的代码。
let f_name = "my_func"
<:str_item< value $lid:f_name$ a = a * 2 >>
After running this through camlp4of
, it produces this: 通过
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")))))))
My question is this, is there anyway to print the generated ocaml code? 我的问题是,是否仍要打印生成的ocaml代码? What
camlp4of
command or option should I use to show the code? 我应该使用哪个
camlp4of
命令或选项来显示代码? What I expect to see from the above example is: 我希望从上面的示例中看到的是:
value my_func a = a * 2
Is that possible? 那可能吗? The reason is because I want to do some debugging to see how the generated ocaml code looks like.
原因是因为我想进行一些调试以查看生成的ocaml代码的外观。
That's a good question I asked myself a few days ago. 我几天前问自己这是一个好问题。
You can use `Camlp4.PreCast.Printers.OCaml.print_implem which has the type 您可以使用`Camlp4.PreCast.Printers.OCaml.print_implem,其类型为
value print_implem : ?input_file:string -> ?output_file:string ->
Ast.str_item -> unit;
For example, in the toplevel (with only the output of the last command shown): 例如,在顶层(仅显示最后一条命令的输出):
# #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 = ()
Another solution is to craft a syntax extension that will produce the output you're looking for. 另一个解决方案是设计语法扩展名,该扩展名将产生您想要的输出。 For example, a Camlp4AstFilter that would just ignore its input, and return your stuff as output, so you can use
camlp4of my_filter.cmo -str ''
to get the AST you're looking for. 例如,一个Camlp4AstFilter只会忽略它的输入,然后将您的东西作为输出返回,因此您可以使用
camlp4of my_filter.cmo -str ''
获得所需的AST。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.