hcfg/jslib/main.ml

50 lines
1.6 KiB
OCaml

type bytearray
external create_bytearray: Bytes.t -> bytearray = "Uint8Array" [@@mel.new]
module JsValue = struct
type jsvalue =
| NUMBER of Js.Float.t
| STRING of Js.String.t
| BINARY of bytearray
| BOOL of bool
| NULL of unit Js.Nullable.t
| ARRAY of jsvalue Js.Array.t
| OBJECT of jsvalue Js.Dict.t
end
let parse str =
let _hvalue_to_js = [%mel.raw {|
function _hvalue_to_js(hvalue) {
switch (hvalue.TAG) {
case 0:
// Number
case 1:
// String
case 2:
// Binary
case 3:
// Bool
case 4:
// Null
return hvalue._0
case 5:
return hvalue._0.map(_hvalue_to_js)
// Array
case 6:
// Obj
return Object.fromEntries(
Object.entries(hvalue._0).map(([k, v]) => [k, _hvalue_to_js(v)])
)
}
}
|}] in
let rec hvalue_to_js = function
| Hcfg.Parser.STRING s -> JsValue.STRING s
| Hcfg.Parser.INTEGER i -> JsValue.NUMBER (float_of_int i)
| Hcfg.Parser.FLOAT f -> JsValue.NUMBER f
| Hcfg.Parser.BINARY b -> JsValue.BINARY (create_bytearray b)
| Hcfg.Parser.BOOL b -> JsValue.BOOL b
| Hcfg.Parser.NULL -> JsValue.NULL (Js.Nullable.null)
| Hcfg.Parser.ARRAY a -> JsValue.ARRAY (Array.of_list (List.map hvalue_to_js a))
| Hcfg.Parser.OBJECT o -> JsValue.OBJECT (Js.Dict.fromList (List.map (fun (k, v) -> (k, hvalue_to_js v)) (Hcfg.Parser.Obj.to_list o))) in
Hcfg.Lexer.generate_tokens str |> Hcfg.Parser.parse |> hvalue_to_js |> _hvalue_to_js