parse.ml 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. open Lexing
  2. open Printf
  3. open Ast
  4. let get_loc lexbuf =
  5. Util.loc_from_lexpos lexbuf.lex_curr_p lexbuf.lex_curr_p
  6. let parse_with_error lexbuf =
  7. try Some (Parser.program Lexer.token lexbuf) with
  8. | Lexer.SyntaxError msg ->
  9. raise (LocError (get_loc lexbuf, msg))
  10. | Parser.Error ->
  11. raise (LocError (get_loc lexbuf, "syntax error"))
  12. let phase repr =
  13. let _ = print_endline "- Parse input" in
  14. match repr with
  15. | Inputfile (filename, verbose) ->
  16. (* TODO: run preprocessor *)
  17. let infile = match filename with
  18. | Some value -> open_in value
  19. | None -> stdin
  20. in
  21. let display_name = match filename with
  22. | Some value -> value
  23. | None -> "stdin"
  24. in
  25. let lexbuf = Lexing.from_channel infile in
  26. lexbuf.lex_curr_p <- { lexbuf.lex_curr_p with pos_fname = display_name };
  27. let ast = parse_with_error lexbuf in
  28. close_in infile;
  29. (match ast with
  30. | None -> raise (CompileError "error during parsing")
  31. | Some ast -> Node (ast, verbose))
  32. | _ -> raise (CompileError "invalid input for this phase")