load.ml 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. open Ast
  2. (* Unix command to call for C preprocessor:
  3. * -nostdinc : don't include from C stdlib
  4. * -C : don't remove comments
  5. * -traditional-cpp : don't remove excessive whitespaces, so that error
  6. * messages preserve correct character locations *)
  7. let cpp_cmd = "cpp -nostdinc -C -traditional-cpp"
  8. let input_all ic =
  9. let n = in_channel_length ic in
  10. let buf = String.create n in
  11. really_input ic buf 0 n;
  12. close_in ic;
  13. buf
  14. let input_buffered ic chunksize =
  15. let rec read_all buf bufsize pos =
  16. match input ic buf pos (bufsize - pos) with
  17. | 0 -> (close_in ic; buf)
  18. | nread when nread = bufsize - pos ->
  19. let bufsize = bufsize + chunksize in
  20. let pos = pos + nread in
  21. read_all (buf ^ String.create chunksize) bufsize pos
  22. | nread ->
  23. read_all buf bufsize (pos + nread)
  24. in
  25. read_all (String.create chunksize) chunksize 0
  26. let phase ir =
  27. prerr_endline "- Load input file";
  28. match ir with
  29. | Args args ->
  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. let _ = prerr_endline "- Run C preprocessor" in
  47. (* Read preprocessed code from cpp's stdout *)
  48. let preprocessed = input_buffered cpp_out bufsize in
  49. FileContent (display_name, preprocessed, args)
  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, args)
  56. | _ -> raise (InvalidInput "load")