@@ -10,16 +10,17 @@ let write_ast (type a) (kind : a Ml_binary.kind) fn (ast : a) =
10
10
output_value oc (ast : a );
11
11
close_out oc
12
12
13
+ let temp_ppx_file () =
14
+ Filename. temp_file " ppx" (Filename. basename ! Location. input_name)
15
+
13
16
let apply_rewriter kind fn_in ppx =
14
17
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
16
19
let comm =
17
20
Printf. sprintf " %s %s %s" ppx (Filename. quote fn_in) (Filename. quote fn_out)
18
21
in
19
22
let ok = Ccomp. command comm = 0 in
20
- Misc. remove_file fn_in;
21
23
if not ok then begin
22
- Misc. remove_file fn_out;
23
24
Cmd_ast_exception. cannot_run comm
24
25
end ;
25
26
if not (Sys. file_exists fn_out) then
@@ -30,31 +31,41 @@ let apply_rewriter kind fn_in ppx =
30
31
try really_input_string ic (String. length magic) with End_of_file -> " " in
31
32
close_in ic;
32
33
if buffer <> magic then begin
33
- Misc. remove_file fn_out;
34
34
Cmd_ast_exception. wrong_magic buffer;
35
35
end ;
36
36
fn_out
37
37
38
+ (* This is a fatal error, no need to protect it *)
38
39
let read_ast (type a ) (kind : a Ml_binary.kind ) fn : a =
39
40
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 *)
53
55
let 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
58
69
59
70
let apply_rewriters_str ?(restore = true ) ~tool_name ast =
60
71
match ! Clflags. all_ppx with
0 commit comments