load.ml 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. open Printf
  2. open Ast
  3. let input_all ic =
  4. let n = in_channel_length ic in
  5. let buf = String.create n in
  6. really_input ic buf 0 n;
  7. close_in ic;
  8. buf
  9. let phase ir =
  10. prerr_endline "- Load input file";
  11. match ir with
  12. | Args args ->
  13. let display_name = match args.filename with
  14. | Some filename -> filename
  15. | None -> "<stdin>"
  16. in
  17. if args.cpp then
  18. let _ = prerr_endline "- Run C preprocessor" in
  19. let cpp_out = match args.filename with
  20. | Some filename ->
  21. Unix.open_process_in ("cpp " ^ filename)
  22. | None ->
  23. let content = input_all stdin in
  24. let (cpp_out, cpp_in) = Unix.open_process "cpp" in
  25. output_string cpp_in content;
  26. close_out cpp_in;
  27. cpp_out
  28. in
  29. (* Read preprocessed code from cpp's stdout *)
  30. let bufsize = 1024 in
  31. let newbuf () = String.create bufsize in
  32. let rec read_all buf pos =
  33. let nread = input cpp_out buf pos bufsize in
  34. if nread = 0
  35. then (close_in cpp_out; buf)
  36. else read_all (String.concat "" [buf; newbuf ()]) nread
  37. in
  38. let preprocessed = read_all (newbuf ()) 0 in
  39. FileContent (display_name, preprocessed, args)
  40. else
  41. let infile = match args.filename with
  42. | Some filename -> open_in filename
  43. | None -> stdin
  44. in
  45. FileContent (display_name, input_all infile, args)
  46. | _ -> raise (InvalidInput "load")