(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) (* JSON text to JSONB and back, as sqlite/src/json.c at version-3.54.1 writes them: jsonTranslateTextToBlob, which reads JSON5 too, and jsonTranslateBlobToText, which writes RFC 8259. *) open Jsonb_core let is_alpha c = (c >= 0x61 && c <= 0x7a) || (c >= 0x41 && c <= 0x5a) (* sqlite3JsonId1 / sqlite3JsonId2: a letter, '$', '_' or a byte from 0x80; then digits too *) let is_id1 c = is_alpha c || c = 0x24 || c = 0x5f || c >= 0x80 let is_id2 c = is_id1 c || is_digit c (* sqlite3UpperToLower on ASCII *) let lower c = if c >= 0x41 && c <= 0x5a then c + 0x20 else c let malformed () = Jsonb_error.fail_malformed () let too_deep () = Jsonb_error.fail_too_deep () (* ── Text to JSONB (jsonTranslateTextToBlob) ──────────────────── *) let is_2hex z i = is_xdigit (zc z i) && is_xdigit (zc z (i + 1)) (* strncmp: [z] at [i] starts with [m] *) let starts z i m = let len = String.length m in i + len <= String.length z && String.sub z i len = m (* sqlite3StrNICmp over [len] bytes of [z] at [i] against [m] *) let strnicmp z i m len = let rec go k = k >= len || (lower (zc z (i + k)) = lower (zc m k) && go (k + 1)) in go 0 (* the end of a '/*' comment whose body starts at [j], if it closes *) let rec comment_end z j = if zc z j = 0 then None else if zc z j = 0x2f && zc z (j - 1) = 0x2a then Some (j + 1) else comment_end z (j + 1) (* the end of a '//' comment from [j]: its line break, or U+2028/2029 *) let rec line_end z j = let c = zc z j in if c = 0 || c = 0x0a || c = 0x0d then j else if c = 0xe2 && zc z (j + 1) = 0x80 && (zc z (j + 2) = 0xa8 || zc z (j + 2) = 0xa9) then j + 2 else line_end z (j + 1) (* the length of the multi-byte space at [n], 0 for none *) let unicode_space z n = let c1 = zc z (n + 1) and c2 = zc z (n + 2) in match zc z n with | 0xc2 -> if c1 = 0xa0 then 2 else 0 | 0xe1 -> if c1 = 0x9a && c2 = 0x80 then 3 else 0 | 0xe2 -> if c1 = 0x80 && c2 >= 0x80 && (c2 <= 0x8a || c2 = 0xa8 || c2 = 0xa9 || c2 = 0xaf) then 3 else if c1 = 0x81 && c2 = 0x9f then 3 else 0 | 0xe3 -> if c1 = 0x80 && c2 = 0x80 then 3 else 0 | 0xef -> if c1 = 0xbb && c2 = 0xbf then 3 else 0 | _ -> 0 (* json5Whitespace: the length of the JSON5 white space and comments at [i] *) let json5_whitespace z i = let rec go n = match zc z n with | 0x09 | 0x0a | 0x0b | 0x0c | 0x0d | 0x20 -> go (n + 1) | 0x2f -> if zc z (n + 1) = 0x2a && zc z (n + 2) <> 0 then match comment_end z (n + 3) with Some n -> go n | None -> n else if zc z (n + 1) = 0x2f then let j = line_end z (n + 2) in go (if zc z j <> 0 then j + 1 else j) else n | _ -> let k = unicode_space z n in if k > 0 then go (n + k) else n in go i - i (* strspn over jsonSpaces *) let skip_spaces z i = let rec go j = if is_space (zc z j) then go (j + 1) else j in go i let fail_at t i = t.err <- i; -1 (* aNanInfName: the extra literals and what they become *) let nan_inf = [ ('i', 'I', "inf", `Inf); ('i', 'I', "infinity", `Inf); ('n', 'N', "NaN", `Null); ('q', 'Q', "QNaN", `Null); ('s', 'S', "SNaN", `Null); ] (* true, false, null and the NaN and infinity names at [i] *) let parse_word t z i = let c = zc z i in let word w ty = if starts z i w && not (is_alnum (zc z (i + String.length w))) then begin append_byte t ty; Some (i + String.length w) end else None in let literal = match c with | 0x74 -> word "true" t_true | 0x66 -> word "false" t_false | 0x6e -> word "null" t_null | _ -> None in match literal with | Some j -> j | None when c = 0x74 || c = 0x66 -> fail_at t i | None -> ( let matches (c1, c2, m, _) = let nn = String.length m in (c = Char.code c1 || c = Char.code c2) && strnicmp z i m nn && not (is_alnum (zc z (i + nn))) in match List.find_opt matches nan_inf with | None -> fail_at t i | Some (_, _, m, kind) -> (match kind with | `Inf -> append_node t t_float "9e999" 0 5 | `Null -> append_byte t t_null); t.has_nonstd <- true; i + String.length m) (* the escapes RFC 8259 has *) let json_escape z j = match zc z j with | 0x22 | 0x5c | 0x2f | 0x62 | 0x66 | 0x6e | 0x72 | 0x74 -> true | 0x75 -> is_4hex z (j + 1) | _ -> false (* the escapes JSON5 adds, but for a backslash before CR LF *) let json5_escape z j = match zc z j with | 0x27 | 0x76 | 0x0a -> true | 0x30 -> not (is_digit (zc z (j + 1))) | 0xe2 -> zc z (j + 1) = 0x80 && (zc z (j + 2) = 0xa8 || zc z (j + 2) = 0xa9) | 0x78 -> is_2hex z (j + 1) | _ -> false (* After a backslash at [j - 1] in a string: the opcode the escape makes the string and where the escape ends, or [None] if it is no escape. *) let string_escape t z j opcode = if json_escape z j then Some ((if opcode = t_text then t_textj else opcode), j) else if json5_escape z j then begin t.has_nonstd <- true; Some (t_text5, j) end else if zc z j = 0x0d then begin t.has_nonstd <- true; Some (t_text5, if zc z (j + 1) = 0x0a then j + 1 else j) end else None (* the next byte at or after [j] a string scan stops at: past one to three bytes that need no escape, as json.c's unrolled loop reads them *) let rec stop z j = if not (is_ok (zc z j)) then j else if not (is_ok (zc z (j + 1))) then j + 1 else if not (is_ok (zc z (j + 2))) then j + 2 else stop z (j + 3) let parse_string t z i = let delim = zc z i in let rec scan j opcode = let j = stop z j in let c = zc z j in if c = delim then Some (j, opcode) else if c = 0x5c then ( match string_escape t z (j + 1) opcode with | Some (opcode, j) -> scan (j + 1) opcode | None -> t.err <- j + 1; None) else if c = 0 then begin t.err <- j; None end else if c <= 0x1f then begin t.has_nonstd <- true; scan (j + 1) t_text5 end else scan (j + 1) (if c = 0x22 then t_text5 else opcode) in match scan (i + 1) t_text with | None -> -1 | Some (j, opcode) -> append_node t opcode z (i + 1) (j - 1 - i); j + 1 let finish_number t z i ty j = let i = if zc z i = 0x2b then i + 1 else i in append_node t (t_int + ty) z i (j - i); j (* the digits, point and exponent of a number from [i]; [ty] has bit 1 for JSON5 and bit 2 for a float *) let parse_number_2 t z i ty = let ty = ref ty and seen_e = ref false in (* a '.' just before [j], after a digit, is JSON5 *) let point_before j = zc z (j - 1) = 0x2e && j - 2 >= i && is_digit (zc z (j - 2)) && (t.has_nonstd <- true; ty := !ty lor 0x01; true) in let exponent j = if (zc z (j - 1) < 0x30 && not (point_before j)) || !seen_e then Error j else begin ty := !ty lor 0x02; seen_e := true; let j = if zc z (j + 1) = 0x2b || zc z (j + 1) = 0x2d then j + 1 else j in if is_digit (zc z (j + 1)) then Ok (j + 1) else Error j end in let rec digits j = let c = zc z j in if is_digit c then digits (j + 1) else if c = 0x2e then if !ty land 0x02 <> 0 then Error j else begin ty := !ty lor 0x02; digits (j + 1) end else if c = 0x65 || c = 0x45 then match exponent j with Ok j -> digits j | Error j -> Error j else Ok j in match digits (i + 1) with | Error j -> fail_at t j | Ok j -> if zc z (j - 1) < 0x30 && not (point_before j) then fail_at t j else finish_number t z i !ty j let rec hex_end z j = if is_xdigit (zc z j) then hex_end z (j + 1) else j (* a number after a sign at [i] *) let parse_signed t z i ty = let c = zc z i and c1 = zc z (i + 1) in if not (is_digit c1) then if (c1 = 0x49 || c1 = 0x69) && strnicmp z (i + 1) "inf" 3 then begin t.has_nonstd <- true; if c = 0x2d then append_node t t_float "-9e999" 0 6 else append_node t t_float "9e999" 0 5; i + if strnicmp z (i + 4) "inity" 5 then 9 else 4 end else if c1 = 0x2e then begin t.has_nonstd <- true; parse_number_2 t z i (ty lor 0x01) end else fail_at t i else if c1 = 0x30 && is_digit (zc z (i + 2)) then fail_at t (i + 1) else if c1 = 0x30 && (zc z (i + 2) = 0x78 || zc z (i + 2) = 0x58) && is_xdigit (zc z (i + 3)) then begin t.has_nonstd <- true; finish_number t z i (ty lor 0x01) (hex_end z (i + 4)) end else parse_number_2 t z i ty (* the number at [i], whose first character is a sign or a digit *) let parse_number t z i ty = let c = zc z i and c1 = zc z (i + 1) in if c = 0x30 then if (c1 = 0x78 || c1 = 0x58) && is_xdigit (zc z (i + 2)) then begin t.has_nonstd <- true; finish_number t z i 0x01 (hex_end z (i + 3)) end else if is_digit c1 then fail_at t (i + 1) else parse_number_2 t z i ty else if c < 0x30 then parse_signed t z i ty else parse_number_2 t z i ty (* An object's label at [j] whose parse answered [x]: the index past it, an unquoted JSON5 identifier included, or [`Close] for the '}' of an empty member list, or a failure. *) let object_label t z j x ~start = if x > 0 then `Label x else if x = -2 then begin if t.n <> start then t.has_nonstd <- true; `Close t.err end else let j = j + json5_whitespace z j in let op = ref t_text in let hex4 k = zc z k = 0x5c && zc z (k + 1) = 0x75 && is_4hex z (k + 2) && (op := t_textj; true) in if is_id1 (zc z j) || hex4 j then begin let rec id k = if (is_id2 (zc z k) && json5_whitespace z k = 0) || hex4 k then id (k + 1) else k in let k = id (j + 1) in append_node t !op z j (k - j); t.has_nonstd <- true; `Label k end else begin if x <> -1 then t.err <- j; `Fail end (* The element of [z] at [i] appended to [t]: the index past it, or 0 at the end of the text, -1 on a syntax error, and -2 to -5 on a '}', ']', ',' or ':' at [t.err]. *) let rec text_to_blob t z i = match zc z i with | 0x7b (* '{' *) -> parse_object t z i | 0x5b (* '[' *) -> parse_array t z i | 0x27 (* '\'' *) -> t.has_nonstd <- true; parse_string t z i | 0x22 (* '"' *) -> parse_string t z i | 0x2b (* '+' *) -> t.has_nonstd <- true; parse_number t z i 0 | 0x2e (* '.' *) -> if is_digit (zc z (i + 1)) then begin t.has_nonstd <- true; parse_number_2 t z i 0x03 end else fail_at t i | 0x2d | 0x30 | 0x31 | 0x32 | 0x33 | 0x34 | 0x35 | 0x36 | 0x37 | 0x38 | 0x39 -> parse_number t z i 0 | (0x7d | 0x5d | 0x2c | 0x3a) as c -> (* '}' ']' ',' ':' *) t.err <- i; if c = 0x7d then -2 else if c = 0x5d then -3 else if c = 0x2c then -4 else -5 | 0 -> 0 | 0x09 | 0x0a | 0x0d | 0x20 -> text_to_blob t z (skip_spaces z (i + 1)) | 0x0b | 0x0c | 0x2f | 0xc2 | 0xe1 | 0xe2 | 0xe3 | 0xef -> let j = json5_whitespace z i in if j > 0 then begin t.has_nonstd <- true; text_to_blob t z (i + j) end else fail_at t i | _ -> parse_word t z i (* After an element ending at [j]: the next member from [j + 1] on a comma, [`Close] on the closing byte [close] (code [code] from a parse), or a failure. *) and after_element t z j ~close ~code = let next j = let x = text_to_blob t z j in if x = -4 then `Next (t.err + 1) else if x = code then `Close t.err else begin t.err <- j; `Fail end in let c = zc z j in if c = 0x2c then `Next (j + 1) else if c = close then `Close j else if is_space c then let j = skip_spaces z (j + 1) in let c = zc z j in if c = 0x2c then `Next (j + 1) else if c = close then `Close j else next j else next j (* the ':' after a label ending at [j], and the index past it *) and colon t z j = if zc z j = 0x3a then Some (j + 1) else let j = if is_space (zc z j) then skip_spaces z (j + 1) else j in if zc z j = 0x3a then Some (j + 1) else let x = text_to_blob t z j in if x <> -5 then begin if x <> -1 then t.err <- j; None end else Some (t.err + 1) (* the value of a member from [j], and what follows it *) and member_value t z j ~start = let x = text_to_blob t z j in if x <= 0 then begin if x <> -1 then t.err <- j; `Fail end else match after_element t z x ~close:0x7d ~code:(-2) with | `Next j -> members t z j ~start | (`Close _ | `Fail) as r -> r and members t z j ~start = let iblob = t.n in match object_label t z j (text_to_blob t z j) ~start with | (`Fail | `Close _) as r -> r | `Label x -> ( let ty = byte t iblob land 0x0f in if ty < t_text || ty > t_textraw then begin t.err <- j; `Fail end else match colon t z x with | None -> `Fail | Some j -> member_value t z j ~start) and container t z i typ elements = let this = t.n in append_header t typ (String.length z - i); let start = t.n in t.depth <- t.depth + 1; if t.depth > max_depth then fail_at t i else match elements t z (i + 1) ~start with | `Fail -> -1 | `Close j -> ignore (change_payload_size t this (t.n - start) : int); t.depth <- t.depth - 1; j + 1 and parse_object t z i = container t z i t_object members and elements t z j ~start = let x = text_to_blob t z j in if x > 0 then match after_element t z x ~close:0x5d ~code:(-3) with | `Next j -> elements t z j ~start | (`Close _ | `Fail) as r -> r else if x = -3 then begin if t.n <> start then t.has_nonstd <- true; `Close t.err end else begin if x <> -1 then t.err <- j; `Fail end and parse_array t z i = container t z i t_array elements (* jsonConvertTextToBlob: the text [z] as JSONB, or [None] if it is not JSON or JSON5 *) let of_string z = let t = empty (String.length z + 16) in let i = text_to_blob t z 0 in if i <= 0 then Error t.err else let i = skip_spaces z i in if zc z i = 0 then Ok t else let i = i + json5_whitespace z i in if zc z i <> 0 then Error t.err else begin t.has_nonstd <- true; Ok t end (* jsonReturnStringAsBlob: [z] is JSON this module wrote *) let blob_of_text z = let t = empty (String.length z + 16) in ignore (text_to_blob t z 0 : int); contents t (* ── JSONB to text (jsonTranslateBlobToText) ──────────────────── *) let type_names = [| "null"; "true"; "false" |] type out = { b : Buffer.t; mutable bad : bool; mutable deep : bool } let out () = { b = Buffer.create 64; bad = false; deep = false } let failed o = o.bad || o.deep (* jsonStringTrimOneChar *) let trim_one o = if not (failed o) then Buffer.truncate o.b (Buffer.length o.b - 1) let hex_digits = "0123456789abcdef" (* jsonAppendControlChar *) let add_control b c = let special = match c with | 0x08 -> 'b' | 0x09 -> 't' | 0x0a -> 'n' | 0x0c -> 'f' | 0x0d -> 'r' | _ -> '\000' in Buffer.add_char b '\\'; if special <> '\000' then Buffer.add_char b special else begin Buffer.add_string b "u00"; Buffer.add_char b hex_digits.[c lsr 4]; Buffer.add_char b hex_digits.[c land 0xf] end (* jsonAppendString: [len] bytes of [s] from [off] as a JSON string *) let add_string b s off len = Buffer.add_char b '"'; let stop = off + len in let rec go i run = if i >= stop then Buffer.add_substring b s run (i - run) else let c = Char.code (String.unsafe_get s i) in if is_ok c then go (i + 1) run else begin Buffer.add_substring b s run (i - run); if c = 0x22 || c = 0x5c then begin Buffer.add_char b '\\'; Buffer.add_char b (Char.chr c) end else if c = 0x27 then Buffer.add_char b '\'' else add_control b c; go (i + 1) (i + 1) end in go off off; Buffer.add_char b '"' (* an INT5 payload, hexadecimal, as decimal; 9.0e999 past 64 bits *) let render_int5 t o p sz = let b = o.b in let k = match byte t p with | 0x2d -> Buffer.add_char b '-'; 3 | 0x2b -> 3 | _ -> 2 in let rec go k u overflow = if k >= sz then (u, overflow) else let c = byte t (p + k) in if not (is_xdigit c) then begin o.bad <- true; (u, overflow) end else if Int64.shift_right_logical u 60 <> 0L then go (k + 1) u true else go (k + 1) (Int64.add (Int64.mul u 16L) (Int64.of_int (hex_value c))) overflow in let u, overflow = go k 0L false in Buffer.add_string b (if overflow then "9.0e999" else Fmt.str "%Lu" u) (* a FLOAT5 payload with the digits RFC 8259 wants either side of the point *) let render_float5 t o p sz = let b = o.b in let neg = byte t p = 0x2d in if neg then Buffer.add_char b '-'; if neg && sz <= 1 then o.bad <- true else begin let k = if neg then 1 else 0 in if byte t (p + k) = 0x2e then Buffer.add_char b '0'; for k = k to sz - 1 do let c = byte t (p + k) in Buffer.add_char b (Char.chr c); if c = 0x2e && (k + 1 = sz || not (is_digit (byte t (p + k + 1)))) then Buffer.add_char b '0' done end (* A TEXT5 escape at [i], [rem] bytes left: what it renders as, and how many bytes past the backslash's two it takes, [None] if it is cut short. *) let text5_escape b z i rem = let c k = zc z (i + k) in match c 1 with | 0x27 -> Buffer.add_char b '\''; Some 0 | 0x76 -> Buffer.add_string b "\\u000b"; Some 0 | 0x78 -> if rem < 4 then None else begin Buffer.add_string b "\\u00"; Buffer.add_substring b z (i + 2) 2; Some 2 end | 0x30 -> Buffer.add_string b "\\u0000"; Some 0 | 0x0d -> Some (if rem > 2 && c 2 = 0x0a then 1 else 0) | 0x0a -> Some 0 | 0xe2 -> if rem < 4 || c 2 <> 0x80 || (c 3 <> 0xa8 && c 3 <> 0xa9) then None else Some 2 | _ -> Buffer.add_substring b z i 2; Some 0 (* a TEXT5 payload as canonical JSON *) let render_text5 o z = let b = o.b in Buffer.add_char b '"'; let rec go i rem = let rec run k = if k < rem && (is_ok (zc z (i + k)) || zc z (i + k) = 0x27) then run (k + 1) else k in let k = run 0 in if k > 0 then Buffer.add_substring b z i k; if k < rem then let i = i + k and rem = rem - k in let c0 = zc z i in if c0 = 0x22 then begin Buffer.add_string b "\\\""; go (i + 1) (rem - 1) end else if c0 <= 0x1f then begin add_control b c0; go (i + 1) (rem - 1) end else if rem < 2 then o.bad <- true else match text5_escape b z i rem with | None -> o.bad <- true | Some s -> go (i + 2 + s) (rem - 2 - s) in go 0 (String.length z); Buffer.add_char b '"' (* a number's or a string's payload *) let render_scalar t o ty p sz = let b = o.b in match ty with | 3 | 5 -> if sz = 0 then o.bad <- true else Buffer.add_subbytes b t.a p sz | 4 -> if sz = 0 then o.bad <- true else render_int5 t o p sz | 6 -> if sz = 0 then o.bad <- true else render_float5 t o p sz | 7 | 8 -> Buffer.add_char b '"'; Buffer.add_subbytes b t.a p sz; Buffer.add_char b '"' | 9 -> render_text5 o (Bytes.sub_string t.a p sz) | 10 -> add_string b (Bytes.sub_string t.a p sz) 0 sz | _ -> o.bad <- true let rec render t i o = let n = size t i in if n = 0 then begin o.bad <- true; t.n + 1 end else let ty = byte t i land 0x0f and p = i + n and sz = t.sz in if ty <= t_false then begin Buffer.add_string o.b type_names.(ty); i + 1 end else if ty = t_array || ty = t_object then begin render_container t o ty p sz; p + sz end else begin render_scalar t o ty p sz; p + sz end and render_container t o ty p sz = let b = o.b and obj = ty = t_object in Buffer.add_char b (if obj then '{' else '['); let stop = p + sz in t.depth <- t.depth + 1; if t.depth > max_depth then o.deep <- true; let rec go j x = if j < stop && not (failed o) then begin let j = render t j o in Buffer.add_char b (if obj && x land 1 = 0 then ':' else ','); go j (x + 1) end else (j, x) in let j, x = go p 0 in t.depth <- t.depth - 1; if (obj && x land 1 <> 0) || j > stop then o.bad <- true; if sz > 0 then trim_one o; Buffer.add_char b (if obj then '}' else ']') (* the element at [i] as JSON text *) let text_at t i = let o = out () in t.delta <- 0; ignore (render t i o : int); if o.deep then too_deep () else if o.bad then malformed (); Buffer.contents o.b (* ── Pretty text (jsonTranslateBlobToPrettyText) ─────────────── *) let pad o ~indent level = for _ = 1 to level do Buffer.add_string o.b indent done (* the element at [i] as text, an array's elements and an object's members one to a line, each [level] times [indent] deep *) let rec render_pretty t i o ~indent ~level = let n = size t i in if n = 0 then begin o.bad <- true; t.n + 1 end else let ty = byte t i land 0x0f in if ty = t_array || ty = t_object then begin let j = i + n in let stop = j + t.sz in let obj = ty = t_object in Buffer.add_char o.b (if obj then '{' else '['); if j < stop then begin Buffer.add_char o.b '\n'; let level = level + 1 in if level >= max_depth then o.deep <- true; if obj then begin t.depth <- level; pretty_members t o ~indent ~level j stop end else pretty_elements t o ~indent ~level j stop; Buffer.add_char o.b '\n'; pad o ~indent (level - 1) end; Buffer.add_char o.b (if obj then '}' else ']'); stop end else render t i o and pretty_elements t o ~indent ~level j stop = if not (failed o) then begin pad o ~indent level; let j = render_pretty t j o ~indent ~level in if j >= stop then (if j > stop then o.bad <- true) else begin Buffer.add_string o.b ",\n"; pretty_elements t o ~indent ~level j stop end end and pretty_members t o ~indent ~level j stop = if not (failed o) then begin pad o ~indent level; let j = render t j o in if j > stop then o.bad <- true else begin Buffer.add_string o.b ": "; let j = render_pretty t j o ~indent ~level in if j < stop then begin Buffer.add_string o.b ",\n"; pretty_members t o ~indent ~level j stop end end end let pretty t ~indent = let o = out () in t.delta <- 0; ignore (render_pretty t 0 o ~indent ~level:0 : int); if o.deep then too_deep () else if o.bad then malformed (); Buffer.contents o.b