(* Small script to test that the code generated by aorai can be parsed again
 * by frama-c.
 *)

open Kernel

include Plugin.Register
(struct 
  let name = "aorai testing module"
  let shortname = "aorai-test"
  let help = "utility script for aorai regtests"
 end)

module TestNumber =
  Zero
    (struct
      let option_name = "-aorai-test-number"
      let help = "test number when multiple tests are run over the same file"
      let arg_name = "n"
     end)

let tmpfile = ref (Filename.temp_file "aorai_test" ".i")

let tmpfile_set = ref false

let ok = ref false

let () =
  at_exit (fun () -> 
    if Debug.get () >= 1 || not !ok then
      result "Keeping temp file %s" !tmpfile
    else
      try Sys.remove !tmpfile with Sys_error _ -> ())

let set_tmpfile _ l =
  if not !tmpfile_set then
    begin
      let name = List.hd l in
      let name = Filename.basename name in
      let name = Filename.chop_extension name in
      tmpfile := (Filename.get_temp_dir_name()) ^ "/aorai_" ^ name ^ 
                   (string_of_int (TestNumber.get())) ^ ".i";
      tmpfile_set := true
    end

let () = Kernel.Files.add_set_hook set_tmpfile

let extend () =
  let myrun =
    let run = !Db.Toplevel.run in
    fun f ->
      let my_project = Project.create "Reparsing" in
      run f;
      let chan = open_out !tmpfile in
      let fmt = Format.formatter_of_out_channel chan in
      File.pretty_ast ~prj:(Project.from_unique_name "aorai") ~fmt ();
      close_out chan;
      Project.set_current my_project;
      Files.append_after [ !tmpfile ];
      Constfold.off ();
      File.pretty_ast ();
      ok:=true (* no error, we can erase the file *)
        
  in
  Db.Toplevel.run := myrun

let () = extend ()


