Browse thread
[camlp4] expr_of_string, string_of_expr functions exist?
-
Richard Jones
- Yitzhak Mandelbaum
- Christophe TROESTLER
- Jeremy Yallop
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Jeremy Yallop <jeremy.yallop@e...> |
| Subject: | Re: [Caml-list] [camlp4] expr_of_string, string_of_expr functions exist? |
Quoting Richard Jones <rich@annexia.org>:
> Maybe a simple question, but does camlp4 have functions to turn
> expr and patt AST structures to and from strings?
One way to do it is to use the Camlp4.Printers module. To illustrate
the idea,
here's a complete working program that prints out all expressions found in a
file.
open Camlp4.PreCast
open Syntax
(* Instantiate the module that allows us to print AST values.
This gives us an object with methods `expr', `patt', etc.,
each with type `Format.formatter -> t -> unit'. *)
let printer = let module P = Camlp4.Printers.OCaml.Make(Syntax)
in new P.printer ()
(* Transform a formatter function into a to_string function. *)
let format_to_string (f : Format.formatter -> 'a -> unit) (v : 'a) : string =
let buf = Buffer.create 128 in
let fmt = Format.formatter_of_buffer buf in
let () = f fmt v in
let () = Format.pp_print_flush fmt () in
Buffer.contents buf
(* Some to_string functions for particular AST types. *)
let expr_of_string : Ast.expr -> string = format_to_string printer#expr
let patt_of_string : Ast.patt -> string = format_to_string printer#patt
(* A "filter" that prints out expressions encountered in the AST
(top-down). *)
let print_stuff = object
inherit Ast.map as super
method expr e =
let () = print_endline ("expr: "^ expr_of_string e) in
super#expr e
end
(* Register the filter with camlp4 *)
let () = AstFilters.register_str_item_filter print_stuff#str_item
Compile:
ocamlc -c -I +camlp4 print.ml
Run:
camlp4of print.cmo file.ml
Hope this helps,
Jeremy.
--
The University of Edinburgh is a charitable body, registered in
Scotland, with registration number SC005336.