about summary refs log tree commit diff
path: root/src/parser/Parser.ml
blob: ae868852f62f888eb7128b5db6c19b05af2a5f58 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
let handle_syntax_error ~source ~lexbuf f = try f () with
  | Lexer.IllegalCharacter illegal_char ->
    Error.illegal_character ~loc:(Asai.Range.of_lexbuf ~source lexbuf) illegal_char
  | Grammar.Error ->
    Error.syntax_error ~loc:(Asai.Range.of_lexbuf ~source lexbuf)

let parse_expr (s : string) : Ast.expr =
  let lexbuf = Lexing.from_string s in
  let string_source : Asai.Range.string_source = {
    title = None;
    content = s;
  } in
  let source = `String string_source in
  Eff.run ~env:source @@ fun () ->
  handle_syntax_error ~source ~lexbuf @@ fun () ->
  Grammar.start_expr Lexer.token lexbuf

let parse_file (path : string) : Ast.file =
  let inchan = try open_in path with
    | Sys_error msg -> Error.file_open_error ~path ~msg
  in
  let lexbuf = Lexing.from_channel inchan in
  let source = `File path in
  Eff.run ~env:source @@ fun () ->
  handle_syntax_error ~source ~lexbuf @@ fun () ->
  Grammar.start_file Lexer.token lexbuf