mlox/lib/error.ml

64 lines
2.2 KiB
OCaml

type code_pos = { line : int; col : int }
type lexer_error = { pos : code_pos; msg : string }
module LexerError = struct
type t = lexer_error
let make (pos : code_pos) (msg : string) : lexer_error = { pos; msg }
let show (e : lexer_error) =
Printf.sprintf "LexerError at line %d, column %d: %s" e.pos.line e.pos.col e.msg
end
type parser_error = { pos : code_pos; msg : string }
module ParserError = struct
type t = parser_error
let make (pos : code_pos) (msg : string) : parser_error = { pos; msg }
let show (e : parser_error) =
Printf.sprintf "ParserError at line %d, column %d: %s" e.pos.line e.pos.col e.msg
end
(* type runtime_error = { pos : code_pos; msg : string; type_ : runtime_error_type } *)
type runtime_error = Error of { pos : code_pos; msg : string } | Break | Continue
module RuntimeError = struct
type t = parser_error
let make (pos : code_pos) (msg : string) : runtime_error = Error { pos; msg }
let break () : runtime_error = Break
let continue () : runtime_error = Continue
let show (e : runtime_error) =
match e with
| Error { pos; msg } ->
Printf.sprintf "RuntimeError at line %d, column %d: %s" pos.line pos.col msg
| Break | Continue -> assert false
end
type lox_error =
| LexerError of lexer_error list
| ParserError of parser_error list
| RuntimeError of runtime_error
let print_error (e : lox_error) =
match e with
| LexerError es ->
let num_errors = List.length es in
assert (num_errors <> 0);
Printf.fprintf stderr "found %d %s:\n" num_errors
(if num_errors = 1 then "LexerError" else "LexerErrors");
List.iter (fun e -> LexerError.show e |> Printf.fprintf stderr "%s\n") es
| ParserError es ->
let num_errors = List.length es in
assert (num_errors <> 0);
Printf.fprintf stderr "found %d %s:\n" num_errors
(if num_errors = 1 then "ParserError" else "ParserErrors");
List.iter (fun e -> ParserError.show e |> Printf.fprintf stderr "%s\n") es
| RuntimeError e -> RuntimeError.show e |> Printf.fprintf stderr "%s\n"
let of_lexer_error e = Result.map_error (fun e -> LexerError e) e
let of_parser_error e = Result.map_error (fun e -> ParserError e) e
let of_runtimer_error e = Result.map_error (fun e -> RuntimeError e) e