将OCaml AST打印为OCaml代码

5

我有一段包含camlp4引用的代码。

let f_name = "my_func"
<:str_item< value $lid:f_name$ a = a * 2 >>

通过运行 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")))))))

我的问题是,有没有办法打印生成的ocaml代码?我应该使用什么 camlp4of 命令或选项来显示代码?从上面的例子中,我期望看到:

value my_func a = a * 2

这可能吗?原因是我想进行一些调试,以查看生成的ocaml代码的样子。

1个回答

5

这是我几天前问自己的一个好问题。

你可以使用类型为`Camlp4.PreCast.Printers.OCaml.print_implem`的函数进行处理。

value print_implem : ?input_file:string -> ?output_file:string ->
                     Ast.str_item -> unit;

例如,在顶级目录中(仅显示最后一个命令的输出):
# #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 = ()

另一种解决方法是编写一个语法扩展,以生成所需的输出结果。例如,可以编写一个Camlp4AstFilter来忽略其输入并将你需要的内容作为输出返回,这样你就可以使用camlp4of my_filter.cmo -str ''获取所需的AST。


еҮҪж•° Camlp4.PreCast.Printers.OCaml.print_implem д»…йҖӮз”ЁдәҺ str_itemгҖӮжҳҜеҗҰжңүе…¶д»–жү“еҚ°еҷЁеҸҜд»Ҙжү“еҚ° exprпјҹ - Jason Yeo
1
在钩子下面,当然,但它们不通过“打印机”接口暴露。将您的表达式包装为let _ = <expr> str_item如何?对于类型,您也可以使用type foo = <type-expr>等。 - gasche

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接