load.ml 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 = function
  28. | Empty ->
  29. let display_name = match args.infile with
  30. | Some filename -> filename
  31. | None -> "<stdin>"
  32. in
  33. let bufsize = 512 in
  34. if args.cpp then
  35. let cpp_out = match args.infile with
  36. | Some filename ->
  37. Unix.open_process_in (cpp_cmd ^ " " ^ filename)
  38. | None ->
  39. let content = input_buffered stdin bufsize in
  40. let (cpp_out, cpp_in) = Unix.open_process cpp_cmd in
  41. output_string cpp_in content;
  42. close_out cpp_in;
  43. cpp_out
  44. in
  45. let _ = log_line 2 "Run C preprocessor" in
  46. (* Read preprocessed code from cpp's stdout *)
  47. let preprocessed = input_buffered cpp_out bufsize in
  48. FileContent (display_name, preprocessed)
  49. else
  50. let content = match args.infile with
  51. | Some filename -> input_all (open_in filename)
  52. | None -> input_buffered stdin bufsize
  53. in
  54. FileContent (display_name, content)
  55. | _ -> raise (InvalidInput "load")