(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire . All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) open Core (* [true] or [false], in any case. *) let bool_of_string_ci s = match String.lowercase_ascii s with | "true" -> Some true | "false" -> Some false | _ -> None (* [Stdlib.string_of_float] without its loss: the shortest of 15 and 17 significant digits that reads back as [f]. 17 always does for a finite double (IEEE 754-2019 section 5.12.2), and 15 keeps the usual decimals, 0.1 among them, as written. *) let string_of_float f = let s = Fmt.str "%.15g" f in if Float.equal (float_of_string s) f then s else Fmt.str "%.17g" f module Attr = struct (* An attribute decoder is handed the value and nothing else, so it raises with no place of its own; whoever looked the attribute up runs it under [locate_at] and gives the error the value's span. *) type 'a t = { dec : string -> 'a; enc : 'a -> string } let err_attr exp = Error.kinded_sort meta_none ~exp ~fnd:Sort.Attribute let string = { dec = Fun.id; enc = Fun.id } let scalar exp of_string enc = { dec = (fun s -> match of_string s with Some v -> v | None -> err_attr exp); enc; } let int = scalar "integer" int_of_string_opt string_of_int let float = scalar "float" float_of_string_opt string_of_float let bool = scalar "boolean" bool_of_string_ci string_of_bool let option codec = { dec = (fun s -> Some (codec.dec s)); enc = (fun v -> match v with | Some v -> codec.enc v | None -> (* should not happen *) ""); } end (* The GADT codec type. Each constructor is inspectable data that can be pattern-matched by decode, encode, or any future interpreter (schema generation, etc.). This is the "finally tagged" approach. *) (* Base decoders for text content (string/int/float/bool) and user- supplied map transformers raise Loc.Error on failure. The top- level decoder catches and converts to the documented result shape. *) (* What a codec calls an element or an attribute: a local part and, when the codec was given one, the namespace it is in. With none it means what the local part means written unprefixed where it is read or written: an element in the default namespace in scope there, an attribute in no namespace. *) type name = { ns : string option; local : string } let pp_name ppf n = match n.ns with | None | Some "" -> Fmt.string ppf n.local | Some uri -> Fmt.pf ppf "{%s}%s" uri n.local let name_string n = Fmt.str "%a" pp_name n (* [El.finish] builds an element codec with no element of its own, whose attributes and children land on the element around it. *) let no_name = { ns = None; local = "" } let is_named n = n.local <> "" let element_matches n ~scope qname = element_is scope ?ns:n.ns n.local qname type ('a, 'b) base_map = { kind : string; dec : string -> 'b; enc : 'b -> string; } type ('a, 'b) map_with = { dom : 'a t; map_dec : 'a -> 'b; map_enc : 'b -> 'a } and ('ret, 'f) dec_fun = | Fun : 'f -> ('ret, 'f) dec_fun | App : ('ret, 'a -> 'b) dec_fun * 'a Type.Id.t -> ('ret, 'b) dec_fun and _ t = | Text : string t | Text_map : (string, 'b) base_map -> 'b t | Element : name * 'a t -> 'a t | El : name * ('o, 'o) el_map -> 'o t | Codec_fn : 'a t_fn -> 'a t | Map : ('a, 'b) map_with -> 'b t | Const : 'a -> 'a t | Option : 'a t -> 'a option t | Rec : 'a t Lazy.t -> 'a t | List : 'a t -> 'a list t | Any : Value.t t | Skip : unit t and 'a t_fn = { kind : string; dec : P.stream -> P.start_tag -> 'a; enc : encoder -> 'a -> unit; } and ('o, 'dec) el_map = { dec : ('o, 'dec) dec_fun; fields : 'o el_field list; needs_children : bool; } and 'o el_field = | Attr : name * 'a Attr.t * 'a Type.Id.t * ('o -> 'a) -> 'o el_field | Attr_opt : name * 'a Attr.t * 'a option Type.Id.t * ('o -> 'a option) -> 'o el_field | Child : name * 'a t * 'a Type.Id.t * ('o -> 'a) -> 'o el_field | Child_opt : name * 'a t * 'a option Type.Id.t * ('o -> 'a option) -> 'o el_field | Children : name * 'a t * 'a list Type.Id.t * ('o -> 'a list) -> 'o el_field | El_text : string Type.Id.t * ('o -> string) -> 'o el_field let rec apply_dec_fun : type ret f. (ret, f) dec_fun -> Dict.t -> f = fun df dict -> match df with | Fun f -> f | App (rest, id) -> let f = apply_dec_fun rest dict in let v = match Dict.find id dict with | Some v -> v | None -> failwith "internal: field not found in dict" in f v (* A codec named one element and the document has another. Both names are said, because neither on its own tells the reader what to change, and the error points at the name that is there. *) let err_expected_element (tag : string Loc.node) exp = Error.expected (snd tag) ("<" ^ name_string exp ^ ">") ~fnd:("<" ^ fst tag ^ ">") let named_attr scope n attrs = List.find_opt (fun (a : attr) -> attr_is scope ?ns:n.ns n.local (fst a.name)) attrs (* Decode attrs from the attrs list, populating the Dict for Attr/Attr_opt fields. Returns the dict with all attribute fields populated. The member frame takes the attribute's own name node, so the path an error carries says where the member was written and not only what it was called. A member that is not there has no node, and the frame falls back to the name the codec asked for. *) let decode_attr : type a. string Loc.node -> string Loc.node -> Namespace.t -> attr list -> Dict.t -> name -> a Attr.t -> a Type.Id.t -> Dict.t = fun el_kind el_tag scope attrs dict name codec id -> match named_attr scope name attrs with | None -> let name = name_string name in push_object_ctx el_kind (name, Meta.none) (fun () -> Error.missing_attr (snd el_tag) name) | Some a -> let v = push_object_ctx el_kind a.name (fun () -> locate_at (snd a.value) (fun () -> codec.dec (fst a.value))) in Dict.add id v dict let decode_attr_opt : type a. string Loc.node -> Namespace.t -> attr list -> Dict.t -> name -> a Attr.t -> a option Type.Id.t -> Dict.t = fun el_kind scope attrs dict name codec id -> match named_attr scope name attrs with | None -> Dict.add id None dict | Some a -> let v = push_object_ctx el_kind a.name (fun () -> locate_at (snd a.value) (fun () -> codec.dec (fst a.value))) in Dict.add id (Some v) dict let decode_attr_field el_kind el_tag scope attrs dict = function | Attr (name, codec, id, _enc) -> decode_attr el_kind el_tag scope attrs dict name codec id | Attr_opt (name, codec, id, _enc) -> decode_attr_opt el_kind scope attrs dict name codec id | Child _ | Child_opt _ | Children _ | El_text _ -> dict let dec_attrs : type o. string Loc.node -> Namespace.t -> o el_field list -> attr list -> Dict.t -> Dict.t = fun el_tag scope fields attrs dict -> let el_kind = element_kind_node el_tag in List.fold_left (decode_attr_field el_kind el_tag scope attrs) dict fields (* Seed the initial dict with empty lists for every Children field. *) let init_children_dict fields dict = List.fold_left (fun d field -> match field with | Children (_tag, _inner, id, _enc) -> Dict.add id [] d | _ -> d) dict fields (* The dictionary an element with no children yields: nothing matched, so every child field falls back to what an empty body gives it. *) let empty_children_dict fields dict = List.fold_left (fun d field -> match field with | Child_opt (_tag, _inner, id, _enc) -> Dict.add id None d | Children (_tag, _inner, id, _enc) -> Dict.add id [] d | El_text (id, _enc) -> Dict.add id "" d | Attr _ | Attr_opt _ | Child _ -> d) dict fields (* Every [Child] field is required, so one left unset by the decode of a body is a missing child rather than an internal dictionary miss. The child that is not there has no node to be pointed at, so the error points at the name of the element that should have held it. Both runtimes can see that node, which is why it and not the element's own span is what an error about an element as a whole takes: a stream reading an element body has not got to the byte the element ends on. *) let check_required_children el_tag fields dict = List.iter (function | Child (tag, _inner, id, _enc) -> ( match Dict.find id dict with | Some _ -> () | None -> Error.missing_child (snd el_tag) (name_string tag)) | Attr _ | Attr_opt _ | Child_opt _ | Children _ | El_text _ -> ()) fields (* After the stream loop: store accumulated text in El_text fields and None for any Child_opt fields that were never matched. *) let finalize_children_dict fields text dict = let d = List.fold_left (fun d field -> match field with El_text (id, _enc) -> Dict.add id text d | _ -> d) dict fields in List.fold_left (fun d field -> match field with | Child_opt (_tag, _inner, id, _enc) -> ( match Dict.find id d with Some _ -> d | None -> Dict.add id None d) | Children (_tag, _inner, id, _enc) -> ( (* Both body loops cons, so the accumulator is in reverse document order until here. [init_children_dict] seeded every [Children] field of [fields] and nothing else writes one, so each list is reversed exactly once, at the level that built it. *) match Dict.find id d with | Some l -> Dict.add id (List.rev l) d | None -> d) | _ -> d) d fields (* How to decode the child element at hand with any codec: the stream reads it off its cursor and the tree off the node it holds. *) type dec_child = { run : 'a. 'a t -> 'a } let dec_child_field : type o. string Loc.node -> string Loc.node -> Namespace.t -> dec_child -> Dict.t -> o el_field -> Dict.t option = fun el_kind child_tag scope d dict field -> let is n = element_matches n ~scope (fst child_tag) in let run inner = push_object_ctx el_kind child_tag (fun () -> d.run inner) in match field with | Child (ftag, inner, id, _enc) when is ftag -> Some (Dict.add id (run inner) dict) | Child_opt (ftag, inner, id, _enc) when is ftag -> Some (Dict.add id (Some (run inner)) dict) | Children (ftag, inner, id, _enc) when is ftag -> let prev = Option.value ~default:[] (Dict.find id dict) in let x = push_array_ctx_lazy (list_kind_node (name_string ftag, snd child_tag)) ~index:(fun () -> List.length prev) (fun () -> d.run inner) in Some (Dict.add id (x :: prev) dict) | Attr _ | Attr_opt _ | Child _ | Child_opt _ | Children _ | El_text _ -> None (* First declared field that names the child's tag wins. A child no field names is [None], and the caller ignores it: the stream by skipping its bytes. *) let dec_child el_kind fields child_tag scope d dict = List.find_map (dec_child_field el_kind child_tag scope d dict) fields let skip_unmatched_child s (st : P.start_tag) = if st.self_close then () else begin stream_skip_children s; P.consume_end_tag s (fst st.tag) end (* The end tag of the element being decoded. Reading it is what settles where the element ends, so it belongs to whoever read the body: [dec_stream] consumes the whole of an element whose start tag it was handed, and nothing above it consumes anything. *) let end_element s (st : P.start_tag) = if not st.self_close then P.consume_end_tag s (fst st.tag) (* Process children from the stream for an El codec. Reads events sequentially: for each child start tag, checks if any declared field matches; if so, decodes inline. Unmatched children are skipped. Text content is accumulated for El_text fields. *) let rec dec_stream_children : type o. string Loc.node -> o el_field list -> P.stream -> Dict.t -> Dict.t = fun el_tag fields s dict -> let el_kind = element_kind_node el_tag in let dict = ref (init_children_dict fields dict) in let text_buf = Buffer.create 32 in stream_loop_children el_kind fields s text_buf dict; let text = Buffer.contents text_buf in finalize_children_dict fields text !dict and stream_loop_children : type o. string Loc.node -> o el_field list -> P.stream -> Buffer.t -> Dict.t ref -> unit = fun el_kind fields s text_buf dict -> let rec loop () = match P.next_content s with | P.End_tag -> () | P.Start_tag -> handle_child_start el_kind fields s dict; loop () | P.Text text -> Buffer.add_string text_buf text; P.count_node s; loop () | P.Misc -> loop () in loop () (* Handle a child-element start tag. *) and handle_child_start : type o. string Loc.node -> o el_field list -> P.stream -> Dict.t ref -> unit = fun el_kind fields s dict -> let st = P.parse_start_tag s in match dec_child el_kind fields st.tag st.scope { run = (fun c -> dec_stream c s st) } !dict with | Some d -> dict := d | None -> skip_unmatched_child s st (* Decode one element off the stream, start tag already read and end tag this function's to consume. A codec that delegates -- [Element], [Map], [Option], [Rec] -- hands the whole element on rather than half of it, so the end tag is read exactly once, by whichever case actually reads the body. *) and dec_stream : type a. a t -> P.stream -> P.start_tag -> a = fun c s st -> match c with | Text -> let v = if st.self_close then "" else stream_read_text s in end_element s st; v | Text_map m -> (* The span of the text run, which is what a scalar that does not parse is reported against: [m.dec] is handed the characters and could not say where they were. *) let start = P.pos s in let t = if st.self_close then "" else String.trim (stream_read_text s) in let dec = locate_span s start (fun () -> m.dec t) in end_element s st; dec | Element (el_tag, inner) -> if not (element_matches el_tag ~scope:st.scope (fst st.tag)) then err_expected_element st.tag el_tag else (* Element is a tag-check filter: it delegates, end tag and all. *) dec_stream inner s st | El (el_tag, map) -> if is_named el_tag && not (element_matches el_tag ~scope:st.scope (fst st.tag)) then err_expected_element st.tag el_tag else (* [st.tag] is the tag actually read (it is all there is when [el_tag] has no name), so it is what names the context frames. *) dec_stream_el map s st | Codec_fn fn -> (* The escape hatch's contract is the body and not the end tag: it is written against the parser and cannot know the element ends where the codec above it says it does. *) let v = fn.dec s st in end_element s st; v | Map mw -> let a = dec_stream mw.dom s st in locate_span s st.start (fun () -> mw.map_dec a) | Const v -> end_element s st; v | Option inner -> (* We're decoding an element that is already known to be present (its start tag was just parsed). "Absence" of an Option field is handled at the parent's field level ([Child_opt]); here, a decode error means the element is malformed, not absent. Swallowing it would return [None] for invalid data, which violates the absence-only semantics documented in xml.mli. *) Some (dec_stream inner s st) | Rec lz -> dec_stream (Lazy.force lz) s st | List inner -> let v = if st.self_close then [] else dec_stream_list inner s in end_element s st; v | Any -> Value.parse_element_body s st | Skip -> if not st.self_close then stream_skip_children s; end_element s st (* Decode a list of child elements directly from the stream. Each child element is decoded with the inner codec. Stops at P.stream -> a list = fun inner s -> let rec loop idx acc = match P.next_content s with | P.End_tag -> List.rev acc | P.Start_tag -> let st = P.parse_start_tag s in let v = push_array_ctx (list_kind_node st.tag) (idx, snd st.tag) (fun () -> dec_stream inner s st) in loop (idx + 1) (v :: acc) | P.Text _ | P.Misc -> loop idx acc in loop 0 [] and dec_stream_el : type o. (o, o) el_map -> P.stream -> P.start_tag -> o = fun map s st -> (* Phase 1: decode all attribute fields from the attrs list *) let dict = dec_attrs st.tag st.scope map.fields st.attrs Dict.empty in if st.self_close then begin (* Self-closing: no children to process, so every child field takes the value an empty body gives it. [] and [] are one element with no children, and the empty-body path below reaches the same dictionary through [init_children_dict] and [finalize_children_dict], so the two spellings must decode alike -- a required child is missing in both. *) let dict = empty_children_dict map.fields dict in check_required_children st.tag map.fields dict; apply_dec_fun map.dec dict end else if not map.needs_children then begin (* No child fields declared: skip all children *) stream_skip_children s; end_element s st; apply_dec_fun map.dec dict end else begin (* Phase 2: decode children directly from the stream *) let dict = dec_stream_children st.tag map.fields s dict in end_element s st; check_required_children st.tag map.fields dict; apply_dec_fun map.dec dict end (* The [fn] escape hatch is written against the byte stream, and that is its contract: it exists for codecs the combinators cannot express, and those are written in terms of the parser. Running one over a tree therefore goes through the bytes, which is what the patch operations in {!Xml.Cursor} -- the only [fn]s in this library -- do internally anyway. There is no ambient parse to inherit resource limits from here, so the nested one runs under the defaults. *) let dec_value_fn : type a. a t_fn -> Value.t -> a = fun f v -> (* [~locs:false]: the bytes being read are a rendering of the tree and not the document the tree came from, so a location into them would say a node sits where nothing was ever written. *) let s = P.make_stream_string ~locs:false (Value.to_string v) in let st = P.parse_start_tag s in let x = f.dec s st in if not st.self_close then P.consume_end_tag s (fst st.tag); x (* The second interpreter of the same GADT. [dec_stream] above reads an element off the byte stream; this one reads it off a [Value.t] the caller already holds. The two are written case for case against the same error helpers, the same context pushers and the same field dictionaries, so a codec run either way answers with the same value, fails with the same kind at the same path, and points at the same bytes: a tree parsed with locations carries on its nodes what the stream reads off its own cursor, so both runtimes have the same node to name. A tree built in the program has none, and an error against one of its nodes carries [Meta.none]. A [Value.t] cannot say whether its element was written [] or []; it does not need to, because after [dec_stream_el] the two spellings decode alike. So every case here reads an element with no children the way the stream reads a self-closing one. *) let rec dec_value : type a. a t -> Value.t -> a = fun c v -> match c with | Text -> Value.text v | Text_map m -> locate_at (Value.text_meta v) (fun () -> m.dec (String.trim (Value.text v))) | Element (el_tag, inner) -> if not (element_matches el_tag ~scope:v.scope (fst v.tag)) then err_expected_element v.tag el_tag else dec_value inner v | El (el_tag, map) -> if is_named el_tag && not (element_matches el_tag ~scope:v.scope (fst v.tag)) then err_expected_element v.tag el_tag else dec_value_el map v | Codec_fn f -> dec_value_fn f v | Map mw -> let a = dec_value mw.dom v in locate_at (Value.meta v) (fun () -> mw.map_dec a) | Const x -> x | Option inner -> Some (dec_value inner v) | Rec lz -> dec_value (Lazy.force lz) v | List inner -> dec_value_list inner v.Value.children | Any -> v | Skip -> () (* Text siblings are not list items: [dec_stream_list] steps its index on elements only, and so does this. *) and dec_value_list : type a. a t -> Value.child list -> a list = fun inner children -> let rec loop idx acc = function | [] -> List.rev acc | Value.Text _ :: rest -> loop idx acc rest | Value.Element child :: rest -> let x = push_array_ctx (list_kind_node child.Value.tag) (idx, snd child.Value.tag) (fun () -> dec_value inner child) in loop (idx + 1) (x :: acc) rest in loop 0 [] children and dec_value_el : type o. (o, o) el_map -> Value.t -> o = fun map v -> let dict = dec_attrs v.tag v.scope map.fields v.attrs Dict.empty in if not map.needs_children then apply_dec_fun map.dec dict else begin let dict = dec_value_children v.Value.tag map.fields v.Value.children dict in check_required_children v.Value.tag map.fields dict; apply_dec_fun map.dec dict end and dec_value_children : type o. string Loc.node -> o el_field list -> Value.child list -> Dict.t -> Dict.t = fun el_tag fields children dict -> let el_kind = element_kind_node el_tag in let dict = ref (init_children_dict fields dict) in let text_buf = Buffer.create 32 in List.iter (function | Value.Text (text, _) -> Buffer.add_string text_buf text | Value.Element child -> dec_value_child el_kind fields child dict) children; finalize_children_dict fields (Buffer.contents text_buf) !dict and dec_value_child : type o. string Loc.node -> o el_field list -> Value.t -> Dict.t ref -> unit = fun el_kind fields child dict -> let d = { run = (fun c -> dec_value c child) } in Option.iter (fun d -> dict := d) (dec_child el_kind fields child.Value.tag child.Value.scope d !dict) exception Attrs_outside (* An [El.finish] builder used as a whole document rather than under [element] sets its attributes on no element, and there is no XML for that. The writer finds out where the attributes would have gone -- nowhere, because no start tag is open -- and {!enc_document} names the codec in the error. *) (* -- Writing names -- Both writers spell a codec's names the same way, from the declarations in scope where they write them. An element named with no namespace is written unprefixed and is in whatever default namespace is around it, which is what the decoder reads such a name as. One named in a namespace is written unprefixed where that is the default, with a prefix bound to it where one is, and otherwise unprefixed under a declaration of the default namespace it carries. An attribute in a namespace needs a prefix, since an unprefixed one is in none: one bound in scope, or the first [nsN] that is not, declared on the tag. Each answer is a qualified name and the declaration it needs. *) let element_qname scope n = match n.ns with | None -> (n.local, None) | Some uri when String.equal (Namespace.default scope) uri -> (n.local, None) | Some uri -> ( match if uri = "" then None else Namespace.prefix_of uri scope with | Some prefix -> (prefix ^ ":" ^ n.local, None) | None -> (n.local, Some ("", uri))) let fresh_prefix scope = let rec go i = let prefix = "ns" ^ string_of_int i in if Option.is_none (Namespace.find prefix scope) then prefix else go (i + 1) in go 1 let attr_qname scope n = match n.ns with | None | Some "" -> (n.local, None) | Some uri -> ( match Namespace.prefix_of uri scope with | Some prefix -> (prefix ^ ":" ^ n.local, None) | None -> let prefix = fresh_prefix scope in (prefix ^ ":" ^ n.local, Some (prefix, uri))) let enc_declaration e = function | None -> () | Some (prefix, uri) -> enc_declare e ~prefix uri (* Opens the element [n] and answers with the qualified name it was written as, which its end tag repeats. The caller restores [e.scope] once the element is closed. *) let enc_open e n = match n.ns with | None -> (* The common case allocates nothing: a writer that streams costs the same heap per element however many it writes. *) enc_start_tag e n.local; n.local | Some _ -> let qname, decl = element_qname e.scope n in enc_start_tag e qname; enc_declaration e decl; qname (* No start tag open is an attribute with nowhere to land: see {!exception-Attrs_outside}. *) let enc_attr_here e n value = if not e.in_start_tag then raise Attrs_outside; match n.ns with | None | Some "" -> enc_attr e n.local value | Some _ -> let qname, decl = attr_qname e.scope n in enc_declaration e decl; enc_attr e qname value let enc_el_field_attr : type o. o el_field -> encoder -> o -> unit = fun field e v -> match field with | Attr (name, codec, _id, enc) -> enc_attr_here e name (codec.enc (enc v)) | Attr_opt (name, codec, _id, enc) -> ( match enc v with | None -> () | Some a -> enc_attr_here e name (codec.enc a)) | Child _ | Child_opt _ | Children _ | El_text _ -> () (* [self_wraps c] is [true] if encoding through [c] will emit its own [] opener (as [Element] and named [El] do). When the user writes [child "address" (element "address" ...)], the inner codec already owns the [
] wrapper; emitting another one around it would double- encode the tag. *) let rec self_wraps : type a. a t -> bool = function | Element _ -> true | El (tag, _) -> is_named tag | Map mw -> self_wraps mw.dom | Rec lz -> self_wraps (Lazy.force lz) | Codec_fn _ -> true | Any -> true | Text | Text_map _ | Const _ | Option _ | List _ | Skip -> false (* The layout rule needs two things about an element's children before its start tag's line break can be written: whether an element is among them, and whether a text node is. A writer that had to see them all to answer would have to hold them all, which is the whole document; these two answer from the codec's own shape and, where the shape is not enough, from the value without descending into any child. [may_elem] over-approximates: it says whether an element child is possible, not whether one is written. Over-approximating is free here, because the breaks are written before children that actually arrive and the end tag closes as [/>] when none did -- an element claimed as a block that turns out to have no children writes exactly what an inline empty element writes. Under-approximating would not be free, so a slot whose answer depends on the value counts as possible. [has_text] is exact, because it cannot be either way round: claiming text that is not there writes mixed-content rules over an element that is a block, and missing text that is there indents inside mixed content, which changes what the document says. It is exact and still bounded because text slots are shallow: a text node comes from {!Text}, {!Text_map} or an [El.text] field, and none of those is a child that has to be walked into. [may_text] keeps it off the value entirely wherever the codec settles the question, which is wherever text is not among the shapes on offer. An element is a leaf to all three: what is inside it is its own layout question, asked when the writer gets there. *) let field_may_text : type o. o el_field -> bool = function | El_text _ -> true | Attr _ | Attr_opt _ | Child _ | Child_opt _ | Children _ -> false let field_may_elem : type o. o el_field -> bool = function | Child _ | Child_opt _ | Children _ -> true | Attr _ | Attr_opt _ | El_text _ -> false let rec may_text : type a. a t -> bool = function | Text | Text_map _ -> true | Element _ | Any | Codec_fn _ | Const _ | Skip -> false | El (tag, map) -> (not (is_named tag)) && List.exists field_may_text map.fields | Map mw -> may_text mw.dom | Option inner -> may_text inner | List inner -> may_text inner | Rec lz -> may_text (Lazy.force lz) let rec may_elem : type a. a t -> bool = function | Text | Text_map _ | Const _ | Skip -> false | Element _ | Any | Codec_fn _ -> true | El (tag, map) -> is_named tag || List.exists field_may_elem map.fields | Map mw -> may_elem mw.dom | Option inner -> may_elem inner | List inner -> may_elem inner | Rec lz -> may_elem (Lazy.force lz) let rec fields_have_text : type o. o el_field list -> o -> bool = fun fields v -> match fields with | [] -> false | El_text (_id, enc) :: rest -> String.length (enc v) > 0 || fields_have_text rest v | (Attr _ | Attr_opt _ | Child _ | Child_opt _ | Children _) :: rest -> fields_have_text rest v let rec has_text : type a. a t -> a -> bool = fun c v -> match c with | Text | Text_map _ -> true | Element _ | Any | Codec_fn _ | Const _ | Skip -> false | El (tag, map) -> (not (is_named tag)) && fields_have_text map.fields v | Map mw -> may_text mw.dom && has_text mw.dom (mw.map_enc v) | Option inner -> ( match v with | None -> false | Some x -> may_text inner && has_text inner x) | Rec lz -> has_text (Lazy.force lz) v | List inner -> may_text inner && List.exists (has_text inner) v (* The escape hatch is written against the byte stream, so the tree it contributes is the one its bytes parse to: [] it wrote comes back as the element [], a comment it wrote comes back as nothing. Both runtimes bridge it the same way, and this is the one place a writer here holds more than the path it is on -- the bytes of the subtree, and then that subtree. There is no way round it: [enc] pushes bytes and nothing can be laid out until they have all been pushed. *) let fn_tree : type a. a t_fn -> a -> Value.t = fun f v -> let buf = Buffer.create 256 in let e = encoder (fun s -> Buffer.add_string buf s) in f.enc e v; (* [~meta:`None]: these bytes were written here and a moment ago, so a node of the tree they parse to was read from nowhere the caller could point at. *) Value.of_string_exn ~meta:`None (Buffer.contents buf) let rec enc_value : type a. a t -> encoder -> a -> unit = fun c e v -> match c with | Text -> enc_text e v | Text_map m -> enc_text e (m.enc v) | Element (tag, inner) -> enc_element e tag inner v | El (tag, map) -> enc_el tag map e v | Codec_fn f -> enc_subtree e (fn_tree f v) | Map mw -> enc_value mw.dom e (mw.map_enc v) | Const _ -> () | Option inner -> ( match v with Some x -> enc_value inner e x | None -> ()) | Rec lz -> enc_value (Lazy.force lz) e v | List inner -> enc_items inner e v | Any -> enc_subtree e v | Skip -> () (* The list walks below are written out rather than reached through [List.iter] because the closure [List.iter] wants is one closure per element, and a writer that streams should cost the same heap for a document of any size. *) and enc_items : type a. a t -> encoder -> a list -> unit = fun inner e items -> match items with | [] -> () | item :: rest -> enc_value inner e item; enc_items inner e rest (* One [...] boundary with [content] inside it. The layout answer is settled here, before the start tag is closed, and the parent's is kept in two locals for the duration -- which is the whole of what nesting costs. *) and enc_element : type a. encoder -> name -> a t -> a -> unit = fun e name content v -> let parent_scope = e.scope in let tag = enc_open e name in let parent_block = e.block and parent_depth = e.depth in let block = parent_block && may_elem content && not (has_text content v) in e.block <- block; e.depth <- parent_depth + 1; enc_value content e v; enc_close_element e ~block ~parent_block ~parent_depth tag; e.scope <- parent_scope and enc_el : type o. name -> (o, o) el_map -> encoder -> o -> unit = fun name map e v -> if not (is_named name) then begin (* Bare El from El.finish (no element wrapper) -- just encode attrs and children into the current (already open) element *) enc_field_attrs e v map.fields; enc_field_children e v map.fields end else begin let parent_scope = e.scope in let tag = enc_open e name in (* Phase 1: write all attributes (start tag is still open) *) enc_field_attrs e v map.fields; (* Phase 2: write all children (will close start tag on first write) *) let parent_block = e.block and parent_depth = e.depth in let block = parent_block && List.exists field_may_elem map.fields && not (fields_have_text map.fields v) in e.block <- block; e.depth <- parent_depth + 1; enc_field_children e v map.fields; enc_close_element e ~block ~parent_block ~parent_depth tag; e.scope <- parent_scope end and enc_field_attrs : type o. encoder -> o -> o el_field list -> unit = fun e v fields -> match fields with | [] -> () | field :: rest -> enc_el_field_attr field e v; enc_field_attrs e v rest and enc_field_children : type o. encoder -> o -> o el_field list -> unit = fun e v fields -> match fields with | [] -> () | field :: rest -> enc_el_field_child field e v; enc_field_children e v rest (* A subtree the writer already holds, placed where it has got to. The tree writer takes it from here, through the same encoder. *) and enc_subtree : encoder -> Value.t -> unit = fun e el -> Value.write_node e (Value.Element el) and enc_child_run : type a. encoder -> name -> a t -> a list -> unit = fun e tag inner children -> match children with | [] -> () | child_v :: rest -> enc_child_wrap e tag inner child_v; enc_child_run e tag inner rest and enc_child_wrap : type a. encoder -> name -> a t -> a -> unit = fun e tag inner child_v -> (* Emit one [...] boundary around [inner]'s payload, unless [inner] already wraps itself in a (usually matching) tag -- then let it own the boundary. *) if self_wraps inner then enc_value inner e child_v else enc_element e tag inner child_v and enc_el_field_child : type o. o el_field -> encoder -> o -> unit = fun field e v -> match field with | Attr _ | Attr_opt _ -> () | Child (tag, inner, _id, enc) -> enc_child_wrap e tag inner (enc v) | Child_opt (tag, inner, _id, enc) -> ( match enc v with | None -> () | Some child_v -> enc_child_wrap e tag inner child_v) | Children (tag, inner, _id, enc) -> enc_child_run e tag inner (enc v) | El_text (_id, enc) -> let s = enc v in if String.length s > 0 then enc_text e s (* What encoding a codec contributes to the element that encloses it: the attributes it sets on that element, and the nodes it appends to its content. It is the tree-shaped reading of [Core.encoder]'s [in_start_tag] flag, which is how [enc_value] keeps the two apart while writing bytes. The nodes wait for the scope they are put in. How an element's name is written, and so the scope its children are in, depends on the declarations around it, and those are only known once the element it is appended to has settled its own name and attributes: the attributes are named and the nodes are a function, which the element hands its scope to. *) type contrib = { attrs : (name * string) list; nodes : Namespace.t -> Value.child list; } let no_nodes (_ : Namespace.t) = [] let contrib_none = { attrs = []; nodes = no_nodes } let contrib_nodes nodes = { attrs = []; nodes } let contrib_attr name value = { name = (name, Meta.none); value = (value, Meta.none) } let declaration_attr (prefix, uri) = contrib_attr (if prefix = "" then "xmlns" else "xmlns:" ^ prefix) uri (* Encoding builds a tree the program means and not one a document wrote, so every node of it is unlocated. *) let unlocated_element ~qname ~attrs ~scope children : Value.t = { tag = (qname, Meta.none); attrs; scope; children; meta = Meta.none } (* The element [n] holding [c], in [parent]'s scope. Its names are spelled as {!enc_open} and {!enc_attr_here} spell them, declarations in the same order, so the tree and the bytes are one document. *) let contrib_declared_element parent n (c : contrib) = let qname, decl = element_qname parent n in let declare (scope, acc) = function | None -> (scope, acc) | Some (prefix, uri) -> (Namespace.add ~prefix uri scope, declaration_attr (prefix, uri) :: acc) in let scope, acc = declare (parent, []) decl in let scope, acc = List.fold_left (fun (scope, acc) (an, value) -> let q, decl = attr_qname scope an in let scope, acc = declare (scope, acc) decl in (scope, contrib_attr q value :: acc)) (scope, acc) c.attrs in unlocated_element ~qname ~attrs:(List.rev acc) ~scope (c.nodes scope) let contrib_element parent n (c : contrib) = match (n.ns, c.attrs) with | None, [] -> (* No name to declare and no attribute: the element is in its parent's scope, and costs the node it is. *) unlocated_element ~qname:n.local ~attrs:[] ~scope:parent (c.nodes parent) | _ -> contrib_declared_element parent n c let enc_contrib_attr : type o. o el_field -> o -> (name * string) list = fun field v -> match field with | Attr (name, codec, _id, enc) -> [ (name, codec.enc (enc v)) ] | Attr_opt (name, codec, _id, enc) -> ( match enc v with None -> [] | Some a -> [ (name, codec.enc a) ]) | Child _ | Child_opt _ | Children _ | El_text _ -> [] let concat_nodes parts scope = List.concat_map (fun f -> f scope) parts let rec enc_contrib : type a. a t -> a -> contrib = fun c v -> match c with | Text -> contrib_nodes (fun _ -> [ Value.Text (v, Meta.none) ]) | Text_map m -> let text = m.enc v in contrib_nodes (fun _ -> [ Value.Text (text, Meta.none) ]) | Element (name, inner) -> let c = enc_contrib inner v in contrib_nodes (fun scope -> [ Value.Element (contrib_element scope name c) ]) | El (name, map) -> enc_contrib_el name map v | Codec_fn f -> let tree = fn_tree f v in contrib_nodes (fun _ -> [ Value.Element tree ]) | Map mw -> enc_contrib mw.dom (mw.map_enc v) | Const _ -> contrib_none | Option inner -> ( match v with Some x -> enc_contrib inner x | None -> contrib_none) | Rec lz -> enc_contrib (Lazy.force lz) v | List inner -> (* Each item once, and each part concatenated once: appending the accumulator to itself per item copies the whole run each time, so a list of n items costs sum(k = 1 to n) cells, 12n^2 bytes on a 64-bit word, which is 3 GB for a run of sixteen thousand. *) let parts = List.map (enc_contrib inner) v in { attrs = List.concat_map (fun (c : contrib) -> c.attrs) parts; nodes = concat_nodes (List.map (fun (c : contrib) -> c.nodes) parts); } | Any -> contrib_nodes (fun _ -> [ Value.Element v ]) | Skip -> contrib_none and enc_contrib_el : type o. name -> (o, o) el_map -> o -> contrib = fun name map v -> let c = { attrs = List.concat_map (fun f -> enc_contrib_attr f v) map.fields; nodes = concat_nodes (List.map (fun f -> enc_contrib_child f v) map.fields); } in (* An [El.finish] with no name has no element of its own: its attributes and children land on whatever element encloses it. *) if not (is_named name) then c else contrib_nodes (fun scope -> [ Value.Element (contrib_element scope name c) ]) and enc_contrib_child : type o. o el_field -> o -> Namespace.t -> Value.child list = fun field v -> match field with | Attr _ | Attr_opt _ -> no_nodes | Child (name, inner, _id, enc) -> let node = enc_child_node name inner (enc v) in fun scope -> [ node scope ] | Child_opt (name, inner, _id, enc) -> ( match enc v with | None -> no_nodes | Some x -> let node = enc_child_node name inner x in fun scope -> [ node scope ]) | Children (name, inner, _id, enc) -> let nodes = List.map (enc_child_node name inner) (enc v) in fun scope -> List.map (fun node -> node scope) nodes | El_text (_id, enc) -> let text = enc v in if String.length text = 0 then no_nodes else fun _ -> [ Value.Text (text, Meta.none) ] (* One [...] boundary around [inner]'s payload, unless [inner] already wraps itself in a (usually matching) tag -- then it owns the boundary. [enc_child_wrap] makes the same call while writing bytes. *) and enc_child_node : type a. name -> a t -> a -> Namespace.t -> Value.child = fun name inner x -> let c = enc_contrib inner x in fun scope -> match (c.attrs, self_wraps inner) with | [], true -> ( match c.nodes scope with | [ (Value.Element _ as node) ] -> node | _ -> Value.Element (contrib_element scope name c)) | _ -> Value.Element (contrib_element scope name c) let string : string t = Text (* A text codec is handed the characters and nothing else, so it raises with no place of its own; both interpreters run it under a wrapper that gives the error the span the characters were read from. *) let err_text exp = Error.kinded_sort meta_none ~exp ~fnd:Sort.Text let scalar kind exp of_string enc = Text_map { kind; dec = (fun s -> match of_string s with Some v -> v | None -> err_text exp); enc; } let int : int t = scalar "int" "integer" int_of_string_opt string_of_int let float : float t = scalar "float" "float" float_of_string_opt string_of_float let bool : bool t = scalar "bool" "boolean" bool_of_string_ci string_of_bool (* A codec names a local part, never a qualified name: the prefix is the document's to choose. [xmlns] names no attribute, only the declarations the writers make themselves. *) let element_name fn ?ns local = if not (Name.is_ncname local) then Fmt.invalid_arg "Xml.Codec.%s: %S is not a local name" fn local; { ns; local } let attr_name fn ?ns local = if local = "xmlns" && (ns = None || ns = Some "") then Fmt.invalid_arg "Xml.Codec.%s: xmlns is a namespace declaration, not an attribute" fn; element_name fn ?ns local module El = struct (* Snapshot the outer codec type before [t] is redefined below so the builder API can still reference it. *) type 'a codec = 'a t type ('o, 'dec) t = { dec : ('o, 'dec) dec_fun; fields : 'o el_field list; (* in reverse order, reversed at finish *) needs_children : bool; } let obj dec = { dec = Fun dec; fields = []; needs_children = false } (* [needs_children] is whether the field is read from the element's body, which the decoder skips when no field is. *) let field ~needs_children mk builder = let id = Type.Id.make () in { dec = App (builder.dec, id); fields = mk id :: builder.fields; needs_children = needs_children || builder.needs_children; } let attr ?ns local (codec : 'a Attr.t) ~enc builder = let name = attr_name "El.attr" ?ns local in field ~needs_children:false (fun id -> Attr (name, codec, id, enc)) builder let attr_opt ?ns local (codec : 'a Attr.t) ~enc builder = let name = attr_name "El.attr_opt" ?ns local in field ~needs_children:false (fun id -> Attr_opt (name, codec, id, enc)) builder let child ?ns local (inner : 'a codec) ~enc builder = let name = element_name "El.child" ?ns local in field ~needs_children:true (fun id -> Child (name, inner, id, enc)) builder let child_opt ?ns local (inner : 'a codec) ~enc builder = let name = element_name "El.child_opt" ?ns local in field ~needs_children:true (fun id -> Child_opt (name, inner, id, enc)) builder let children ?ns local (inner : 'a codec) ~enc builder = let name = element_name "El.children" ?ns local in field ~needs_children:true (fun id -> Children (name, inner, id, enc)) builder let text ~enc builder = field ~needs_children:true (fun id -> El_text (id, enc)) builder let finish (builder : ('o, 'o) t) : 'o codec = El ( no_name, { dec = builder.dec; fields = List.rev builder.fields; needs_children = builder.needs_children; } ) end let element ?ns local codec = let name = element_name "element" ?ns local in match codec with | El (n, map) when not (is_named n) -> (* El.finish produced this with no name of its own *) El (name, map) | _ -> (* Wrap any codec in a named element: [element "foo" string] is [Element (foo, Text)], decoded and encoded by the interpreter as a name check and a delegation to the inner codec. *) Element (name, codec) let rec kind : type a. a t -> string = function | Text -> "string" | Text_map m -> m.kind | Element (tag, inner) -> "element <" ^ name_string tag ^ "> of " ^ kind inner | El (tag, _) -> if is_named tag then "element <" ^ name_string tag ^ ">" else "element" | Codec_fn fn -> fn.kind | Map mw -> kind mw.dom | Const _ -> "constant" | Option inner -> "optional " ^ kind inner | Rec lz -> kind (Lazy.force lz) | List inner -> "list of " ^ kind inner | Any -> "any element" | Skip -> "skip" let map ?dec ?enc codec = let map_dec = match dec with | Some f -> f | None -> fun _ -> Error.no_decoder meta_none ~kind:(kind codec) in let map_enc = match enc with | Some f -> f | None -> fun _ -> Error.no_encoder meta_none ~kind:(kind codec) in Map { dom = codec; map_dec; map_enc } let const v = Const v let option codec = Option codec let list codec = List codec let fix lz = Rec lz let decode_stream codec s = P.skip_preamble s; if P.at_end s then err_msg_at (P.loc s) "empty document: no root element"; let v = dec_stream codec s (P.parse_start_tag s) in P.skip_trailing_misc s; v (* Check whether the parse stream encountered malformed UTF-8 while refilling. XML 1.0 section 4.3.3 requires UTF-8 well-formedness as a document-level precondition. Call after a successful parse so that otherwise-valid structural output doesn't mask a UTF-8 error. *) let check_stream_utf8 s = match P.utf8_error s with | Some i -> Loc.Error.failf meta_none "malformed UTF-8 at byte offset %d" i | None -> () let child ?ns local c = (* Build an El with a single required child field that extracts the child named [local] and decodes it with c. The El has no name of its own, so it matches any outer element. *) let name = element_name "child" ?ns local in let id = Type.Id.make () in El ( no_name, { dec = App (Fun Fun.id, id); fields = [ Child (name, c, id, Fun.id) ]; needs_children = true; } ) let attr ?ns local = (* Build an El with a single required attribute field *) let name = attr_name "attr" ?ns local in let id = Type.Id.make () in El ( no_name, { dec = App (Fun Fun.id, id); fields = [ Attr (name, Attr.string, id, Fun.id) ]; needs_children = false; } ) let nth n c = (* Map over a List codec that extracts the nth child element *) Map { dom = List c; map_dec = (fun items -> match List.nth_opt items n with | Some v -> v | None -> Error.index_out_of_range meta_none ~n ~len:(List.length items)); map_enc = (fun v -> [ v ]); } let pp ppf c = Fmt.string ppf (kind c) (* [fn] wraps a hand-written decode/encode pair as a codec -- the escape hatch behind the identity codec [value], [skip], and Cursor's patch operations. *) let fn f = Codec_fn f (* The identity codec: decode any XML document into a [Value.t] and encode any [Value.t] back out. It ties [Value.t] to the codec GADT, so it lives in the codec layer (codec -> value), not in the base [value.ml]. It is a constructor rather than a [fn] so that both interpreters can be exact: the tree runtime hands the value straight back instead of serialising it and parsing it again, which would merge adjacent text nodes. *) let value : Value.t t = Any (* [skip] decodes any element to [()] while discarding its body. Use it inside [list]/[El.child_opt]/[El.children] to filter an element type out of a large document without materializing the skipped subtree. It is the one shape that is genuinely stream-level -- byte-skipping is the whole point of it -- so it is a constructor and not a [fn]. *) let skip : unit t = Skip let decode_exn c v = dec_value c v let decode c v = match dec_value c v with x -> Ok x | exception Loc.Error e -> Error e (* The node sequence a codec writes. It is a sequence and not one element because a run of siblings and bare text are both legal codec output -- [list] writes the first and [string] the second -- and {!Xml.to_string} writes either. Attributes are the one contribution with nowhere to land: an [El.finish] builder used as a whole document rather than under [element] sets them on no element, and there is no XML for that. *) let encode_nodes : type a. a t -> a -> Value.child list = fun c v -> match enc_contrib c v with | { attrs = []; nodes } -> nodes Namespace.empty | { attrs = _ :: _; _ } -> Fmt.kstr err_msg "%s sets attributes outside an element" (kind c) let encode : type a. a t -> a -> Value.t = fun c v -> let nodes = match enc_contrib c v with | { attrs = []; nodes } -> nodes Namespace.empty | { attrs = _ :: _; _ } -> [] in match nodes with | [ Value.Element el ] -> el | [ Value.Text _ ] -> (* Bare text is legal codec output -- it is what [to_string] writes for [string] -- and it is not an element, which [Value.t] is. The two sorts are the whole of what is wrong, and there is no document to point into: the value came from the program. *) Error.sort meta_none ~exp:Sort.Element ~fnd:Sort.Text | _ -> (* A run of siblings is legal output too, and so is nothing at all. Saying so beats inventing a wrapper tag the codec never named. *) Fmt.kstr err_msg "%s does not encode to a single element" (kind c) (* The document: the top-level run of nodes a codec writes. It follows the same rule with no enclosing tag to indent against, so the break goes after each node rather than before it, and a document laid out at all ends in one newline. *) let enc_document : type a. a t -> encoder -> a -> unit = fun c e v -> e.block <- e.indent > 0 && may_elem c && not (has_text c v); (try enc_value c e v with Attrs_outside -> Fmt.kstr err_msg "%s sets attributes outside an element" (kind c)); enc_end_document e