A JSON parser generated by typed bnf, which gives your cross-language semantic actions, and static type checking before codeg generation, and automatic type inference!
You can copy all .cs
files from this project to get a complete Json parser. Such parser produces a JsonValue
, in case you needs to handle Json serialization for variant types:
interface JsonValue
class JInt : JsonValue
class JFloat : JsonValue
class JList : JsonValue
...
class JNull : JsonValue
- Install
bash build.sh
(see concrete commands atbuild.sh
)dotnet run
to see the results.
Check out generated antlr g4 source at testjson.g4
.
shape token {
Text : str
}
// Using type alias is a workaround for C# codegen.
// C# has no type alias so we cannot refer to types
// via language-independent names.
// Some declarations. they specifies what you need to
// provide for generating this parser.
val nil : forall 'a. () -> list['a]
val append : forall 'a. (list['a], 'a) -> list['a]
val json_dict: (list[(str, JsonValue)]) -> JsonValue
val parse_int: (str) -> int
val parse_float: (str) -> float
val unesc_string: (str) -> str
val json_list: (list[JsonValue]) -> JsonValue
val json_int : (int) -> JsonValue
val json_float : (float) -> JsonValue
val json_string : (str) -> JsonValue
val json_bool : (int) -> JsonValue
val json_null : () -> JsonValue
start : json <EOF> { $1 }
// parametric rules!
list[a] : a { [$1] }
| list[a] a { append($1, $2) }
seplist[sep, elt] : seplist[sep, elt] sep elt { append($1, $3) }
| elt { [$1] }
nullable[a] : a { $1 }
| { [] }
str : <str> { unesc_string($1.Text) }
pair : str ":" json { ($1, $3) }
json : "[" nullable[seplist[",", json]] "]" { json_list($2) }
| "{" nullable[seplist[",", pair]] "}" { json_dict($2) }
| <int> { json_int(parse_int($1.Text)) }
| <FLOAT> { json_float(parse_float($1.Text)) }
| str { json_string($1) }
| "null" { json_null() }
| "true" { json_bool(1) }
| "false" { json_bool(0) }
%ignore <ws>
<ESCAPED_QUOTE> : "\\\""
<str> : "\"" ( ESCAPED_QUOTE | !"\"")* "\""
<ws> : ("\r" | "\t" | "\n" | " ")
<exp> : ("E"|"e") DIGIT+
<int> : "-"? DIGIT+ exp?
<DIGIT> : [0 .. 9]
<FLOAT> : "-"? int "." int exp?
You can check JsonParse.cs
to see how we interface with the Antlr4-generated parser.