Seal OCaml AST as OCaml Code

I have this piece of code that contains a camlp4 quote.

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

After doing this through camlp4ofhe produces this:

  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, is there anyway for printing the generated ocaml code? Which command or parameter camlp4ofshould be used to display the code? What I expect to see from the above example is the following:

value my_func a = a * 2

Is it possible? The reason is because I want to do some debugging to see what the generated ocaml code looks like.

+5
source share
1 answer

This is a good question I asked myself a few days ago.

You can use `Camlp4.PreCast.Printers.OCaml.print_implem, which is of type

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

, 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 = ()

, , . , Camlp4AstFilter, , , camlp4of my_filter.cmo -str '', AST, .

+5

All Articles