refactor errors

This commit is contained in:
tali 2023-11-29 13:43:14 -05:00
parent c800a14262
commit 3cd480fbee
4 changed files with 24 additions and 17 deletions

View File

@ -1,6 +1,8 @@
let () =
Logs.set_reporter (Logs.format_reporter ());
Logs.set_level (Some Logs.Debug);
try
let modl = Spice.parse "fun main(x) { val y = x * 2 val z = if(y > x) y else 1 }" in
Format.fprintf Format.std_formatter "%a\n" Spice.Syn.pp_modl modl
with Spice.Error.Error err ->
Format.fprintf Format.err_formatter "error: %a\n" Spice.Error.pp err
let syn = Spice.parse "val x = 3 val y = x + 1" in
Fmt.pr "%a\n" Spice.Syn.pp_modl syn
with Spice.Error msg -> Logs.err (fun m -> m "%s" msg)

View File

@ -1,8 +0,0 @@
type t = Syntax of string
exception Error of t
let raise_syntax_error msg = raise (Error (Syntax msg))
let pp ppf = function
| Syntax why -> Format.fprintf ppf "syntax error: %s" why

View File

@ -1,6 +1,11 @@
{
open Parser
exception Error of string
let fail msg =
raise (Error msg)
let keywords = Hashtbl.create 17
let _ = begin
Hashtbl.add keywords "true" Kw_true;
@ -27,7 +32,7 @@ let parse_integer str =
Buffer.add_char buffer ch)
str;
if Buffer.length buffer > 18 then
Error.raise_syntax_error "integer literal is too long";
fail "integer literal is too long";
Int64.of_string (Buffer.contents buffer)
let identifier str =
@ -68,6 +73,6 @@ rule read =
| "!=" { Binop Not_eql }
| "." { Dot }
| "," { Com }
| _ { Error.raise_syntax_error "unrecognized character" }
| _ { fail "unrecognized character" }
| eof { EOF }

View File

@ -1,7 +1,15 @@
module Error = Error
module Syn = Syn
module Ir = Ir
exception Error of string
let failf f = Fmt.kstr (fun s -> raise (Error s)) f
let parse input =
let lexbuf = Lexing.from_string input ~with_positions:true in
try Parser.modl Lexer.read lexbuf
with Parser.Error -> Error.raise_syntax_error "bad syntax"
try Parser.modl Lexer.read lexbuf with
| Parser.Error -> failf "syntax error"
| Lexer.Error msg -> failf "syntax error: %s" msg
let compile syn =
try Anf_pass.anf syn with Failure msg -> failf "compilation error: %s" msg