parse.ml 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. open Lexing
  2. open Printf
  3. open Ast
  4. let get_position lexbuf =
  5. let pos = lexbuf.lex_curr_p in
  6. sprintf "%s:%d:%d" pos.pos_fname pos.pos_lnum
  7. (pos.pos_cnum - pos.pos_bol + 1)
  8. (*
  9. let get_loc lexbuf =
  10. let pos = lexbuf.lex_curr_p in
  11. let colnum = (pos.pos_cnum - pos.pos_bol + 1) in
  12. sprintf "%s:%d:%d" pos.pos_fname pos.pos_lnum
  13. (pos.pos_cnum - pos.pos_bol + 1)
  14. *)
  15. let parse_with_error lexbuf =
  16. try Some (Parser.program Lexer.token lexbuf) with
  17. | Lexer.SyntaxError msg ->
  18. raise (CompileError (sprintf "%s: %s" (get_position lexbuf) msg))
  19. | Parser.Error ->
  20. raise (CompileError (sprintf "%s: syntax error" (get_position lexbuf)))
  21. (*raise (LocError ("syntax error" (get_loc lexbuf)))*)
  22. let phase repr =
  23. print_endline "- Parse input";
  24. match repr with
  25. | Inputfile (filename, verbose) ->
  26. (* TODO: run preprocessor *)
  27. let infile = match filename with
  28. | Some value -> open_in value
  29. | None -> stdin
  30. in
  31. let display_name = match filename with
  32. | Some value -> value
  33. | None -> "stdin"
  34. in
  35. let lexbuf = Lexing.from_channel infile in
  36. lexbuf.lex_curr_p <- { lexbuf.lex_curr_p with pos_fname = display_name };
  37. let ast = parse_with_error lexbuf in
  38. close_in infile;
  39. (match ast with
  40. | None -> failwith "error during parsing"
  41. | Some ast -> Node (ast, verbose))
  42. | _ -> failwith "invalid input for this phase"