@@ -10,16 +10,17 @@ let write_ast (type a) (kind : a Ml_binary.kind) fn (ast : a) =
1010 output_value oc (ast : a );
1111 close_out oc
1212
13+ let temp_ppx_file () =
14+ Filename. temp_file " ppx" (Filename. basename ! Location. input_name)
15+
1316let apply_rewriter kind fn_in ppx =
1417 let magic = Ml_binary. magic_of_kind kind in
15- let fn_out = Filename. temp_file " camlppx " " " in
18+ let fn_out = temp_ppx_file () in
1619 let comm =
1720 Printf. sprintf " %s %s %s" ppx (Filename. quote fn_in) (Filename. quote fn_out)
1821 in
1922 let ok = Ccomp. command comm = 0 in
20- Misc. remove_file fn_in;
2123 if not ok then begin
22- Misc. remove_file fn_out;
2324 Cmd_ast_exception. cannot_run comm
2425 end ;
2526 if not (Sys. file_exists fn_out) then
@@ -30,31 +31,41 @@ let apply_rewriter kind fn_in ppx =
3031 try really_input_string ic (String. length magic) with End_of_file -> " " in
3132 close_in ic;
3233 if buffer <> magic then begin
33- Misc. remove_file fn_out;
3434 Cmd_ast_exception. wrong_magic buffer;
3535 end ;
3636 fn_out
3737
38+ (* This is a fatal error, no need to protect it *)
3839let read_ast (type a ) (kind : a Ml_binary.kind ) fn : a =
3940 let ic = open_in_bin fn in
40- try
41- let magic = Ml_binary. magic_of_kind kind in
42- let buffer = really_input_string ic (String. length magic) in
43- assert (buffer = magic); (* already checked by apply_rewriter *)
44- Location. set_input_name @@ (input_value ic : string );
45- let ast = (input_value ic : a ) in
46- close_in ic;
47- Misc. remove_file fn;
48- ast
49- with exn ->
50- close_in ic;
51- Misc. remove_file fn;
52- raise exn
41+ let magic = Ml_binary. magic_of_kind kind in
42+ let buffer = really_input_string ic (String. length magic) in
43+ assert (buffer = magic); (* already checked by apply_rewriter *)
44+ Location. set_input_name @@ (input_value ic : string );
45+ let ast = (input_value ic : a ) in
46+ close_in ic;
47+
48+ ast
49+
50+
51+ (* * [ppxs] are a stack,
52+ [-ppx1 -ppx2 -ppx3]
53+ are stored as [-ppx3; -ppx2; -ppx1]
54+ [fold_right] happens to process the first one *)
5355let rewrite kind ppxs ast =
54- let fn = Filename. temp_file " camlppx" " " in
55- write_ast kind fn ast;
56- let fn = List. fold_left (apply_rewriter kind) fn (List. rev ppxs) in
57- read_ast kind fn
56+ let fn_in = temp_ppx_file () in
57+ write_ast kind fn_in ast;
58+ let temp_files = List. fold_right (fun ppx fns ->
59+ match fns with
60+ | [] -> assert false
61+ | fn_in :: _ -> (apply_rewriter kind fn_in ppx) :: fns
62+ ) ppxs [fn_in] in
63+ match temp_files with
64+ | last_fn :: _ ->
65+ let out = read_ast kind last_fn in
66+ Ext_list. iter temp_files Misc. remove_file;
67+ out
68+ | _ -> assert false
5869
5970let apply_rewriters_str ?(restore = true ) ~tool_name ast =
6071 match ! Clflags. all_ppx with
0 commit comments