load.ml 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. open Types
  2. open Util
  3. (* Unix command to call for C preprocessor:
  4. * -nostdinc : don't include from C stdlib
  5. * -C : don't remove comments
  6. * -traditional-cpp : don't remove excessive whitespaces, so that error
  7. * messages preserve correct character locations *)
  8. let cpp_cmd = "cpp -nostdinc -C -traditional-cpp"
  9. let input_all ic =
  10. let n = in_channel_length ic in
  11. let buf = String.create n in
  12. really_input ic buf 0 n;
  13. close_in ic;
  14. buf
  15. let input_buffered ic chunksize =
  16. let rec read_all buf bufsize pos =
  17. match input ic buf pos (bufsize - pos) with
  18. | 0 -> (close_in ic; buf)
  19. | nread when nread = bufsize - pos ->
  20. let bufsize = bufsize + chunksize in
  21. let pos = pos + nread in
  22. read_all (buf ^ String.create chunksize) bufsize pos
  23. | nread ->
  24. read_all buf bufsize (pos + nread)
  25. in
  26. read_all (String.create chunksize) chunksize 0
  27. let phase ir =
  28. log_line 2 "- Load input file";
  29. match ir with
  30. | Empty ->
  31. let display_name = match args.infile with
  32. | Some filename -> filename
  33. | None -> "<stdin>"
  34. in
  35. let bufsize = 512 in
  36. if args.cpp then
  37. let cpp_out = match args.infile with
  38. | Some filename ->
  39. Unix.open_process_in (cpp_cmd ^ " " ^ filename)
  40. | None ->
  41. let content = input_buffered stdin bufsize in
  42. let (cpp_out, cpp_in) = Unix.open_process cpp_cmd in
  43. output_string cpp_in content;
  44. close_out cpp_in;
  45. cpp_out
  46. in
  47. let _ = log_line 2 "- Run C preprocessor" in
  48. (* Read preprocessed code from cpp's stdout *)
  49. let preprocessed = input_buffered cpp_out bufsize in
  50. FileContent (display_name, preprocessed)
  51. else
  52. let content = match args.infile with
  53. | Some filename -> input_all (open_in filename)
  54. | None -> input_buffered stdin bufsize
  55. in
  56. FileContent (display_name, content)
  57. | _ -> raise (InvalidInput "load")