Skip to content

Commit 10a4b25

Browse files
committed
Improved the error messages to include the position and the token.
1 parent d699b7e commit 10a4b25

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

json-parser.sml

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,11 @@ structure JSONParser : sig
1616
structure T = JSONTokens
1717
structure J = JSON
1818

19-
fun error msg = raise Fail msg
20-
2119
fun parse' (srcMap, inStrm) = let
20+
fun error (pos, msg, tok) = raise Fail(concat[
21+
"error ", AntlrStreamPos.spanToString srcMap pos, ": ",
22+
msg, ", found '", JSONTokens.toString tok, "'"
23+
])
2224
val lexer = Lex.lex srcMap
2325
fun parseValue (strm : Lex.strm) = let
2426
val (tok, pos, strm) = lexer strm
@@ -32,7 +34,7 @@ structure JSONParser : sig
3234
| T.INT n => (strm, J.INT n)
3335
| T.FLOAT f => (strm, J.FLOAT f)
3436
| T.STRING s => (strm, J.STRING s)
35-
| _ => error "error parsing value"
37+
| _ => error (pos, "parsing value", tok)
3638
(* end case *)
3739
end
3840
and parseArray (strm : Lex.strm) = (case lexer strm
@@ -46,7 +48,7 @@ structure JSONParser : sig
4648
case tok
4749
of T.RB => (strm, v::items)
4850
| T.COMMA => loop (strm, v::items)
49-
| _ => error "error parsing array"
51+
| _ => error (pos, "parsing array", tok)
5052
(* end case *)
5153
end
5254
val (strm, items) = loop (strm, [])
@@ -62,7 +64,7 @@ structure JSONParser : sig
6264
in
6365
SOME(strm, (s, v))
6466
end
65-
| _ => error "error parsing field"
67+
| (tok, pos, _) => error (pos, "parsing field", tok)
6668
(* end case *))
6769
| _ => NONE
6870
(* end case *))
@@ -72,7 +74,7 @@ structure JSONParser : sig
7274
case lexer strm
7375
of (T.RCB, pos, strm) => (strm, fld::flds)
7476
| (T.COMMA, pos, strm) => loop (strm, fld::flds)
75-
| _ => error "error parsing object"
77+
| (tok, pos, _) => error (pos, "parsing object", tok)
7678
(* end case *))
7779
| NONE => (strm, flds)
7880
(* end case *))

0 commit comments

Comments
 (0)