load.ml 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. open Ast
  2. let input_all ic =
  3. let n = in_channel_length ic in
  4. let buf = String.create n in
  5. really_input ic buf 0 n;
  6. close_in ic;
  7. buf
  8. let input_buffered ic chunksize =
  9. let rec read_all buf bufsize pos =
  10. match input ic buf pos (bufsize - pos) with
  11. | 0 -> (close_in ic; buf)
  12. | nread when nread = bufsize - pos ->
  13. let bufsize = bufsize + chunksize in
  14. let pos = pos + nread in
  15. read_all (buf ^ String.create chunksize) bufsize pos
  16. | nread ->
  17. read_all buf bufsize (pos + nread)
  18. in
  19. read_all (String.create chunksize) chunksize 0
  20. let phase ir =
  21. prerr_endline "- Load input file";
  22. match ir with
  23. | Args args ->
  24. let display_name = match args.filename with
  25. | Some filename -> filename
  26. | None -> "<stdin>"
  27. in
  28. let bufsize = 512 in
  29. if args.cpp then
  30. let cpp_out = match args.filename with
  31. | Some filename ->
  32. Unix.open_process_in ("cpp " ^ filename)
  33. | None ->
  34. let content = input_buffered stdin bufsize in
  35. let (cpp_out, cpp_in) = Unix.open_process "cpp" in
  36. output_string cpp_in content;
  37. close_out cpp_in;
  38. cpp_out
  39. in
  40. let _ = prerr_endline "- Run C preprocessor" in
  41. (* Read preprocessed code from cpp's stdout *)
  42. let preprocessed = input_buffered cpp_out bufsize in
  43. FileContent (display_name, preprocessed, args)
  44. else
  45. let content = match args.filename with
  46. | Some filename -> input_all (open_in filename)
  47. | None -> input_buffered stdin bufsize
  48. in
  49. FileContent (display_name, content, args)
  50. | _ -> raise (InvalidInput "load")