Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
[camlp4] expr_of_string, string_of_expr functions exist?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ 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 <>:
> 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

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 as super
   method expr e =
      let () = print_endline ("expr: "^ expr_of_string e) in
         super#expr e

(* Register the filter with camlp4 *)
let () = AstFilters.register_str_item_filter print_stuff#str_item

    ocamlc -c -I +camlp4
    camlp4of print.cmo

Hope this helps,


The University of Edinburgh is a charitable body, registered in
Scotland, with registration number SC005336.