load.ml 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 =
  30. match Globals.args.infile with
  31. | Some filename -> filename
  32. | None -> "<stdin>"
  33. in
  34. let bufsize = 512 in
  35. if Globals.args.cpp then
  36. let cpp_out =
  37. match Globals.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. log_line 2 "Run C preprocessor";
  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 =
  53. match Globals.args.infile with
  54. | Some filename -> input_all (open_in filename)
  55. | None -> input_buffered stdin bufsize
  56. in
  57. FileContent (display_name, content)
  58. | _ -> raise (InvalidInput "load")