Browse thread
Camlp4 3.10: printing OCaml expression within extension: how?
-
Dmitri Boulytchev
- Julien Moutinho
[
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: | Julien Moutinho <julien.moutinho@g...> |
| Subject: | Re: [Caml-list] Camlp4 3.10: printing OCaml expression within extension: how? |
On Wed, Oct 17, 2007 at 01:18:51AM +0000, Dmitri Boulytchev wrote:
> is it possible to convert OCaml expression into string within syntax
> extension? In past version
> it could be done by string_of function.
Maybe you can do like this:
% cat pa_soe.ml4
module Id =
struct
let name = "Pa_soe"
let version = "$Id: Pa_soe mer 17 oct 2007 00:19:12 CEST $"
end
module Make (Syntax : Camlp4.Sig.Camlp4Syntax) =
struct
include Syntax
let print_interf ?input_file ?output_file ast = ()
let print_implem ?input_file ?output_file ast = ()
module PP = Camlp4.Printers.OCaml.Make(Syntax)
let pp = new PP.printer ~comments: false ()
let string_of_expr expr =
let buf = Buffer.create 42 in
let () = Format.bprintf buf "%a@?" pp#expr expr in
let str = Buffer.contents buf
in if str = "" then assert false else str
EXTEND Gram
GLOBAL: expr;
expr: LEVEL "."
(* A macro building a 2-tuple string * expr.
* Example: `(name) gives ("name", name) *)
[ [ "`"; "("; e = SELF; ")" -> <:expr< $str:string_of_expr e$,$exp:e$ >> ] ];
END
end
module M = Camlp4.Register.OCamlSyntaxExtension(Id)(Make)
% camlp4of -o pa_soe.ml -loc _loc -printer o -impl pa_soe.ml4
% ocamlc -c -I +camlp4 pa_soe.ml
% cat test.ml4
prerr_endline (fst `((=) (6 * 9) 42))
% camlp4of -o test.ml -loc _loc pa_soe.cmo -printer o -impl test.ml4
% ocamlc -c test.ml
% ocamlc -o test.tpo test.cmo
% ./test.tpo
(6 * 9) = 42
Bonus, how I have found this:
% cd /usr/local/src/ocaml/_cvs/ocaml/camlp4
% grep -R string_of * > /tmp/out
% vim /tmp/out
There is a line:
boot/camlp4boot.ml: let string_of_patt patt =
% vim boot/camlp4boot.ml
There is a line:
let () = Format.bprintf buf "%a@?" pp#patt patt in
Match against "method patt"
2nd match: just above (with vim's line folding) there is a "method expr"
% grep -R "method expr" * > /tmp/out2
% vim /tmp/out2
Encouraging lines:
Camlp4/Printers/OCaml.ml: method expr_list f =
Camlp4/Printers/OCaml.ml: method expr_list_cons simple f e =
Camlp4/Printers/OCaml.ml: method expr f e =
% vim Camlp4/Printers/OCaml.ml
Seems like the holy grail.
pa_soe.ml4 is derivated from the module Make holding string_of_patt (boot/camlp4boot.ml)