Native OCaml compiler

Hi.
I attach here a code which allows one to translate ocaml code in order to use native compilation.
The code itself and the generated code are uggly but it works Fill free to modify it and to reuse it.


(* translor <src.ml> produce a file <src_cg.ml> which prints the original code into a file before native compile it and then run the obtained code*)

let read_file_and_write fmt cin =
  try
    while true do
      let s = input_line cin in
      Format.fprintf fmt "%s@." (String.escaped s)
    done
  with _ -> ()


let main () =
  let file = Sys.argv.(1) in
  let cin = open_in file in
  let cout = open_out ((Filename.chop_extension (Filename.basename file))^"_cg.ml") in
  let fmt = Format.formatter_of_out_channel cout in 
  Format.fprintf fmt "let s = \"";
  f fmt cin;
  Format.fprintf fmt "\"@.";
  Format.fprintf fmt "let cout = open_out \"test.ml\"
                 let _ = output_string cout s
                 let _ = close_out cout
                 let _ = Sys.command \"ocamlopt -unsafe test.ml\" 
                 let _ = Sys.command \"./a.out\"
                 ";              
  close_in cin;
  close_out cout;
  ()
  
           
let _ = main ()

2 Likes