load.ml 1.8 KB

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