Skip to main content

sup_xml_tree/
dom.rs

1//! Bumpalo-backed, libxml2-shaped DOM.
2//!
3//! This is the v2 tree representation that replaces the per-node-`malloc`
4//! design in [`crate::node`].  It's not wired into the parser yet — that
5//! happens in Milestone 2.  Until then, the rest of the codebase keeps using
6//! the existing [`crate::node`] types unchanged.
7//!
8//! # Design
9//!
10//! * **One arena per document.**  A [`bumpalo::Bump`] owns all node, attribute,
11//!   namespace, and string allocations.  Per-node alloc cost drops to a
12//!   pointer bump; drop is free per node — the whole arena is freed at once.
13//!
14//! * **libxml2-shaped nodes.**  A single [`Node`] struct (not a Rust enum)
15//!   with a [`NodeKind`] tag and inline fields for every variant.  Children
16//!   form a doubly-linked list via `first_child`/`last_child` on the parent
17//!   and `next_sibling`/`prev_sibling` + `parent` on each child.  Attributes
18//!   form their own doubly-linked list on the element.  Field offsets and
19//!   semantics mirror `xmlNode` so a future `extern "C"` shim can expose the
20//!   same memory to libxml2 callers verbatim.
21//!
22//! * **Cell-of-references for links.**  All sibling/child/parent pointers
23//!   are `Cell<Option<&'doc Node<'doc>>>`.  This is the standard idiomatic
24//!   pattern for graph-shaped data in an arena: you get mutation without
25//!   `RefCell` overhead and without raw pointers in the public API.
26//!
27//! * **Strings borrowed where possible.**  Names and text contents are
28//!   `&'doc str`.  When the parser can borrow from the source slice
29//!   directly it does; otherwise it allocates a copy in the arena.  No
30//!   `Arc<str>` per name.
31//!
32//! # The self-referential `Document` wrapper
33//!
34//! [`Document`] owns a `Bump` *and* holds a root pointer (`&Node`) into that
35//! same `Bump`.  That's a self-referential struct, which safe Rust doesn't
36//! express directly.  The arena nodes have stable addresses (bumpalo never
37//! relocates allocations), so the references are sound in principle.  We
38//! encode it with one contained `unsafe` block in [`Document::root`], audited by:
39//!
40//! 1. The `Bump` is stored in an `Arc<Bump>` — heap-allocated, never
41//!    moved while any clone of the Arc lives.  C-ABI consumers
42//!    (`sup-xml-compat`) share a single thread-local arena across
43//!    every document, so cross-doc node grafts (libxml2 consumers
44//!    like lxml moving nodes between documents) are safe by
45//!    construction — node memory outlives any individual doc.
46//! 2. The root pointer is built from `&Bump::alloc(...)` of the same `Bump`,
47//!    so the lifetime is genuinely `'self` (as in: tied to the `Document`).
48//! 3. The `Document`'s public methods hand out references with a borrow of
49//!    `&self`, which the borrow checker treats as `'self`-bounded.  Outside
50//!    those methods, no `'doc` reference can escape.
51//!
52//! See [`Document`] for the API.
53
54#![allow(unsafe_code)]  // see module docs § "self-referential Document wrapper"
55
56use std::cell::{Cell, RefCell};
57use std::sync::Arc;
58
59use bumpalo::Bump;
60
61// ── HTML metadata ────────────────────────────────────────────────────────────
62
63/// HTML5 quirks-mode flag set from the DOCTYPE.  Only meaningful for HTML
64/// documents; XML documents always carry `None` for `Document::html_metadata`.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum QuirksMode {
67    NoQuirks,
68    LimitedQuirks,
69    Quirks,
70}
71
72/// Captured DOCTYPE content from an HTML document.  Stored verbatim; HTML5 does
73/// not validate against DTDs, but the public/system identifiers are surfaced
74/// for tools that want to introspect them (e.g. detecting XHTML vs HTML5 input).
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct HtmlDoctype {
77    pub name: String,
78    pub public_id: String,
79    pub system_id: String,
80}
81
82/// HTML-specific document metadata.  Set when the document came from
83/// `parse_html_*`; `None` for XML documents.
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct HtmlMeta {
86    pub quirks_mode: QuirksMode,
87    pub doctype: Option<HtmlDoctype>,
88}
89
90// ── node kinds ──────────────────────────────────────────────────────────────
91
92/// Discriminant for [`Node::kind`].
93///
94/// `#[repr(u32)]` chosen to match libxml2's `xmlElementType` numeric layout —
95/// the future `extern "C"` shim can transmute / cast directly.  Variant values
96/// are pinned to libxml2's enum order; do not reorder without a coordinated
97/// ABI update.
98#[repr(u32)]
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
100pub enum NodeKind {
101    /// `<element>...</element>`.
102    Element = 1,
103    /// An attribute.  Only used as the `kind` of an
104    /// [`Attribute`](crate::dom::Attribute) under the `c-abi` feature
105    /// — never appears on a real [`Node`]; the libxml2 ABI requires
106    /// xmlAttr's `type` field at offset 8 to carry this discriminant
107    /// so generic walkers casting `xmlAttr*` to `xmlNode*` see the
108    /// right type.
109    Attribute = 2,
110    /// Character data between tags.  `content` holds the (entity-expanded) text.
111    Text    = 3,
112    /// `<![CDATA[…]]>`.  Preserved as a distinct kind for round-trip serialization.
113    CData   = 4,
114    /// An unresolved entity reference — `&name;` left literal in the
115    /// tree.  Emitted only when the parser is configured with
116    /// `resolve_entities: false`; the default expands entity
117    /// references inline.  `name` holds the entity name (e.g.
118    /// `"foo"` for `&foo;`); `content` holds the literal source
119    /// form `"&foo;"` so serialization round-trips by writing
120    /// `content` verbatim, and lxml-compat code can return
121    /// `node.text == "&foo;"`.
122    ///
123    /// libxml2's enum value for `XML_ENTITY_REF_NODE` is 5 —
124    /// pinned here so generic walkers see the right tag.
125    EntityRef = 5,
126    /// `<!-- … -->`.
127    Comment = 8,
128    /// `<?target content?>`.
129    Pi      = 7,
130    /// The document root.  Only used as the `kind` of an
131    /// [`XmlDoc`](crate::dom::XmlDoc) under the `c-abi` feature — never
132    /// appears on a real [`Node`].  libxml2's enum value for
133    /// `XML_DOCUMENT_NODE` is 9.
134    Document = 9,
135    /// A detached subtree root with no semantic content of its own —
136    /// just a parent for an ordered list of child nodes.  Returned by
137    /// `xmlNewDocFragment` and used by callers that want to build a
138    /// composite subtree before grafting it into a real document.
139    ///
140    /// libxml2's enum value for `XML_DOCUMENT_FRAG_NODE` is 11.
141    DocumentFragment = 11,
142    /// The DOCTYPE internal-subset node itself (`XML_DTD_NODE` = 14).
143    /// Never allocated in the arena — sup-xml models the DTD through
144    /// the compat shim's 128-byte `xmlDtd` struct, which shares the
145    /// node header (`kind@8`, `children@24`, `parent@40`, `next@48`,
146    /// `prev@56`, `doc@64`) with [`Node`].  The shim splices that
147    /// struct into the document's sibling chain at the DOCTYPE's true
148    /// position; reinterpreted as a `Node` it reports this kind, so
149    /// every tree walker traverses past it as an inert node (it emits
150    /// no markup of its own — lxml serializes the subset via
151    /// `doc->intSubset` directly).
152    Dtd = 14,
153    /// A document-type internal-subset declaration block (`<!ENTITY …>`,
154    /// `<!ELEMENT …>`, `<!ATTLIST …>`, …).  Held as the single child of
155    /// the internal-subset DTD node; `content` carries the raw markup
156    /// declarations (each terminated by a newline) verbatim, which the
157    /// serializer emits unescaped inside the DOCTYPE's `[ … ]`.  The
158    /// discriminant sits in libxml2's declaration-type range
159    /// (`XML_ELEMENT_DECL` = 15) so generic walkers treat it as a DTD
160    /// declaration; sup-xml does not model per-declaration nodes.
161    DtdDecl = 15,
162}
163
164// ── core types ──────────────────────────────────────────────────────────────
165
166/// Thin NUL-terminated UTF-8 pointer with arena lifetime — c-abi-only.
167///
168/// Used in the [`Node`] / [`Attribute`] / [`Namespace`] structs under
169/// the `c-abi` feature to match libxml2's `xmlChar*` (8-byte thin
170/// pointer to NUL-terminated UTF-8) at fixed byte offsets.  On the
171/// lean (default) build these fields are `&'doc str` (16 bytes —
172/// ptr + len); `ArenaCStr` is the 8-byte alternative used when the
173/// libxml2 ABI window applies.
174///
175/// Callers reach the bytes via [`as_ptr`](Self::as_ptr) (for C FFI —
176/// cast to `*const xmlChar`) or [`as_str`](Self::as_str) (for Rust
177/// — does a strlen + `from_utf8_unchecked`).
178///
179/// Builder discipline guarantees the trailing `\0` and that the
180/// bytes are valid UTF-8.
181#[cfg(feature = "c-abi")]
182#[repr(transparent)]
183#[derive(Copy, Clone)]
184pub struct ArenaCStr<'doc> {
185    /// Non-null because libxml2's `xmlChar*` slots use `NULL` to mean
186    /// "absent" — we model the absent case explicitly with
187    /// `Option<ArenaCStr>` and rely on the niche-optimization here to
188    /// keep `Option<ArenaCStr>` 8 bytes wide (matches `xmlChar*` slot
189    /// width in `_xmlNs` etc.).
190    ptr: std::ptr::NonNull<u8>,
191    _marker: std::marker::PhantomData<&'doc u8>,
192}
193
194#[cfg(feature = "c-abi")]
195impl<'doc> ArenaCStr<'doc> {
196    /// Construct from a raw pointer.  Caller asserts NUL-terminated
197    /// UTF-8 with at least `'doc` lifetime AND non-null.  Use
198    /// [`empty`](Self::empty) when "absent" is the intent.
199    ///
200    /// # Safety
201    /// The pointed-to byte array must be NUL-terminated UTF-8 valid
202    /// for the entire `'doc` lifetime, and `ptr` must be non-null.
203    #[inline]
204    pub unsafe fn from_raw(ptr: *const u8) -> Self {
205        debug_assert!(!ptr.is_null(), "ArenaCStr::from_raw given NULL");
206        // SAFETY: caller asserts non-null.
207        Self {
208            ptr: unsafe { std::ptr::NonNull::new_unchecked(ptr as *mut u8) },
209            _marker: std::marker::PhantomData,
210        }
211    }
212
213    /// Raw pointer suitable for C FFI as `*const xmlChar`.
214    #[inline]
215    pub fn as_ptr(&self) -> *const u8 { self.ptr.as_ptr() }
216
217    /// Decode to `&'doc str`.  Does a strlen scan; bytes are
218    /// guaranteed valid UTF-8 by builder discipline.
219    pub fn as_str(&self) -> &'doc str {
220        // SAFETY: builder allocates with trailing `\0`; bytes are UTF-8.
221        unsafe {
222            let cstr = std::ffi::CStr::from_ptr(self.ptr.as_ptr() as *const std::os::raw::c_char);
223            std::str::from_utf8_unchecked(cstr.to_bytes())
224        }
225    }
226
227    /// Empty-string singleton — points at a static NUL byte.
228    /// Used for "this kind of node doesn't have a name/content"
229    /// initialization without a per-instance allocation.
230    pub fn empty() -> Self {
231        static EMPTY: u8 = 0;
232        Self {
233            ptr: std::ptr::NonNull::from(&EMPTY),
234            _marker: std::marker::PhantomData,
235        }
236    }
237
238    /// Construct from the address of `xmlStringText` — the static
239    /// `"text\0"` exported as a libxml2-ABI symbol.  libxslt's
240    /// `xsltCopyText` and similar helpers compare `node->name`
241    /// against `xmlStringText` *by pointer* to identify text nodes,
242    /// so every Text node we create must point at this exact byte.
243    #[inline]
244    pub fn text_name() -> Self {
245        // SAFETY: xml_string_text() returns the address of a
246        // 'static byte array that's NUL-terminated.
247        unsafe { Self::from_raw(xml_string_text()) }
248    }
249
250    /// Construct from the address of `xmlStringTextNoenc` — the
251    /// disable-output-escaping marker.  Same pointer-equality
252    /// contract as `text_name`.
253    #[inline]
254    pub fn text_noenc_name() -> Self {
255        unsafe { Self::from_raw(xml_string_text_noenc()) }
256    }
257}
258
259/// libxml2's `xmlStringText` — exported as a C symbol so callers
260/// (libxslt, lxml) that test `node->name == xmlStringText` by
261/// pointer get the canonical address.  Defined in tree (rather than
262/// compat) so the tree builder can reach it when constructing text
263/// nodes without a dependency cycle.
264#[cfg(feature = "c-abi")]
265#[unsafe(no_mangle)]
266pub static xmlStringText: [u8; 5] = *b"text\0";
267
268/// Sibling of `xmlStringText`, for text nodes with
269/// `disable-output-escaping="yes"`.
270#[cfg(feature = "c-abi")]
271#[unsafe(no_mangle)]
272pub static xmlStringTextNoenc: [u8; 10] = *b"textnoenc\0";
273
274/// Address of `xmlStringText` for in-crate use.
275#[cfg(feature = "c-abi")]
276#[inline]
277fn xml_string_text() -> *const u8 { (&xmlStringText) as *const _ as *const u8 }
278
279#[cfg(feature = "c-abi")]
280#[inline]
281fn xml_string_text_noenc() -> *const u8 { (&xmlStringTextNoenc) as *const _ as *const u8 }
282
283#[cfg(feature = "c-abi")]
284impl std::fmt::Debug for ArenaCStr<'_> {
285    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
286        write!(f, "{:?}", self.as_str())
287    }
288}
289
290/// A namespace binding (`prefix → href`).  Lifetime-bound to the document's arena.
291///
292/// `prefix` is `None` for the default namespace (`xmlns="…"`).
293///
294/// # Layout
295/// On the lean (default) build, `prefix` and `href` are `&'doc str`
296/// (fat slice).  Under the `c-abi` feature this struct is byte-exact
297/// with libxml2's `_xmlNs` as verified against libxml2 2.9.13 and
298/// 2.15.3.  We do not claim layout compatibility with libxml2
299/// versions we have not verified against; the `t-upstream-layout`
300/// c-test fails the build when the installed libxml2 header
301/// disagrees with the offsets here:
302///
303/// ```text
304/// _xmlNs (64-bit), the odd duck among libxml2 structs because
305/// `next` precedes `_private`:
306///   xmlNs         *next;            // offset  0   (chain pointer)
307///   xmlNsType      type;            // offset  8   (XML_LOCAL_NAMESPACE = 18)
308///   const xmlChar *href;            // offset 16
309///   const xmlChar *prefix;          // offset 24
310///   void          *_private;        // offset 32
311///   xmlDoc        *context;         // offset 40
312///   // sizeof == 48
313/// ```
314///
315/// We populate `next` via [`DocumentBuilder::append_ns_def`] so
316/// `xmlSearchNs` can walk the per-element ns_def chain.  `_private`
317/// and `context` are zero-initialized; we don't use them but the
318/// slots have to exist for ABI compatibility.
319#[cfg(not(feature = "c-abi"))]
320#[repr(C)]
321#[derive(Debug)]
322pub struct Namespace<'doc> {
323    pub prefix: Option<&'doc str>,
324    pub href:   &'doc str,
325}
326
327#[cfg(feature = "c-abi")]
328#[repr(C)]
329pub struct Namespace<'doc> {
330    /// Next namespace declaration on the same element (chain head
331    /// rooted at `Node::ns_def`).
332    pub next:     Cell<Option<&'doc Namespace<'doc>>>,     //   0
333    /// libxml2's `xmlNsType`.  Always `XML_LOCAL_NAMESPACE = 18`
334    /// for the only kind of namespace record we produce.
335    pub kind:     i32,                                          //   8
336    _pad_kind:    i32,                                          //  12
337    pub href:     ArenaCStr<'doc>,                            //  16
338    pub prefix:   Option<ArenaCStr<'doc>>,                    //  24
339    pub _private: Cell<*mut std::os::raw::c_void>,             //  32
340    pub context:  Cell<*mut std::os::raw::c_void>,             //  40 (xmlDoc*)
341}
342
343#[cfg(feature = "c-abi")]
344impl std::fmt::Debug for Namespace<'_> {
345    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
346        f.debug_struct("Namespace")
347            .field("prefix", &self.prefix.map(|p| p.as_str()))
348            .field("href",   &self.href.as_str())
349            .finish()
350    }
351}
352
353impl<'doc> Namespace<'doc> {
354    /// Namespace prefix (`"xlink"`, etc.), or `None` for the default
355    /// namespace declaration (`xmlns="..."`).
356    ///
357    /// **Prefer this method over direct `ns.prefix` field access.**
358    /// On the lean rlib build it just returns the field; on the
359    /// `c-abi` build the storage type changes to a thin
360    /// NUL-terminated `ArenaCStr` and this method handles the
361    /// conversion.
362    #[inline]
363    pub fn prefix(&self) -> Option<&'doc str> {
364        #[cfg(not(feature = "c-abi"))]
365        { self.prefix }
366        #[cfg(feature = "c-abi")]
367        { self.prefix.map(|p| p.as_str()) }
368    }
369
370    /// Namespace URI (the right-hand side of `xmlns="..."`).  Same
371    /// rationale as [`prefix`](Self::prefix) for preferring this
372    /// over direct field access.
373    #[inline]
374    pub fn href(&self) -> &'doc str {
375        #[cfg(not(feature = "c-abi"))]
376        { self.href }
377        #[cfg(feature = "c-abi")]
378        { self.href.as_str() }
379    }
380}
381
382/// An attribute on an element.  Belongs to a doubly-linked list rooted at
383/// [`Node::first_attribute`] / [`Node::last_attribute`] on its owning element.
384///
385/// # Layout
386/// libxml2's `_xmlAttr` shares its first 8 fields with `_xmlNode`:
387/// generic walkers cast `xmlAttr*` to `xmlNode*` and read `.type` /
388/// `.name`.  Under the `c-abi` feature this struct's layout matches
389/// `_xmlAttr` byte-exact.
390///
391/// ```text
392/// libxml2 _xmlAttr (64-bit):
393///   void           *_private;     // offset  0
394///   xmlElementType  type;         // offset  8   (XML_ATTRIBUTE_NODE = 2)
395///   const xmlChar  *name;         // offset 16
396///   xmlNode        *children;     // offset 24   (text/entity content nodes)
397///   xmlNode        *last;         // offset 32
398///   xmlNode        *parent;       // offset 40   (the element)
399///   xmlAttr        *next;         // offset 48
400///   xmlAttr        *prev;         // offset 56
401///   xmlDoc         *doc;          // offset 64
402///   xmlNs          *ns;           // offset 72
403///   xmlAttributeType atype;       // offset 80   (DTD type info)
404///   void           *psvi;         // offset 88
405///   ...
406/// ```
407#[cfg(not(feature = "c-abi"))]
408#[repr(C)]
409pub struct Attribute<'doc> {
410    pub name:      &'doc str,
411    pub namespace: Cell<Option<&'doc Namespace<'doc>>>,
412    /// Already entity-expanded by the parser.
413    pub value:     &'doc str,
414    pub next:      Cell<Option<&'doc Attribute<'doc>>>,
415    pub prev:      Cell<Option<&'doc Attribute<'doc>>>,
416    /// Element this attribute belongs to.  `None` only for a freshly-allocated
417    /// attribute not yet attached via [`DocumentBuilder::append_attribute`].
418    pub parent:    Cell<Option<&'doc Node<'doc>>>,
419}
420
421/// xmlAttr-mirror layout (c-abi build).  See type-level doc for the
422/// libxml2 reference layout.  Note: libxml2's `xmlAttr` puts the
423/// **value** in a child text node chain (`children`/`last`), not in a
424/// dedicated `value` field.  Our `value: ArenaCStr` is in the
425/// sup-xml-only tail (after `psvi`).  C callers that follow
426/// `xmlAttr::children` get the text node our serializer materialises;
427/// callers using `xmlGetProp(...)` (the documented path) get the
428/// value directly through that function.
429#[cfg(feature = "c-abi")]
430#[repr(C)]
431pub struct Attribute<'doc> {
432    pub _private:  Cell<*mut std::os::raw::c_void>,            //   0
433    pub kind:      NodeKind,             // XML_ATTRIBUTE_NODE //   8
434    _pad_kind:     u32,                                        //  12
435    pub name:      ArenaCStr<'doc>,                          //  16
436    pub children:  Cell<Option<&'doc Node<'doc>>>,         //  24  (text-node chain)
437    pub last:      Cell<Option<&'doc Node<'doc>>>,         //  32
438    pub parent:    Cell<Option<&'doc Node<'doc>>>,         //  40
439    pub next:      Cell<Option<&'doc Attribute<'doc>>>,    //  48
440    pub prev:      Cell<Option<&'doc Attribute<'doc>>>,    //  56
441    pub doc:       Cell<*mut std::os::raw::c_void>,            //  64  (xmlDoc*)
442    pub namespace: Cell<Option<&'doc Namespace<'doc>>>,    //  72  (`ns`)
443    pub atype:     u32,                                        //  80  (xmlAttributeType)
444    _pad_atype:    u32,                                        //  84
445    pub psvi:      Cell<*mut std::os::raw::c_void>,            //  88
446    // ── sup-xml-only tail (NOT part of ABI window) ──
447    /// Already entity-expanded by the parser.  Direct slot — libxml2
448    /// callers normally use `xmlGetProp(...)` rather than reading it
449    /// from the struct directly.
450    pub value:     ArenaCStr<'doc>,
451}
452
453impl<'doc> Attribute<'doc> {
454    /// Attribute name (`xlink:href`, `id`, etc.).
455    ///
456    /// **Prefer this method over direct `attr.name` field access.**
457    /// The `pub name` field stays stable on the lean rlib build; in
458    /// the `c-abi` build it becomes a thin NUL-terminated
459    /// `ArenaCStr`.  This method returns `&str` either way.
460    #[inline]
461    pub fn name(&self) -> &'doc str {
462        #[cfg(not(feature = "c-abi"))]
463        { self.name }
464        #[cfg(feature = "c-abi")]
465        { self.name.as_str() }
466    }
467
468    /// The attribute's local name (the part after any `prefix:`).
469    ///
470    /// Layout-agnostic, mirroring [`Node::local_name`]: on the lean
471    /// build [`name`](Self::name) is the full QName, while on the
472    /// `c-abi` build the prefix is stripped at parse time so `name()`
473    /// is already local.  Callers matching a namespaced attribute by
474    /// its local part should use this rather than `name()`.
475    #[inline]
476    pub fn local_name(&self) -> &'doc str {
477        let n = self.name();
478        match n.rfind(':') {
479            Some(i) => &n[i + 1..],
480            None    => n,
481        }
482    }
483
484    /// Attribute value (entity-expanded by the parser).  Same
485    /// rationale as [`name`](Self::name) for preferring this over
486    /// direct field access.
487    ///
488    /// In the c-abi build, attribute values are stored two ways:
489    /// the sup-xml-only `value` slot (set by our parser /
490    /// `new_attribute` API) and the libxml2-standard text-node
491    /// chain rooted at `children` (the path libxslt writes to when
492    /// it builds attributes during an XSLT transform — it doesn't
493    /// know about our tail field).  When `value` is empty, fall
494    /// back to walking `children` so attributes built post-parse
495    /// by libxslt still report the right text.
496    #[inline]
497    pub fn value(&self) -> &'doc str {
498        #[cfg(not(feature = "c-abi"))]
499        { self.value }
500        #[cfg(feature = "c-abi")]
501        {
502            let v = self.value.as_str();
503            if !v.is_empty() { return v; }
504            let mut child = self.children.get();
505            while let Some(c) = child {
506                let s = c.content();
507                if !s.is_empty() { return s; }
508                child = c.next_sibling.get();
509            }
510            ""
511        }
512    }
513
514    /// Iterate the attribute's text-node child chain — the libxml2
515    /// representation of the attribute's value.  Only meaningful in
516    /// the c-abi build (where `Attribute` carries `children`); the
517    /// lean build holds the value directly in [`value`](Self::value).
518    #[cfg(feature = "c-abi")]
519    pub fn children(&self) -> ChildIter<'doc> {
520        ChildIter::from_head(self.children.get())
521    }
522}
523
524impl std::fmt::Debug for Attribute<'_> {
525    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
526        f.debug_struct("Attribute")
527            .field("name",  &self.name())
528            .field("value", &self.value())
529            .finish()
530    }
531}
532
533/// A node in the XML tree.  One struct for every kind; fields are used per-kind.
534///
535/// # Layout (libxml2 mirror)
536///
537/// The struct is `#[repr(C)]` with field order chosen to align with
538/// `_xmlNode` in libxml2.  When we later expose an `extern "C"` shim,
539/// callers can treat `*mut Node` as `xmlNode*` (modulo a few private slots
540/// we may still need to add — `_private`, `psvi`, etc.).
541///
542/// # Field usage by kind
543///
544/// | Kind         | `name`       | `content`                  | `first_*` / `last_*` |
545/// |--------------|--------------|----------------------------|----------------------|
546/// | `Element`    | tag name     | unused (`""`)              | children + attrs     |
547/// | `Text`       | `""`         | text data                  | unused               |
548/// | `CData`      | `""`         | CDATA payload              | unused               |
549/// | `Comment`    | `""`         | comment text               | unused               |
550/// | `Pi`         | target       | content after target       | unused               |
551#[cfg(not(feature = "c-abi"))]
552#[repr(C)]
553pub struct Node<'doc> {
554    pub kind:            NodeKind,
555    pub name:            &'doc str,
556    pub namespace:       Cell<Option<&'doc Namespace<'doc>>>,
557    /// Linked-list head for element attributes (None for non-elements).
558    pub first_attribute: Cell<Option<&'doc Attribute<'doc>>>,
559    pub last_attribute:  Cell<Option<&'doc Attribute<'doc>>>,
560    pub first_child:     Cell<Option<&'doc Node<'doc>>>,
561    pub last_child:      Cell<Option<&'doc Node<'doc>>>,
562    pub parent:          Cell<Option<&'doc Node<'doc>>>,
563    pub next_sibling:    Cell<Option<&'doc Node<'doc>>>,
564    pub prev_sibling:    Cell<Option<&'doc Node<'doc>>>,
565    /// Text/CData/Comment/Pi payload.  `None` mirrors libxml2's NULL
566    /// `content` — notably a processing instruction with no data
567    /// (`<?foo?>`), which serializes without the trailing space that a
568    /// PI carrying a (possibly empty) data section gets.
569    pub content:         Cell<Option<&'doc str>>,
570    /// 1-based source line of the opening tag.  0 for nodes constructed
571    /// programmatically.
572    pub line:            u32,
573    /// 0-based byte offset of the opening tag's name in the source
574    /// buffer.  0 for nodes not produced by the parser.  Saturates at
575    /// `u32::MAX` for inputs past 4 GiB.  Line and column are derived
576    /// from this offset against the document's source buffer
577    /// ([`Document::source`]) — the offset is the single ground truth.
578    pub source_offset:   u32,
579}
580
581/// libxml2-shape Node (c-abi build).  Byte-exact match with `_xmlNode`
582/// for the public window (offsets 0..120).  See type-level doc and
583/// `thoughts/c_abi_implementation_plan.md` for the offset table.
584///
585/// Field naming choices for the c-abi build:
586/// - `first_child` / `last_child` rather than libxml2's `children` /
587///   `last` (the field SLOT matches; we use the more descriptive
588///   sup-xml name).
589/// - `first_attribute` rather than libxml2's `properties` (same
590///   reasoning).
591/// - `namespace` rather than libxml2's `ns` (same).
592/// - `ns_def` matches libxml2's name verbatim.
593#[cfg(feature = "c-abi")]
594#[repr(C)]
595pub struct Node<'doc> {
596    pub _private:        Cell<*mut std::os::raw::c_void>,            //   0
597    pub kind:            NodeKind,                  // xmlElementType //   8
598    _pad_kind:           u32,                                        //  12
599    pub name:            ArenaCStr<'doc>,                          //  16
600    pub first_child:     Cell<Option<&'doc Node<'doc>>>,         //  24
601    pub last_child:      Cell<Option<&'doc Node<'doc>>>,         //  32
602    pub parent:          Cell<Option<&'doc Node<'doc>>>,         //  40
603    pub next_sibling:    Cell<Option<&'doc Node<'doc>>>,         //  48
604    pub prev_sibling:    Cell<Option<&'doc Node<'doc>>>,         //  56
605    pub doc:             Cell<*mut std::os::raw::c_void>,            //  64  (xmlDoc*)
606    pub namespace:       Cell<Option<&'doc Namespace<'doc>>>,    //  72
607    pub content:         Cell<Option<ArenaCStr<'doc>>>,            //  80
608    pub first_attribute: Cell<Option<&'doc Attribute<'doc>>>,    //  88
609    pub ns_def:          Cell<Option<&'doc Namespace<'doc>>>,    //  96
610    pub psvi:            Cell<*mut std::os::raw::c_void>,            // 104
611    pub line:            u16,                                        // 112
612    pub extra:           u16,                                        // 114
613    _pad_extra:          [u8; 4],                                    // 116..120
614    // ── sup-xml-only tail (NOT part of ABI window) ──
615    /// Tail of the attribute linked list for O(1) append.  libxml2
616    /// walks `first_attribute->next->...->NULL` to find the tail;
617    /// we cache it for the parse hot path.
618    pub last_attribute:  Cell<Option<&'doc Attribute<'doc>>>,
619    /// Full-width source line, uncapped.  The ABI `line` field is a
620    /// `u16` (libxml2's `unsigned short`) so it saturates at 65535; this
621    /// shadow copy keeps the real line for files past that, which
622    /// `xmlGetLineNo` returns in preference.  `0` for nodes not produced
623    /// by the parser (created via the tree API), which fall back to
624    /// `line`.  libxml2 instead stashes big lines in `psvi` on text nodes
625    /// and recurses in `xmlGetLineNo`; a dedicated field is exact (no
626    /// neighbour-line guessing for childless nodes like `<br/>`).
627    pub full_line:       u32,
628    /// 0-based byte offset of the opening tag's name in the source
629    /// buffer.  0 for nodes not produced by the parser.  Saturates at
630    /// `u32::MAX` for inputs past 4 GiB.  Outside the libxml2 ABI
631    /// window, so it does not affect `_xmlNode` compatibility.  Line and
632    /// column are derived from this offset against the document's source
633    /// buffer ([`Document::source`]) — the offset is the ground truth.
634    pub source_offset:   u32,
635}
636
637// ── compile-time layout assertions (c-abi build) ────────────────────────────
638//
639// These `const _:` blocks verify that our `#[repr(C)]` struct layouts
640// match libxml2 byte-exact at every field offset in the public ABI
641// window.  Drift = compile error.
642//
643// The offsets below are pinned to libxml2 2.9.13 and 2.15.3, the
644// versions we have verified compat against.  We do NOT make a
645// forward-compatibility claim — if libxml2 ships a version that
646// appends fields to `_xmlNode` / `_xmlAttr` / `_xmlDoc`, our Box
647// allocations would be undersized for callers reading at the new
648// offsets and compat needs a coordinated bump on our side.
649//
650// Two checks defend against drifting unawares:
651//   - `crates/compat/c-tests/t-upstream-layout.c` compiles
652//     `_Static_assert(offsetof(...))` against the *live installed*
653//     `<libxml/...>` headers.  If the dev/CI host has a libxml2
654//     version newer than what we've pinned, the build breaks at the
655//     exact offset that moved.
656//   - `crates/compat/c-tests/t-layout-{03,04}.c` plus `t-err-03.c`
657//     use locally-typedef'd reference structs to verify these Rust
658//     offsets match compat's expected C-side view.
659//   - `crates/compat/c-tests/t-libxml2-headers.c` uses the real
660//     headers at runtime — would have caught the earlier mistake
661//     where we mis-encoded `_xmlNs`.
662
663#[cfg(feature = "c-abi")]
664const _: () = {
665    use std::mem::offset_of;
666
667    // ── _xmlNode (64-bit) ──
668    assert!(offset_of!(Node<'static>, _private)        ==   0, "Node::_private @ 0");
669    assert!(offset_of!(Node<'static>, kind)            ==   8, "Node::kind @ 8");
670    assert!(offset_of!(Node<'static>, name)            ==  16, "Node::name @ 16");
671    assert!(offset_of!(Node<'static>, first_child)     ==  24, "Node::first_child (children) @ 24");
672    assert!(offset_of!(Node<'static>, last_child)      ==  32, "Node::last_child (last) @ 32");
673    assert!(offset_of!(Node<'static>, parent)          ==  40, "Node::parent @ 40");
674    assert!(offset_of!(Node<'static>, next_sibling)    ==  48, "Node::next_sibling (next) @ 48");
675    assert!(offset_of!(Node<'static>, prev_sibling)    ==  56, "Node::prev_sibling (prev) @ 56");
676    assert!(offset_of!(Node<'static>, doc)             ==  64, "Node::doc @ 64");
677    assert!(offset_of!(Node<'static>, namespace)       ==  72, "Node::namespace (ns) @ 72");
678    assert!(offset_of!(Node<'static>, content)         ==  80, "Node::content @ 80");
679    assert!(offset_of!(Node<'static>, first_attribute) ==  88, "Node::first_attribute (properties) @ 88");
680    assert!(offset_of!(Node<'static>, ns_def)          ==  96, "Node::ns_def @ 96");
681    assert!(offset_of!(Node<'static>, psvi)            == 104, "Node::psvi @ 104");
682    assert!(offset_of!(Node<'static>, line)            == 112, "Node::line @ 112");
683    assert!(offset_of!(Node<'static>, extra)           == 114, "Node::extra @ 114");
684    // The libxml2 ABI window ends at offset 120.  Our sup-xml-only
685    // tail (last_attribute) starts there or after — we don't pin its
686    // offset since it's not part of the contract.
687    assert!(offset_of!(Node<'static>, last_attribute)  >= 120, "Node tail starts after ABI window");
688
689    // ── _xmlAttr (64-bit) — shares first 8 fields with _xmlNode ──
690    assert!(offset_of!(Attribute<'static>, _private)   ==   0, "Attribute::_private @ 0");
691    assert!(offset_of!(Attribute<'static>, kind)       ==   8, "Attribute::kind @ 8");
692    assert!(offset_of!(Attribute<'static>, name)       ==  16, "Attribute::name @ 16");
693    assert!(offset_of!(Attribute<'static>, children)   ==  24, "Attribute::children @ 24");
694    assert!(offset_of!(Attribute<'static>, last)       ==  32, "Attribute::last @ 32");
695    assert!(offset_of!(Attribute<'static>, parent)     ==  40, "Attribute::parent @ 40");
696    assert!(offset_of!(Attribute<'static>, next)       ==  48, "Attribute::next @ 48");
697    assert!(offset_of!(Attribute<'static>, prev)       ==  56, "Attribute::prev @ 56");
698    assert!(offset_of!(Attribute<'static>, doc)        ==  64, "Attribute::doc @ 64");
699    assert!(offset_of!(Attribute<'static>, namespace)  ==  72, "Attribute::namespace (ns) @ 72");
700    assert!(offset_of!(Attribute<'static>, atype)      ==  80, "Attribute::atype @ 80");
701    assert!(offset_of!(Attribute<'static>, psvi)       ==  88, "Attribute::psvi @ 88");
702    // value lives in the sup-xml-only tail.
703    assert!(offset_of!(Attribute<'static>, value)      >=  96, "Attribute value in tail");
704
705    // ── Struct sizes ──
706    // _xmlNode public window is 120 bytes.  Our struct is 120 + tail
707    // (last_attribute = 8 bytes, no padding).
708    assert!(std::mem::size_of::<Node<'static>>()      >= 120, "Node size >= 120 (ABI window)");
709    // Attribute's ABI window is exposed up through `psvi` at offset 88
710    // (so the window is 96 bytes including alignment padding); the
711    // value field in the tail brings us to 96 + 8 = 104+ minimum.
712    assert!(std::mem::size_of::<Attribute<'static>>() >=  96, "Attribute size >= ABI window");
713
714    // ── ArenaCStr is 1 pointer wide (matches xmlChar*) ──
715    assert!(std::mem::size_of::<ArenaCStr<'static>>() == std::mem::size_of::<*const u8>(),
716        "ArenaCStr must be a single thin pointer to match xmlChar*");
717    // ── Option<ArenaCStr> must niche-opt to a single pointer too,
718    //    since libxml2 uses NULL `xmlChar*` to mean "absent" and our
719    //    Option<ArenaCStr> sits in the xmlChar* slot of _xmlNs::prefix.
720    assert!(std::mem::size_of::<Option<ArenaCStr<'static>>>() == std::mem::size_of::<*const u8>(),
721        "Option<ArenaCStr> must niche-opt to a single pointer");
722
723    // ── _xmlNs (64-bit) — the odd duck: `next` precedes `_private`
724    //    whereas every other public libxml2 struct puts `_private` first.
725    //    Layout verified against libxml2 2.9.13 and 2.15.3.
726    assert!(offset_of!(Namespace<'static>, next)     ==  0, "Namespace::next @ 0");
727    assert!(offset_of!(Namespace<'static>, kind)     ==  8, "Namespace::kind @ 8");
728    assert!(offset_of!(Namespace<'static>, href)     == 16, "Namespace::href @ 16");
729    assert!(offset_of!(Namespace<'static>, prefix)   == 24, "Namespace::prefix @ 24");
730    assert!(offset_of!(Namespace<'static>, _private) == 32, "Namespace::_private @ 32");
731    assert!(offset_of!(Namespace<'static>, context)  == 40, "Namespace::context @ 40");
732    assert!(std::mem::size_of::<Namespace<'static>>() == 48, "sizeof(Namespace) == 48");
733};
734
735impl<'doc> Node<'doc> {
736    pub fn is_element(&self)     -> bool { matches!(self.kind, NodeKind::Element) }
737    pub fn is_text(&self)        -> bool { matches!(self.kind, NodeKind::Text) }
738    pub fn is_entity_ref(&self)  -> bool { matches!(self.kind, NodeKind::EntityRef) }
739
740    /// Element name (or PI target for PI nodes).  Empty `""` for
741    /// Text/CData/Comment.
742    ///
743    /// **Prefer this method over direct `node.name` field access in
744    /// internal / downstream code.**  The `pub name` field stays
745    /// stable on the lean rlib build, but when sup-xml is built with
746    /// the `c-abi` feature the storage type changes to a thin
747    /// NUL-terminated `ArenaCStr`.  This method returns `&str` on
748    /// both configs — direct field access does not.
749    #[inline]
750    pub fn name(&self) -> &'doc str {
751        #[cfg(not(feature = "c-abi"))]
752        { self.name }
753        #[cfg(feature = "c-abi")]
754        { self.name.as_str() }
755    }
756
757    /// Text payload for `Text`/`CData`/`Comment`/`Pi` nodes; `""` for
758    /// elements.  See [`name`](Self::name) for why to prefer this
759    /// method over direct field access.
760    #[inline]
761    pub fn content(&self) -> &'doc str {
762        self.content_opt().unwrap_or("")
763    }
764
765    /// The payload as libxml2 stores it: `None` when the underlying
766    /// `content` pointer is NULL, `Some` (possibly `""`) otherwise.
767    /// Most callers want [`content`](Self::content); the serializer uses
768    /// this to reproduce libxml2's PI rule (a NULL-data PI omits the
769    /// space a non-NULL-but-empty-data PI emits).
770    pub fn content_opt(&self) -> Option<&'doc str> {
771        #[cfg(not(feature = "c-abi"))]
772        { self.content.get() }
773        #[cfg(feature = "c-abi")]
774        { self.content.get().map(|c| c.as_str()) }
775    }
776
777    /// Replace the node's content (text/CData/comment/PI payload).
778    /// Used by the HTML sink and other in-place tree mutators.  Allocates
779    /// a NUL-terminated copy in the arena when the c-abi feature is on.
780    ///
781    /// `arena` must be the same `DocumentBuilder` that owns this node
782    /// (lifetimes enforce it).
783    pub fn set_content(&self, arena: &'doc DocumentBuilder, content: &'doc str) {
784        #[cfg(not(feature = "c-abi"))]
785        {
786            let _ = arena; // unused in lean build — content fits straight as &str
787            self.content.set(Some(content));
788        }
789        #[cfg(feature = "c-abi")]
790        {
791            self.content.set(Some(arena.alloc_arena_cstr(content)));
792        }
793    }
794
795    /// Iterate child nodes in document order.
796    pub fn children(&self) -> ChildIter<'doc> {
797        ChildIter { cur: self.first_child.get() }
798    }
799
800    /// Iterate attributes in document order.  Returns an empty iterator for
801    /// non-elements.
802    pub fn attributes(&self) -> AttrIter<'doc> {
803        AttrIter { cur: self.first_attribute.get() }
804    }
805
806    /// Local part of this element/attr-like node's name — `"foo"` for both
807    /// `<foo/>` and `<ns:foo/>`.  On the lean build [`name`](Self::name)
808    /// returns the full QName including any prefix; on the `c-abi` build
809    /// the prefix is stripped at parse time and `name()` is already the
810    /// local part.  `local_name()` is the layout-agnostic accessor:
811    /// callers that want to match by local name should use this.
812    #[inline]
813    pub fn local_name(&self) -> &'doc str {
814        let n = self.name();
815        match n.rfind(':') {
816            Some(i) => &n[i + 1..],
817            None    => n,
818        }
819    }
820
821    /// Iterate this element's xmlns declarations as `(prefix, href)` —
822    /// `prefix` is `None` for the default namespace (`xmlns="..."`),
823    /// `Some("dc")` for `xmlns:dc="..."`.  Empty for non-elements.
824    ///
825    /// Storage differs by build: the c-abi build keeps xmlns declarations
826    /// on the element's `ns_def` chain (matching libxml2's `_xmlNode`);
827    /// the lean build keeps them in [`attributes`](Self::attributes)
828    /// instead.  A namespace-blind parse (`namespace_aware: false`) does
829    /// no namespace processing and leaves xmlns declarations in the
830    /// attribute list under *either* build, so the c-abi iterator walks
831    /// `ns_def` first and then the attribute list — the two are mutually
832    /// exclusive (a given parse populates one or the other), so nothing is
833    /// reported twice.  Callers see every declaration regardless of build
834    /// or parse mode.
835    pub fn ns_declarations(&self) -> NsDeclIter<'doc> {
836        #[cfg(feature = "c-abi")]
837        {
838            NsDeclIter::CAbi { cur: self.ns_def.get(), attrs: self.first_attribute.get() }
839        }
840        #[cfg(not(feature = "c-abi"))]
841        {
842            NsDeclIter::Lean { cur: self.first_attribute.get() }
843        }
844    }
845
846    /// First child element matching `name`, or `None`.  O(n) walk; for repeated
847    /// lookups, iterate `children()` yourself.
848    pub fn find_child(&self, name: &str) -> Option<&'doc Node<'doc>> {
849        self.children().find(|n| n.is_element() && n.name() == name)
850    }
851
852    /// For text-bearing kinds returns the content; for elements returns the
853    /// first text-or-CDATA child's content; otherwise `None`.
854    pub fn text_content(&self) -> Option<&'doc str> {
855        match self.kind {
856            NodeKind::Text | NodeKind::CData => Some(self.content()),
857            NodeKind::Element => self.children().find_map(|c| match c.kind {
858                NodeKind::Text | NodeKind::CData => Some(c.content()),
859                _ => None,
860            }),
861            _ => None,
862        }
863    }
864}
865
866impl std::fmt::Debug for Node<'_> {
867    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
868        let mut s = f.debug_struct("Node");
869        s.field("kind", &self.kind);
870        let name = self.name();
871        if !name.is_empty() { s.field("name", &name); }
872        let content = self.content();
873        if !content.is_empty() { s.field("content", &content); }
874        s.finish()
875    }
876}
877
878/// Iterator over a node's children.
879pub struct ChildIter<'doc> { cur: Option<&'doc Node<'doc>> }
880impl<'doc> ChildIter<'doc> {
881    /// Construct from an explicit head pointer — used by
882    /// [`Attribute::children`] which holds its child chain in a
883    /// different field than [`Node::children`].
884    #[inline]
885    pub fn from_head(head: Option<&'doc Node<'doc>>) -> Self {
886        Self { cur: head }
887    }
888}
889impl<'doc> Iterator for ChildIter<'doc> {
890    type Item = &'doc Node<'doc>;
891    fn next(&mut self) -> Option<Self::Item> {
892        let c = self.cur?;
893        self.cur = c.next_sibling.get();
894        Some(c)
895    }
896}
897
898/// Iterator over an element's attributes.
899pub struct AttrIter<'doc> { cur: Option<&'doc Attribute<'doc>> }
900impl<'doc> Iterator for AttrIter<'doc> {
901    type Item = &'doc Attribute<'doc>;
902    fn next(&mut self) -> Option<Self::Item> {
903        let a = self.cur?;
904        self.cur = a.next.get();
905        Some(a)
906    }
907}
908
909/// Iterator yielded by [`Node::ns_declarations`].  Each item is
910/// `(prefix, href)` where `prefix` is `None` for the default
911/// namespace declaration.  The variant in use depends on the build
912/// feature flags — callers should treat it as opaque.
913pub enum NsDeclIter<'doc> {
914    #[cfg(feature = "c-abi")]
915    CAbi {
916        cur:   Option<&'doc Namespace<'doc>>,
917        attrs: Option<&'doc Attribute<'doc>>,
918    },
919    #[cfg(not(feature = "c-abi"))]
920    Lean { cur: Option<&'doc Attribute<'doc>> },
921}
922
923/// Advance an attribute cursor to the next `xmlns`/`xmlns:*` declaration,
924/// yielding `(prefix, href)` and skipping ordinary attributes.
925#[inline]
926fn next_xmlns_attr<'doc>(
927    cur: &mut Option<&'doc Attribute<'doc>>,
928) -> Option<(Option<&'doc str>, &'doc str)> {
929    loop {
930        let a = (*cur)?;
931        *cur = a.next.get();
932        let n = a.name();
933        if n == "xmlns" {
934            return Some((None, a.value()));
935        } else if let Some(local) = n.strip_prefix("xmlns:") {
936            return Some((Some(local), a.value()));
937        }
938    }
939}
940
941impl<'doc> Iterator for NsDeclIter<'doc> {
942    type Item = (Option<&'doc str>, &'doc str);
943    fn next(&mut self) -> Option<Self::Item> {
944        match self {
945            #[cfg(feature = "c-abi")]
946            NsDeclIter::CAbi { cur, attrs } => {
947                if let Some(ns) = *cur {
948                    *cur = ns.next.get();
949                    return Some((ns.prefix(), ns.href()));
950                }
951                // `ns_def` exhausted — surface any xmlns declarations that a
952                // namespace-blind parse left in the attribute list.
953                next_xmlns_attr(attrs)
954            }
955            #[cfg(not(feature = "c-abi"))]
956            NsDeclIter::Lean { cur } => next_xmlns_attr(cur),
957        }
958    }
959}
960
961// ── builder ─────────────────────────────────────────────────────────────────
962
963/// Constructs a [`Document`] one node at a time.  The parser uses this
964/// internally; consumers building trees by hand use the same.
965///
966/// The builder owns a [`Bump`].  Allocated nodes live for the lifetime of
967/// the builder (and, after `build()`, of the resulting [`Document`]).
968///
969/// # Build flow
970///
971/// ```
972/// # use sup_xml_tree::dom::DocumentBuilder;
973/// let b = DocumentBuilder::new();
974/// let root = b.new_element(b.alloc_str("catalog"));
975/// // … allocate more nodes, link them via append_child / append_attribute …
976/// b.set_root(root);
977/// let doc = b.build();
978/// ```
979///
980/// `set_root` returns immediately (no borrow on the builder is held past the
981/// call), so the subsequent `build()` is free to consume `self` even though
982/// `root` borrowed from the builder during construction.
983pub struct DocumentBuilder {
984    /// Refcounted heap allocation.  Stored as `Arc<Bump>` rather than
985    /// `Box<Bump>` so a node grafted into another document can keep its
986    /// origin arena alive past the origin document's drop — see
987    /// [`DocumentBuilder::new_with_dict_and_arena`] and the
988    /// `compat::dict::new_doc_arena` rationale.  Cloning is a pure
989    /// refcount bump.
990    ///
991    /// `Bump` is `!Sync`, which makes `Arc<Bump>` `!Send` per Rust's
992    /// auto-trait rules.  The containing `Document` re-asserts `Send`
993    /// via `unsafe impl` — that's safe because the GIL contract on the
994    /// consumer side (and our own internal single-threaded discipline)
995    /// guarantees we never use two `&Bump` derived from the same Arc on
996    /// two threads concurrently.
997    bump: Arc<Bump>,
998    /// Per-document name interner.  Element / attribute /
999    /// namespace names route through this rather than the bumpalo
1000    /// arena so consumers see pointer-equality across identical
1001    /// names — e.g. every `<p>` tag in a 100k-element doc shares
1002    /// one canonical name pointer instead of 100k arena copies.
1003    ///
1004    /// Holds *one* refcounted reference; the underlying dict may be
1005    /// shared with the parser context that originally created it
1006    /// (when [`new_with_dict`](Self::new_with_dict) is used) or be
1007    /// owned solely by this builder otherwise.  Released on drop.
1008    #[cfg(feature = "c-abi")]
1009    dict: *mut crate::dict::Dict,
1010    /// Root pointer.  Stored with `'static` lifetime erasure; the borrow-check
1011    /// rigor lives in `set_root` (lifetime ties root to `&self`) and the
1012    /// `Document::root()` accessor (re-binds lifetime to `&'a self`).
1013    root: Cell<*const Node<'static>>,
1014    /// XML declaration version (default `"1.0"`).  Set via
1015    /// [`set_version`](Self::set_version); plumbed into [`Document::version`].
1016    version:    std::cell::RefCell<String>,
1017    /// XML declaration encoding (default `"UTF-8"`).  Set via
1018    /// [`set_encoding`](Self::set_encoding); plumbed into [`Document::encoding`].
1019    encoding:   std::cell::RefCell<String>,
1020    /// XML declaration `standalone="…"` value, or `None` when absent.
1021    /// Set via [`set_standalone`](Self::set_standalone).
1022    standalone: Cell<Option<bool>>,
1023    /// URI the document is being loaded from, if known.  Set via
1024    /// [`set_base_url`](Self::set_base_url); plumbed into
1025    /// [`Document::base_url`].
1026    base_url:   std::cell::RefCell<Option<String>>,
1027    /// HTML-specific metadata.  Set by the HTML parser sink via
1028    /// [`set_html_metadata`](Self::set_html_metadata); `None` for XML
1029    /// documents.  Plumbed into [`Document::html_metadata`] on `build`.
1030    html_metadata: std::cell::RefCell<Option<HtmlMeta>>,
1031    /// Owned source buffer (raw pointer + length) that arena strings may
1032    /// point into via [`alloc_str_borrow`](Self::alloc_str_borrow).
1033    ///
1034    /// **Raw pointer rather than `Box<[u8]>` is intentional.**  Storing
1035    /// as `Pin<Box<[u8]>>` triggers a Stacked Borrows violation: when
1036    /// [`build`](Self::build) consumes `self`, the Box field is moved
1037    /// into the [`Document`] and the move performs a Unique retag of
1038    /// the parent.  Any `SharedReadOnly` borrows we'd handed out into
1039    /// the source bytes (i.e. arena names and text content) get
1040    /// invalidated by that Unique retag — a real `cargo +nightly miri`
1041    /// failure.  Storing the bytes via a raw pointer that the parent
1042    /// only ever observes by-value avoids the retag chain entirely.
1043    /// See `parse_owned_bytes` in `sup-xml-core::parser` for the
1044    /// matching parser-side discipline.
1045    ///
1046    /// Ownership: the `Box<[u8]>` is leaked at [`set_source`](Self::set_source)
1047    /// time; the resulting raw pointer is then either reclaimed by
1048    /// [`build`](Self::build) (which transfers ownership to the
1049    /// [`Document`]'s `Drop`) or by the builder's own `Drop` if `build`
1050    /// was never called.
1051    source_ptr: Cell<*mut u8>,
1052    source_len: Cell<usize>,
1053    /// Orphan leaves (comments / PIs) encountered before the root
1054    /// element opened.  Each entry is a type-erased pointer to a
1055    /// node already allocated in this builder's arena.  On
1056    /// [`build`](Self::build) these are linked as `root.prev`
1057    /// siblings (in order) so consumers walking the document's
1058    /// children see comments-before-root + root + comments-after-
1059    /// root, just like libxml2.  Empty when the document has no
1060    /// prolog/epilogue content (the common case).
1061    prolog_orphans:   RefCell<Vec<*const Node<'static>>>,
1062    /// Same as [`prolog_orphans`] for nodes that follow the root.
1063    epilogue_orphans: RefCell<Vec<*const Node<'static>>>,
1064}
1065
1066impl DocumentBuilder {
1067    pub fn new() -> Self {
1068        Self {
1069            bump:          Arc::new(Bump::new()),
1070            #[cfg(feature = "c-abi")]
1071            dict:          crate::dict::Dict::new_refcounted(),
1072            root:          Cell::new(std::ptr::null()),
1073            version:       std::cell::RefCell::new("1.0".to_string()),
1074            // Default to empty — libxml2 leaves doc->encoding NULL
1075            // when the source XML had no `<?xml encoding="…"?>`
1076            // declaration; serializers then omit the encoding
1077            // attribute on output.  The parser explicitly sets this
1078            // when it sees a declaration.
1079            encoding:      std::cell::RefCell::new(String::new()),
1080            standalone:    Cell::new(None),
1081            base_url:      std::cell::RefCell::new(None),
1082            html_metadata: std::cell::RefCell::new(None),
1083            source_ptr:    Cell::new(std::ptr::null_mut()),
1084            source_len:    Cell::new(0),
1085            prolog_orphans:   RefCell::new(Vec::new()),
1086            epilogue_orphans: RefCell::new(Vec::new()),
1087        }
1088    }
1089
1090    /// Build with an externally-supplied name dict (refcount bumped
1091    /// for our reference).  Used when a parser context already owns
1092    /// a dict that should be shared with the new document — e.g.
1093    /// libxml2's `xmlCtxtReadMemory` flow, where `ctxt->dict` is
1094    /// the thread-shared interner the consumer wants names to live
1095    /// in.  Names interned through this builder reuse that dict's
1096    /// canonical pointers.
1097    ///
1098    /// # Safety
1099    ///
1100    /// `dict` must be a valid pointer returned by
1101    /// [`crate::dict::Dict::new_refcounted`] (or otherwise refcount-
1102    /// managed by the libxml2 ABI), with at least one outstanding
1103    /// reference.
1104    #[cfg(feature = "c-abi")]
1105    pub unsafe fn new_with_dict(dict: *mut crate::dict::Dict) -> Self {
1106        // SAFETY: caller asserts `dict` is live with a positive
1107        // refcount; bumping is sound.
1108        unsafe { (*dict).add_ref(); }
1109        Self {
1110            bump:          Arc::new(Bump::new()),
1111            dict,
1112            root:          Cell::new(std::ptr::null()),
1113            version:       std::cell::RefCell::new("1.0".to_string()),
1114            // Default to empty — libxml2 leaves doc->encoding NULL
1115            // when the source XML had no `<?xml encoding="…"?>`
1116            // declaration; serializers then omit the encoding
1117            // attribute on output.  The parser explicitly sets this
1118            // when it sees a declaration.
1119            encoding:      std::cell::RefCell::new(String::new()),
1120            standalone:    Cell::new(None),
1121            base_url:      std::cell::RefCell::new(None),
1122            html_metadata: std::cell::RefCell::new(None),
1123            source_ptr:    Cell::new(std::ptr::null_mut()),
1124            source_len:    Cell::new(0),
1125            prolog_orphans:   RefCell::new(Vec::new()),
1126            epilogue_orphans: RefCell::new(Vec::new()),
1127        }
1128    }
1129
1130    /// Build with both an externally-supplied dict and arena.  The
1131    /// arena is an [`Arc`]-shared [`Bump`]; cloning into a Document
1132    /// is a pure refcount bump, no allocation.  Used by C-ABI
1133    /// consumers that route all per-thread doc creation through a
1134    /// single shared arena — node memory then survives any
1135    /// individual doc's drop, which makes cross-doc graft
1136    /// operations (libxml2 consumers' `_appendChild` /
1137    /// `moveNodeToDocument`) safe by construction.
1138    ///
1139    /// # Safety
1140    ///
1141    /// `dict` must be a valid pointer returned by
1142    /// [`crate::dict::Dict::new_refcounted`] with at least one
1143    /// outstanding reference.
1144    #[cfg(feature = "c-abi")]
1145    pub unsafe fn new_with_dict_and_arena(
1146        dict:  *mut crate::dict::Dict,
1147        arena: Arc<Bump>,
1148    ) -> Self {
1149        // SAFETY: caller asserts `dict` is live with a positive refcount.
1150        unsafe { (*dict).add_ref(); }
1151        Self {
1152            bump:          arena,
1153            dict,
1154            root:          Cell::new(std::ptr::null()),
1155            version:       std::cell::RefCell::new("1.0".to_string()),
1156            // Default to empty — libxml2 leaves doc->encoding NULL
1157            // when the source XML had no `<?xml encoding="…"?>`
1158            // declaration; serializers then omit the encoding
1159            // attribute on output.  The parser explicitly sets this
1160            // when it sees a declaration.
1161            encoding:      std::cell::RefCell::new(String::new()),
1162            standalone:    Cell::new(None),
1163            base_url:      std::cell::RefCell::new(None),
1164            html_metadata: std::cell::RefCell::new(None),
1165            source_ptr:    Cell::new(std::ptr::null_mut()),
1166            source_len:    Cell::new(0),
1167            prolog_orphans:   RefCell::new(Vec::new()),
1168            epilogue_orphans: RefCell::new(Vec::new()),
1169        }
1170    }
1171
1172    /// Pre-allocate `capacity` bytes for the arena.  Useful when parsing large
1173    /// documents — avoids the initial small-chunk allocations.
1174    pub fn with_capacity(capacity: usize) -> Self {
1175        Self {
1176            bump:          Arc::new(Bump::with_capacity(capacity)),
1177            #[cfg(feature = "c-abi")]
1178            dict:          crate::dict::Dict::new_refcounted(),
1179            root:          Cell::new(std::ptr::null()),
1180            version:       std::cell::RefCell::new("1.0".to_string()),
1181            // Default to empty — libxml2 leaves doc->encoding NULL
1182            // when the source XML had no `<?xml encoding="…"?>`
1183            // declaration; serializers then omit the encoding
1184            // attribute on output.  The parser explicitly sets this
1185            // when it sees a declaration.
1186            encoding:      std::cell::RefCell::new(String::new()),
1187            standalone:    Cell::new(None),
1188            base_url:      std::cell::RefCell::new(None),
1189            html_metadata: std::cell::RefCell::new(None),
1190            source_ptr:    Cell::new(std::ptr::null_mut()),
1191            source_len:    Cell::new(0),
1192            prolog_orphans:   RefCell::new(Vec::new()),
1193            epilogue_orphans: RefCell::new(Vec::new()),
1194        }
1195    }
1196
1197    /// Stash an owned source buffer that arena strings may borrow from.
1198    /// The parser calls this with the (possibly transcoded) input bytes so
1199    /// that subsequent [`alloc_str_borrow`](Self::alloc_str_borrow) calls
1200    /// can hand back zero-copy `&str` slices into these bytes instead of
1201    /// memcpy'ing them into the arena.
1202    ///
1203    /// Ownership transfers to the [`Document`] on [`build`](Self::build),
1204    /// so the borrowed slices stay valid for the document's lifetime.
1205    /// Calling `set_source` twice on the same builder is allowed and
1206    /// frees the prior buffer.
1207    pub fn set_source(&self, bytes: Box<[u8]>) {
1208        // Free any previous source first.
1209        self.free_source();
1210        let leaked: &'static mut [u8] = Box::leak(bytes);
1211        self.source_ptr.set(leaked.as_mut_ptr());
1212        self.source_len.set(leaked.len());
1213    }
1214
1215    /// Free the leaked source bytes (if any).  Used by `Drop` and by
1216    /// `set_source` for replace semantics.
1217    fn free_source(&self) {
1218        let ptr = self.source_ptr.get();
1219        let len = self.source_len.get();
1220        if !ptr.is_null() {
1221            // SAFETY: `ptr` came from `Box::leak`'d `Box<[u8]>` of length `len`.
1222            // Recover the Box and drop it.
1223            unsafe {
1224                let _: Box<[u8]> = Box::from_raw(
1225                    std::slice::from_raw_parts_mut(ptr, len) as *mut [u8]
1226                );
1227            }
1228            self.source_ptr.set(std::ptr::null_mut());
1229            self.source_len.set(0);
1230        }
1231    }
1232
1233    /// Raw mutable pointer to the stashed source buffer.  Returns null
1234    /// if no source has been set.  Used by `parse_bytes_in_place` to
1235    /// construct a `&mut [u8]` view into the leaked buffer that the
1236    /// in-place reader will mutate.  Not part of the public stable API
1237    /// — the parser is the only intended caller.
1238    #[doc(hidden)]
1239    pub fn source_ptr_for_inplace(&self) -> *mut u8 {
1240        self.source_ptr.get()
1241    }
1242    /// Companion to [`source_ptr_for_inplace`].
1243    #[doc(hidden)]
1244    pub fn source_len_for_inplace(&self) -> usize {
1245        self.source_len.get()
1246    }
1247
1248    /// Return the stashed source bytes, if any.  Returns a slice whose
1249    /// lifetime is bounded by `&self` — but in practice the bytes live
1250    /// at a stable heap address until [`build`](Self::build) moves
1251    /// ownership of them to the [`Document`].
1252    pub fn source(&self) -> Option<&[u8]> {
1253        let ptr = self.source_ptr.get();
1254        let len = self.source_len.get();
1255        if ptr.is_null() {
1256            None
1257        } else {
1258            // SAFETY: `ptr` came from `Box::leak`, points at `len` valid
1259            // bytes that we own.  The returned slice is bounded by
1260            // `&self`'s lifetime; it stays valid until `build()` is
1261            // called (which transfers the pointer to a `Document` whose
1262            // own `Drop` will eventually free the bytes).
1263            Some(unsafe { std::slice::from_raw_parts(ptr, len) })
1264        }
1265    }
1266
1267    /// Set the XML declaration version (e.g. `"1.0"`, `"1.1"`).  Default is
1268    /// `"1.0"`.  Plumbed into [`Document::version`] on [`build`](Self::build).
1269    pub fn set_version(&self, v: impl Into<String>) {
1270        *self.version.borrow_mut() = v.into();
1271    }
1272
1273    /// Set the XML declaration encoding (e.g. `"UTF-8"`).  Default is
1274    /// `"UTF-8"`.  Plumbed into [`Document::encoding`] on [`build`](Self::build).
1275    pub fn set_encoding(&self, e: impl Into<String>) {
1276        *self.encoding.borrow_mut() = e.into();
1277    }
1278
1279    /// Set the URI the document is being loaded from.  Plumbed into
1280    /// [`Document::base_url`] on [`build`](Self::build).
1281    pub fn set_base_url(&self, uri: Option<String>) {
1282        *self.base_url.borrow_mut() = uri;
1283    }
1284
1285    /// Set the XML declaration `standalone="…"` value.  `None` means the
1286    /// declaration did not include `standalone`; `Some(true)` / `Some(false)`
1287    /// correspond to `standalone="yes"` / `standalone="no"`.
1288    pub fn set_standalone(&self, s: Option<bool>) {
1289        self.standalone.set(s);
1290    }
1291
1292    /// Attach HTML-specific document metadata.  Used by the HTML parser sink
1293    /// to record quirks-mode and DOCTYPE info; XML callers leave this as
1294    /// `None` (the default).  Plumbed into [`Document::html_metadata`] on
1295    /// [`build`](Self::build).
1296    pub fn set_html_metadata(&self, m: Option<HtmlMeta>) {
1297        *self.html_metadata.borrow_mut() = m;
1298    }
1299
1300    /// Direct access to the underlying [`Bump`].  Use sparingly — most allocation
1301    /// should go through the typed [`new_element`](Self::new_element) etc. methods.
1302    pub fn bump(&self) -> &Bump { &self.bump }
1303
1304    /// Copy `s` into the arena and return an arena-lifetime slice.  When the
1305    /// caller can prove `s` already lives at least as long as the eventual
1306    /// [`Document`] (e.g. it borrows from the input string slice that the
1307    /// caller will keep alive), [`alloc_str_borrow`](Self::alloc_str_borrow)
1308    /// is cheaper — no copy.
1309    pub fn alloc_str<'a>(&'a self, s: &str) -> &'a str {
1310        self.bump.alloc_str(s)
1311    }
1312
1313    /// Pass through a `&str` that the caller has guaranteed lives at least
1314    /// until the [`Document`] drops.  Typically the input source slice.
1315    /// Zero-copy.
1316    ///
1317    /// # Safety
1318    ///
1319    /// The caller must guarantee `s` outlives the returned reference.  In
1320    /// practice this means `s` borrows from the same input the parser is
1321    /// reading and the [`Document`] will be tied to that same input via the
1322    /// caller's outer lifetime.  For untrusted lifetimes use [`alloc_str`](Self::alloc_str).
1323    pub unsafe fn alloc_str_borrow<'a>(&'a self, s: &'a str) -> &'a str {
1324        // SAFETY: extending the lifetime from the caller's '_ to 'a (which is
1325        // 'self-bounded) is sound because the caller guarantees s outlives 'a.
1326        unsafe { &*(s as *const str) }
1327    }
1328
1329    /// Construct a new node with the given `kind`, `name`, and `content`.
1330    /// Internal helper — public builder methods call this with the right
1331    /// shape for each kind.  Centralises the field-init dance so the
1332    /// cfg-gated layouts only diverge in one place.
1333    fn new_node_impl<'a>(
1334        &'a self,
1335        kind: NodeKind,
1336        name: &'a str,
1337        content: Option<&'a str>,
1338    ) -> &'a mut Node<'a> {
1339        #[cfg(not(feature = "c-abi"))]
1340        {
1341            self.bump.alloc(Node {
1342                kind,
1343                name,
1344                namespace:       Cell::new(None),
1345                first_attribute: Cell::new(None),
1346                last_attribute:  Cell::new(None),
1347                first_child:     Cell::new(None),
1348                last_child:      Cell::new(None),
1349                parent:          Cell::new(None),
1350                next_sibling:    Cell::new(None),
1351                prev_sibling:    Cell::new(None),
1352                content:         Cell::new(content),
1353                line:            0,
1354                source_offset:   0,
1355            })
1356        }
1357        #[cfg(feature = "c-abi")]
1358        {
1359            // Names dedup through the dict (pointer-equal across
1360            // duplicate tags); content stays in the arena (rarely
1361            // repeats).
1362            // Text / CData nodes pin `name` to the libxml2
1363            // `xmlStringText` / `xmlStringTextNoenc` statics — C
1364            // consumers (libxslt's xsltCopyText, lxml's smart-string
1365            // wrapping) compare against those by pointer to identify
1366            // text-kinds.  Any other `name` would silently break the
1367            // dispatch and surface as `Internal error in xsltCopyText`.
1368            let name_c = match kind {
1369                NodeKind::Text | NodeKind::CData => ArenaCStr::text_name(),
1370                _ if name.is_empty() => ArenaCStr::empty(),
1371                _ => self.intern_arena_cstr(name),
1372            };
1373            let content_c = content.map(|c| if c.is_empty() { ArenaCStr::empty() } else { self.alloc_arena_cstr(c) });
1374            self.bump.alloc(Node {
1375                _private:        Cell::new(std::ptr::null_mut()),
1376                kind,
1377                _pad_kind:       0,
1378                name:            name_c,
1379                first_child:     Cell::new(None),
1380                last_child:      Cell::new(None),
1381                parent:          Cell::new(None),
1382                next_sibling:    Cell::new(None),
1383                prev_sibling:    Cell::new(None),
1384                doc:             Cell::new(std::ptr::null_mut()),
1385                namespace:       Cell::new(None),
1386                content:         Cell::new(content_c),
1387                first_attribute: Cell::new(None),
1388                ns_def:          Cell::new(None),
1389                psvi:            Cell::new(std::ptr::null_mut()),
1390                line:            0,
1391                extra:           0,
1392                _pad_extra:      [0u8; 4],
1393                last_attribute:  Cell::new(None),
1394                full_line:       0,
1395                source_offset:   0,
1396            })
1397        }
1398    }
1399
1400    pub fn new_element<'a>(&'a self, name: &'a str) -> &'a mut Node<'a> {
1401        self.new_node_impl(NodeKind::Element, name, None)
1402    }
1403
1404    pub fn new_text<'a>(&'a self, content: &'a str) -> &'a mut Node<'a> {
1405        self.new_node_impl(NodeKind::Text, "", Some(content))
1406    }
1407
1408    pub fn new_cdata<'a>(&'a self, content: &'a str) -> &'a mut Node<'a> {
1409        self.new_node_impl(NodeKind::CData, "", Some(content))
1410    }
1411
1412    pub fn new_comment<'a>(&'a self, content: &'a str) -> &'a mut Node<'a> {
1413        self.new_node_impl(NodeKind::Comment, "", Some(content))
1414    }
1415
1416    /// Build a processing-instruction node.  `content` is `None` for a
1417    /// PI with no data section (`<?foo?>`) and `Some` — possibly `""` —
1418    /// for one that has one (`<?foo?>` created via `xmlNewDocPI` with an
1419    /// empty string).  The distinction is libxml2's NULL-vs-empty
1420    /// `content` and governs the trailing space the serializer emits.
1421    pub fn new_pi<'a>(&'a self, target: &'a str, content: Option<&'a str>) -> &'a mut Node<'a> {
1422        self.new_node_impl(NodeKind::Pi, target, content)
1423    }
1424
1425    /// Build a DTD internal-subset declaration node.  `content` is the
1426    /// raw markup declarations (each newline-terminated), emitted
1427    /// verbatim by the serializer inside the DOCTYPE's `[ … ]`.  Held
1428    /// as the single child of the internal-subset DTD node.
1429    pub fn new_dtd_decl<'a>(&'a self, content: &'a str) -> &'a mut Node<'a> {
1430        self.new_node_impl(NodeKind::DtdDecl, "", Some(content))
1431    }
1432
1433    /// Allocate an empty document-fragment node.  Used by the libxml2
1434    /// compat shim's `xmlNewDocFragment`; the fragment is a transparent
1435    /// container that holds an ordered child list before being grafted
1436    /// into a real document subtree.
1437    pub fn new_fragment<'a>(&'a self) -> &'a mut Node<'a> {
1438        self.new_node_impl(NodeKind::DocumentFragment, "", None)
1439    }
1440
1441    /// Build an unresolved entity-reference node.  `name` is the
1442    /// entity's NCName (e.g. `"foo"` for `&foo;`); `content` is the
1443    /// literal source form including the leading `&` and trailing
1444    /// `;`, which the serializer writes verbatim to round-trip the
1445    /// reference back to source.  Emitted by the parser only when
1446    /// `ParseOptions::resolve_entities` is `false`.
1447    pub fn new_entity_ref<'a>(&'a self, name: &'a str, content: &'a str) -> &'a mut Node<'a> {
1448        self.new_node_impl(NodeKind::EntityRef, name, Some(content))
1449    }
1450
1451    pub fn new_attribute<'a>(&'a self, name: &'a str, value: &'a str) -> &'a mut Attribute<'a> {
1452        #[cfg(not(feature = "c-abi"))]
1453        {
1454            self.bump.alloc(Attribute {
1455                name,
1456                namespace: Cell::new(None),
1457                value,
1458                next:      Cell::new(None),
1459                prev:      Cell::new(None),
1460                parent:    Cell::new(None),
1461            })
1462        }
1463        #[cfg(feature = "c-abi")]
1464        {
1465            // Materialise a text-node child holding `value` so
1466            // libxml2 ABI consumers (libxslt, lxml's XPath etc.)
1467            // that read `attr->children->content` directly see the
1468            // attribute's value through the documented C path,
1469            // not just our sup-xml-only `value` tail field.
1470            //
1471            // Without this, libxslt walks attribute children
1472            // looking for the text node, finds NULL, and treats
1473            // every attribute value as empty — surfacing as
1474            // "could not compile select expression ''" errors when
1475            // libxslt parses a stylesheet through our shim.
1476            let text_child: &Node = self.new_text(value);
1477            self.bump.alloc(Attribute {
1478                _private:  Cell::new(std::ptr::null_mut()),
1479                kind:      NodeKind::Attribute,
1480                _pad_kind: 0,
1481                name:      self.intern_arena_cstr(name),
1482                children:  Cell::new(Some(text_child)),
1483                last:      Cell::new(Some(text_child)),
1484                parent:    Cell::new(None),
1485                next:      Cell::new(None),
1486                prev:      Cell::new(None),
1487                doc:       Cell::new(std::ptr::null_mut()),
1488                namespace: Cell::new(None),
1489                atype:     0,
1490                _pad_atype: 0,
1491                psvi:      Cell::new(std::ptr::null_mut()),
1492                value:     self.alloc_arena_cstr(value),
1493            })
1494        }
1495    }
1496
1497    /// Chain `ns` onto `el`'s `ns_def` list in document order
1498    /// (last-in-list ordering — libxml2's `xmlNewNs` does the same).
1499    /// c-abi-only because the lean Namespace has no `next` field.
1500    #[cfg(feature = "c-abi")]
1501    pub fn append_ns_def<'a>(&'a self, el: &'a Node<'a>, ns: &'a Namespace<'a>) {
1502        match el.ns_def.get() {
1503            None => el.ns_def.set(Some(ns)),
1504            Some(head) => {
1505                // Walk to the tail of the chain and link there.
1506                let mut cur = head;
1507                while let Some(n) = cur.next.get() {
1508                    cur = n;
1509                }
1510                cur.next.set(Some(ns));
1511            }
1512        }
1513    }
1514
1515    pub fn new_namespace<'a>(&'a self, prefix: Option<&'a str>, href: &'a str) -> &'a Namespace<'a> {
1516        #[cfg(not(feature = "c-abi"))]
1517        {
1518            self.bump.alloc(Namespace { prefix, href })
1519        }
1520        #[cfg(feature = "c-abi")]
1521        {
1522            // c-abi: stamp NUL-terminated copies into the arena so
1523            // `as_ptr()` is a valid `xmlChar*`.  The full libxml2-shape
1524            // _xmlNs needs `_private`, `next`, `kind` slots populated
1525            // too — `next` is None at creation and gets stitched up
1526            // by the parser when chaining onto `node->ns_def`.
1527            // Namespace URI + prefix go through the dict — XML
1528            // commonly has many elements sharing the same xmlns,
1529            // and pointer-equal namespaces let consumers do
1530            // O(1) "same namespace?" checks across the tree.
1531            let href_c = self.intern_arena_cstr(href);
1532            let prefix_c = prefix.map(|p| self.intern_arena_cstr(p));
1533            self.bump.alloc(Namespace {
1534                next:     Cell::new(None),
1535                kind:     18,  // XML_LOCAL_NAMESPACE
1536                _pad_kind: 0,
1537                href:     href_c,
1538                prefix:   prefix_c,
1539                _private: Cell::new(std::ptr::null_mut()),
1540                context:  Cell::new(std::ptr::null_mut()),
1541            })
1542        }
1543    }
1544
1545    /// Allocate a NUL-terminated copy of `s` in the arena, returning
1546    /// an [`ArenaCStr`] pointing at the start byte.  C-ABI-only.
1547    ///
1548    /// Used for *values* — text content, attribute values, etc. —
1549    /// which are typically unique per occurrence and don't benefit
1550    /// from dedup.  For *names* (element / attribute / namespace
1551    /// names) prefer [`intern_arena_cstr`](Self::intern_arena_cstr)
1552    /// so consumers get stable pointer-equality across identical
1553    /// names without paying repeated arena copies.
1554    #[cfg(feature = "c-abi")]
1555    fn alloc_arena_cstr<'a>(&'a self, s: &str) -> ArenaCStr<'a> {
1556        // Allocate len + 1 bytes, copy in s, NUL the last byte.
1557        let bytes = s.as_bytes();
1558        let dst: &mut [u8] = self.bump.alloc_slice_fill_with(bytes.len() + 1, |i| {
1559            if i < bytes.len() { bytes[i] } else { 0 }
1560        });
1561        // SAFETY: dst is bytes.len()+1 long with trailing 0; valid UTF-8
1562        // by construction (input was &str).
1563        unsafe { ArenaCStr::from_raw(dst.as_ptr()) }
1564    }
1565
1566    /// Intern `s` through the per-document name dict, returning a
1567    /// canonical [`ArenaCStr`] that is byte-equal for any identical
1568    /// input.  Use this for any string a downstream consumer might
1569    /// pointer-compare (element / attribute / namespace names) or
1570    /// might pass to a "free if not dict-owned" path.  C-ABI-only.
1571    ///
1572    /// Repeated calls with the same bytes return the same pointer
1573    /// in O(1) amortised; on a miss the dict pays one allocation.
1574    /// Strings live until the owning document drops.
1575    #[cfg(feature = "c-abi")]
1576    fn intern_arena_cstr<'a>(&'a self, s: &str) -> ArenaCStr<'a> {
1577        // SAFETY: self.dict is a refcount-managed pointer owned by
1578        // this struct for as long as &self is live; we hold a
1579        // reference (drop releases it).  Dict::intern_str returns a
1580        // pointer into one of the dict's own Box<[u8]>s, valid for
1581        // the dict's lifetime.
1582        let ptr = unsafe { (*self.dict).intern_str(s) };
1583        unsafe { ArenaCStr::from_raw(ptr) }
1584    }
1585
1586    /// Append `child` as the last child of `parent`.  Sets `parent`/sibling
1587    /// pointers consistently.
1588    ///
1589    /// # Panics
1590    ///
1591    /// Panics if `child` is already attached somewhere (its `parent` is not
1592    /// `None`) — callers should detach first.  We treat double-attach as a
1593    /// builder bug, not a recoverable error.
1594    pub fn append_child<'a>(&'a self, parent: &'a Node<'a>, child: &'a Node<'a>) {
1595        debug_assert!(child.parent.get().is_none(), "append_child: child is already attached");
1596        child.parent.set(Some(parent));
1597        match parent.last_child.get() {
1598            None => {
1599                parent.first_child.set(Some(child));
1600                parent.last_child.set(Some(child));
1601            }
1602            Some(prev_last) => {
1603                prev_last.next_sibling.set(Some(child));
1604                child.prev_sibling.set(Some(prev_last));
1605                parent.last_child.set(Some(child));
1606            }
1607        }
1608    }
1609
1610    /// Append `attr` to the end of `element`'s attribute list.  Sets the
1611    /// attribute's `parent` and links siblings.
1612    pub fn append_attribute<'a>(&'a self, element: &'a Node<'a>, attr: &'a Attribute<'a>) {
1613        debug_assert!(element.is_element(), "append_attribute: not an element");
1614        debug_assert!(attr.parent.get().is_none(), "append_attribute: attr already attached");
1615        attr.parent.set(Some(element));
1616        match element.last_attribute.get() {
1617            None => {
1618                element.first_attribute.set(Some(attr));
1619                element.last_attribute.set(Some(attr));
1620            }
1621            Some(prev_last) => {
1622                prev_last.next.set(Some(attr));
1623                attr.prev.set(Some(prev_last));
1624                element.last_attribute.set(Some(attr));
1625            }
1626        }
1627    }
1628
1629    /// Detach `child` from its current parent (no-op if already detached).
1630    /// Repairs sibling links on the parent's child list.
1631    pub fn detach<'a>(&'a self, child: &'a Node<'a>) {
1632        let Some(parent) = child.parent.get() else { return; };
1633        let prev = child.prev_sibling.get();
1634        let next = child.next_sibling.get();
1635        match prev {
1636            Some(p) => p.next_sibling.set(next),
1637            None    => parent.first_child.set(next),
1638        }
1639        match next {
1640            Some(n) => n.prev_sibling.set(prev),
1641            None    => parent.last_child.set(prev),
1642        }
1643        child.parent.set(None);
1644        child.prev_sibling.set(None);
1645        child.next_sibling.set(None);
1646    }
1647
1648    /// Record an orphan leaf (comment / PI) that appeared in the
1649    /// document's prolog (before the root element opened).  Linked
1650    /// as `root.prev_sibling` chain on [`build`](Self::build).
1651    pub fn attach_prolog_orphan<'a>(&'a self, node: &'a Node<'a>) {
1652        let p: *const Node<'static> = node as *const _ as *const Node<'static>;
1653        self.prolog_orphans.borrow_mut().push(p);
1654    }
1655
1656    /// Record an orphan leaf (comment / PI) that appeared in the
1657    /// document's epilogue (after `</root>`).  Linked as
1658    /// `root.next_sibling` chain on [`build`](Self::build).
1659    pub fn attach_epilogue_orphan<'a>(&'a self, node: &'a Node<'a>) {
1660        let p: *const Node<'static> = node as *const _ as *const Node<'static>;
1661        self.epilogue_orphans.borrow_mut().push(p);
1662    }
1663
1664    /// Mark `root` as the document's root element.  Call before [`build`](Self::build).
1665    /// The borrow on `&self` only lives for this call, so subsequent
1666    /// `build()` can freely consume the builder.
1667    pub fn set_root<'a>(&'a self, root: &'a Node<'a>) {
1668        // SAFETY: erasing 'a → 'static is sound because:
1669        //   - `root` borrows from `self.bump`, which we own.
1670        //   - On `build()` we move `self.bump` into the `Document`, where it
1671        //     remains pinned in heap memory.  The pointer stays valid.
1672        //   - The Cell type prevents anyone from reading the raw pointer with
1673        //     a longer lifetime than the eventual `Document::root()` call,
1674        //     which re-binds to `&self`.
1675        let p: *const Node<'static> = root as *const _ as *const Node<'static>;
1676        self.root.set(p);
1677    }
1678
1679    /// Finalize the build.  Must be called after [`set_root`](Self::set_root).
1680    ///
1681    /// # Panics
1682    ///
1683    /// Panics if `set_root` was never called.
1684    pub fn build(self) -> Document {
1685        let root = self.root.get();
1686        assert!(!root.is_null(),
1687            "DocumentBuilder::build called without set_root — call set_root(node) first");
1688        // Wire any prolog/epilogue orphan leaves (comments/PIs from
1689        // outside the root) as siblings of `root` so the resulting
1690        // document mirrors libxml2's children list: prolog → root →
1691        // epilogue.  No-op for the common case (no out-of-root
1692        // content).
1693        //
1694        // SAFETY: each entry was registered via `attach_orphan` with a
1695        // pointer into this builder's arena, which moves into the
1696        // returned Document and stays valid for its lifetime.
1697        let first_sibling: *const Node<'static> = unsafe {
1698            link_doc_level_orphans(
1699                root,
1700                &self.prolog_orphans.borrow(),
1701                &self.epilogue_orphans.borrow(),
1702            )
1703        };
1704        // We have a `Drop` impl on `DocumentBuilder` (to free the leaked
1705        // source bytes when build() is *not* called).  That Drop blocks
1706        // by-value move-out of fields, so we use the standard
1707        // ManuallyDrop + ptr::read pattern: suppress Drop, then move each
1708        // owned field out by raw pointer.
1709        let s = std::mem::ManuallyDrop::new(self);
1710        let source_ptr = s.source_ptr.get();
1711        let source_len = s.source_len.get();
1712        let standalone = s.standalone.get();
1713        // SAFETY: ManuallyDrop suppresses the destructor; each owned field
1714        // is read exactly once and ownership is transferred either to a
1715        // local binding (then into the returned Document) or explicitly
1716        // dropped here.  Final destination is the returned Document, which
1717        // now owns these fields (including the source buffer, freed by
1718        // Document's Drop).
1719        let bump          = unsafe { std::ptr::read(&s.bump) };
1720        let version       = unsafe { std::ptr::read(&s.version) }.into_inner();
1721        let encoding      = unsafe { std::ptr::read(&s.encoding) }.into_inner();
1722        let html_metadata = unsafe { std::ptr::read(&s.html_metadata) }.into_inner();
1723        let base_url      = unsafe { std::ptr::read(&s.base_url) }.into_inner();
1724        // The orphan Vecs were consumed above by `link_doc_level_orphans`.
1725        // Their contents (the *const Node pointers) are now wired into the
1726        // document, but the Vec's heap-allocated buffer itself still needs
1727        // to be freed — ManuallyDrop suppresses the field-level drop, so
1728        // read them out into local bindings that drop at scope end.
1729        let _prolog_orphans:   std::cell::RefCell<Vec<*const Node<'static>>>
1730            = unsafe { std::ptr::read(&s.prolog_orphans) };
1731        let _epilogue_orphans: std::cell::RefCell<Vec<*const Node<'static>>>
1732            = unsafe { std::ptr::read(&s.epilogue_orphans) };
1733        // Transfer the refcounted dict pointer.  No add_ref needed
1734        // — the builder's reference becomes the document's.
1735        #[cfg(feature = "c-abi")]
1736        let dict          = s.dict;
1737        Document {
1738            bump,
1739            #[cfg(feature = "c-abi")]
1740            #[cfg(feature = "c-abi")]
1741            dict,
1742            root,
1743            first_sibling,
1744            version,
1745            encoding,
1746            standalone,
1747            html_metadata,
1748            source_ptr,
1749            source_len,
1750            unparsed_entities: std::sync::Arc::new(std::collections::HashMap::new()),
1751            id_attributes:     std::sync::Arc::new(std::collections::HashMap::new()),
1752            idref_attributes:  std::sync::Arc::new(std::collections::HashMap::new()),
1753            base_url,
1754        }
1755    }
1756}
1757
1758/// Link prolog/epilogue orphan leaves as siblings of `root` and
1759/// return the first node in the resulting sibling chain (either the
1760/// first prolog node, or `root` if there is no prolog).
1761///
1762/// # Safety
1763///
1764/// `root` and every entry in `prolog` / `epilogue` must be valid
1765/// pointers into the same arena that the returned chain will live
1766/// in.  Lifetimes are erased to `'static` for storage; callers must
1767/// ensure the arena outlives all reads.
1768unsafe fn link_doc_level_orphans(
1769    root: *const Node<'static>,
1770    prolog: &[*const Node<'static>],
1771    epilogue: &[*const Node<'static>],
1772) -> *const Node<'static> {
1773    if prolog.is_empty() && epilogue.is_empty() {
1774        return root;
1775    }
1776    // SAFETY: `root` is a non-null pointer into the arena; the
1777    // returned reference borrows from a 'static-erased pointer but
1778    // is only used to thread sibling links here.
1779    let root_ref: &Node<'static> = unsafe { &*root };
1780    // Prolog: chain prev_sibling links so the first prolog entry
1781    // becomes the head, then ... → root.
1782    let mut prev_node: Option<&Node<'static>> = None;
1783    for &p in prolog {
1784        let n: &Node<'static> = unsafe { &*p };
1785        if let Some(pv) = prev_node {
1786            n.prev_sibling.set(Some(pv));
1787            pv.next_sibling.set(Some(n));
1788        }
1789        prev_node = Some(n);
1790    }
1791    if let Some(last_prolog) = prev_node {
1792        last_prolog.next_sibling.set(Some(root_ref));
1793        root_ref.prev_sibling.set(Some(last_prolog));
1794    }
1795    // Epilogue: chain next_sibling links after root.
1796    let mut prev_node = Some(root_ref);
1797    for &p in epilogue {
1798        let n: &Node<'static> = unsafe { &*p };
1799        if let Some(pv) = prev_node {
1800            pv.next_sibling.set(Some(n));
1801            n.prev_sibling.set(Some(pv));
1802        }
1803        prev_node = Some(n);
1804    }
1805    // First sibling is either the first prolog entry or root.
1806    if let Some(&first) = prolog.first() { first } else { root }
1807}
1808
1809impl Default for DocumentBuilder {
1810    fn default() -> Self { Self::new() }
1811}
1812
1813impl Drop for DocumentBuilder {
1814    fn drop(&mut self) {
1815        // If `build()` wasn't called, the leaked source bytes are still ours.
1816        // `free_source` is a no-op when the pointer is null (post-`build`).
1817        self.free_source();
1818        // Release our dict reference.  When `build()` is called the
1819        // dict pointer is transferred to the Document via `ptr::read`
1820        // and our drop only fires when `build` ISN'T called — so we
1821        // need to release here to balance the `new()` add-ref.
1822        //
1823        // build() uses ManuallyDrop, so our drop doesn't fire after
1824        // a successful build.
1825        #[cfg(feature = "c-abi")]
1826        unsafe {
1827            if !self.dict.is_null() {
1828                crate::dict::Dict::release(self.dict);
1829            }
1830        }
1831    }
1832}
1833
1834// ── document (self-ref wrapper) ─────────────────────────────────────────────
1835
1836/// An owned XML document with an arena-allocated tree.
1837///
1838/// An unparsed external general entity declared with an `NDATA`
1839/// annotation (XML 1.0 § 4.2.2): `<!ENTITY name SYSTEM "uri" NDATA n>`
1840/// or the `PUBLIC "fpi" "uri"` form.  Backs XSLT's
1841/// `unparsed-entity-uri()` and `unparsed-entity-public-id()`
1842/// (XSLT 1.0 § 12.4).
1843#[derive(Clone, Debug, Default, PartialEq)]
1844pub struct UnparsedEntity {
1845    /// The entity's SYSTEM identifier — the URI a non-XML processor
1846    /// would fetch.  Stored as declared; callers resolve it against
1847    /// the document's base URI.
1848    pub system_id: String,
1849    /// The entity's PUBLIC identifier (FPI), when declared with the
1850    /// `PUBLIC` form; `None` for `SYSTEM`-only declarations.
1851    pub public_id: Option<String>,
1852}
1853
1854/// `Document` owns a [`Bump`] and a pointer to the root [`Node`] inside that
1855/// `Bump`.  The struct is self-referential and the unsafety is *contained* —
1856/// see the module-level docs for the safety argument.
1857///
1858/// Outside this type, all node references are bounded by `&self` so they
1859/// can never escape the `Document`.
1860pub struct Document {
1861    // SAFETY-RELEVANT FIELD ORDER: `root` is dropped before `bump` (Rust drops
1862    // fields in declaration order), but neither field needs Drop, so the order
1863    // is academic — bumpalo's Drop on `bump` walks its own chunks; `root` is
1864    // just a raw pointer.  Keeping the order anyway as a defensive measure.
1865    root: *const Node<'static>,
1866    /// First sibling in the document's top-level chain — equals
1867    /// `root` when the document has no prolog/epilogue content
1868    /// (the common case), or points to the first prolog comment /
1869    /// PI otherwise.  Walking `next_sibling` from here visits
1870    /// every document-level node in source order.
1871    ///
1872    /// Used by the C-ABI shim's `XmlDoc.children` field (which
1873    /// libxml2 consumers walk to find prolog + root + epilogue)
1874    /// and by the serializer's `Document` write path.
1875    first_sibling: *const Node<'static>,
1876    /// Refcounted heap allocation.  See [`DocumentBuilder::bump`] for the
1877    /// rationale.  Multiple documents created on the same thread
1878    /// share this same `Arc<Bump>` — node memory survives any
1879    /// individual doc's drop and the libxml2-style cross-doc graft
1880    /// (lxml's `_appendChild` / `moveNodeToDocument`) is safe by
1881    /// construction.
1882    bump: Arc<Bump>,
1883    /// Per-document name interner.  Element / attribute / namespace
1884    /// names point into the boxes this dict owns; pointer equality
1885    /// across identical names matters to C-ABI consumers that
1886    /// pointer-compare names or check "did this string come from
1887    /// the dict?" before freeing.
1888    ///
1889    /// Refcount-managed (see [`crate::dict::Dict`]) — the underlying
1890    /// dict may be shared with the parser context that produced this
1891    /// document.  Document owns one reference; drop releases it.
1892    #[cfg(feature = "c-abi")]
1893    dict: *mut crate::dict::Dict,
1894    /// XML declaration version (e.g. `"1.0"`).  Defaults to `"1.0"` when
1895    /// the document had no `<?xml ... ?>` declaration.
1896    pub version:    String,
1897    /// XML declaration encoding (e.g. `"UTF-8"`).  Defaults to `"UTF-8"`
1898    /// when the declaration omitted `encoding=…` or was absent entirely.
1899    pub encoding:   String,
1900    /// XML declaration `standalone="…"` value, or `None` when absent.
1901    pub standalone: Option<bool>,
1902    /// HTML-specific metadata when this document was produced by an HTML
1903    /// parser; `None` for XML documents.  Use [`Document::is_html`] to
1904    /// discriminate.
1905    pub html_metadata: Option<HtmlMeta>,
1906    /// Owned source bytes (raw pointer + length) that arena strings may
1907    /// point into via the parser's borrow-from-source optimization.  The
1908    /// buffer is heap-allocated via `Box::leak` at parse time; the
1909    /// `Document`'s `Drop` impl reclaims it.
1910    ///
1911    /// **Raw pointer storage is intentional**, not just paranoia.  Using
1912    /// `Pin<Box<[u8]>>` directly causes a Stacked Borrows violation when
1913    /// `DocumentBuilder::build` moves the `Box` field into the
1914    /// `Document` — the move performs a Unique retag of the parent,
1915    /// invalidating any `SharedReadOnly` borrows the parser handed out
1916    /// into the bytes.  Storing as a raw pointer (which is `Copy`) means
1917    /// the build transfer is a pointer copy, not a parent retag, so the
1918    /// borrows survive.  Verified clean under `cargo +nightly miri`.
1919    ///
1920    /// `source_ptr` is null when the parser ran in pure-copy mode
1921    /// (everything alloc_str'd into the bump and no source was stashed).
1922    source_ptr: *mut u8,
1923    source_len: usize,
1924    /// Unparsed external general entities declared in the DTD with
1925    /// an `NDATA` annotation (XML 1.0 § 4.2.2).  Keyed by entity
1926    /// name → SYSTEM identifier.  Populated by the parser when the
1927    /// document carries a `<!DOCTYPE>` with one or more
1928    /// `<!ENTITY name SYSTEM "uri" NDATA notation>` declarations;
1929    /// otherwise empty.  Surfaces through
1930    /// [`Document::unparsed_entity_uri`] for XSLT's
1931    /// `unparsed-entity-uri()` function (XSLT 1.0 § 12.4).  Wrapped
1932    /// in `Arc` so XSLT can share a cheap handle across the
1933    /// transform's lifetime without copying the map per-call.
1934    unparsed_entities: std::sync::Arc<std::collections::HashMap<String, UnparsedEntity>>,
1935    /// DTD-declared ID attribute typing.  Keyed by element name
1936    /// (the parent of the attribute), value is the list of attribute
1937    /// names typed as `ID` in that element's `<!ATTLIST>`.  Empty
1938    /// when the document had no DTD or no ID-typed declarations.
1939    /// Consulted by XPath 1.0 §4.1's `id()` function.
1940    id_attributes: std::sync::Arc<std::collections::HashMap<String, Vec<String>>>,
1941    /// DTD-derived IDREF/IDREFS-attribute map: element-name → attribute
1942    /// names declared `<!ATTLIST e a IDREF>` / `IDREFS`.  Empty when the
1943    /// document had no such declarations.  Consulted by XPath 2.0
1944    /// §14.5.5's `idref()` function.
1945    idref_attributes: std::sync::Arc<std::collections::HashMap<String, Vec<String>>>,
1946    /// URI the document was loaded from, when known — the value of
1947    /// [`ParseOptions::base_url`](crate) at parse time, or the URI a
1948    /// loader resolved for `doc()`/`document()`.  `None` for documents
1949    /// built in memory with no source URI.  Surfaces as the document
1950    /// node's base URI for XPath `fn:base-uri()` / `fn:document-uri()`
1951    /// (XPath 2.0 §2.5, §15.5.3): a source document's base URI is the
1952    /// URI it was retrieved from, independent of the stylesheet's own
1953    /// static base URI.
1954    base_url: Option<String>,
1955}
1956
1957// SAFETY: `Node` and friends contain `Cell<&Node>` which is !Sync.
1958// Document is !Sync as a result.  `Arc<Bump>` is !Send because `Bump`
1959// is !Sync — auto-Send is blocked on that ground.  We re-assert Send
1960// here under the contract that callers serialize all access to the
1961// document (Python GIL on the lxml shim, single-threaded API on the
1962// Rust side).  Moving the Document moves the Arc<Bump>, whose
1963// underlying chunks stay at the same heap address; the root pointer
1964// remains valid.  The raw `source_ptr` is safe to send since the
1965// bytes it points at aren't shared.
1966unsafe impl Send for Document {}
1967
1968impl Drop for Document {
1969    fn drop(&mut self) {
1970        // Drop order: Rust drops `bump` (an `Arc`) after this body
1971        // runs.  The arena only releases its bumpalo memory when
1972        // the last `Arc<Bump>` clone drops — in c-abi compat the
1973        // thread keeps a clone alive until thread exit, so per-doc
1974        // drops are just refcount decrements.
1975        //
1976        // Source bytes: reclaimed unconditionally here.  In c-abi
1977        // mode no node field references them post-parse (names
1978        // intern into the dict, content/values copy into the bump),
1979        // so freeing is safe regardless of who else holds the
1980        // arena.  In the lean build callers that graft nodes
1981        // across documents must keep the source alive themselves —
1982        // we don't try to track those references.
1983        if !self.source_ptr.is_null() {
1984            // SAFETY: `source_ptr` came from `Box::leak`'d
1985            // `Box<[u8]>` of length `source_len` (set in
1986            // `DocumentBuilder::set_source`), and ownership was
1987            // transferred to this `Document` by
1988            // `DocumentBuilder::build`.  No other code frees it.
1989            unsafe {
1990                let _: Box<[u8]> = Box::from_raw(
1991                    std::slice::from_raw_parts_mut(self.source_ptr, self.source_len)
1992                        as *mut [u8]
1993                );
1994            }
1995        }
1996        // Release our dict reference.  Other holders (the parser
1997        // context that originated it, the thread-local dict slot)
1998        // keep it alive; only the last release frees the interned
1999        // strings.
2000        #[cfg(feature = "c-abi")]
2001        unsafe {
2002            if !self.dict.is_null() {
2003                crate::dict::Dict::release(self.dict);
2004            }
2005        }
2006    }
2007}
2008
2009impl Document {
2010    /// The original source bytes this document was parsed from, when the
2011    /// parser stashed them (the borrow-from-source path).  `None` in
2012    /// pure-copy mode or for programmatically built documents.  Element
2013    /// byte offsets ([`Node::source_offset`]) index into this buffer.
2014    pub fn source(&self) -> Option<&[u8]> {
2015        if self.source_ptr.is_null() {
2016            None
2017        } else {
2018            // SAFETY: `source_ptr`/`source_len` describe a `Box::leak`ed
2019            // buffer owned by this `Document` (reclaimed in `Drop`), so it
2020            // stays valid for `&self`.
2021            Some(unsafe { std::slice::from_raw_parts(self.source_ptr, self.source_len) })
2022        }
2023    }
2024
2025    /// The document root.  Lifetime is bound to `&self`, so node references
2026    /// cannot outlive the `Document`.
2027    pub fn root<'a>(&'a self) -> &'a Node<'a> {
2028        // SAFETY: `self.root` points into `self.bump`, which we own.  The
2029        // returned reference is bounded by `&'a self`, so it cannot outlive
2030        // the `Document` — and therefore cannot outlive the `Bump`.  The
2031        // pointer was set via `DocumentBuilder::set_root` from a `&'b Node<'b>`
2032        // borrowed from `self.bump` while it lived in the builder; moving the
2033        // pinned `Bump` from the builder to `Document` did not relocate the
2034        // node (bumpalo allocations have stable addresses).
2035        unsafe { &*(self.root as *const Node<'a>) }
2036    }
2037
2038    /// Approximate bytes of memory the document holds.  Includes every
2039    /// allocation made by the parser (nodes, attributes, interned-style
2040    /// strings, the source slice).  Useful for memory diagnostics.
2041    pub fn memory_bytes(&self) -> usize {
2042        self.bump.allocated_bytes()
2043    }
2044
2045    /// SYSTEM identifier of the unparsed external general entity
2046    /// declared as `<!ENTITY name SYSTEM "uri" NDATA notation>` in
2047    /// the source document's DTD.  Returns `None` when no such
2048    /// entity is declared.  Backs XSLT 1.0 §12.4's
2049    /// `unparsed-entity-uri()` function.
2050    pub fn unparsed_entity_uri(&self, name: &str) -> Option<&str> {
2051        self.unparsed_entities.get(name).map(|e| e.system_id.as_str())
2052    }
2053
2054    /// PUBLIC identifier (FPI) of the unparsed external general entity
2055    /// named `name`, when it was declared with the `PUBLIC` form.
2056    /// Backs XSLT 2.0 §16.6.3's `unparsed-entity-public-id()`.
2057    pub fn unparsed_entity_public_id(&self, name: &str) -> Option<&str> {
2058        self.unparsed_entities.get(name)
2059            .and_then(|e| e.public_id.as_deref())
2060    }
2061
2062    /// String-value of a node previously allocated in *some* document's
2063    /// arena (typically this one) and reachable by raw pointer.  Used
2064    /// by foreign-pointer code paths (XPath's `ForeignNodeSet`, EXSLT
2065    /// `str:tokenize` result nodes) where the type system can't track
2066    /// the lifetime back to a `Document`.  Returns `""` for null.
2067    ///
2068    /// SAFETY-encapsulated: the unsafe deref is contained here.  The
2069    /// caller's contract is that `ptr` was minted by *some* live
2070    /// `Document::new_*` (or this crate's parser) and the underlying
2071    /// arena has not been freed.  Passing a stale or alien pointer
2072    /// is undefined behavior.
2073    pub fn node_string_value_by_ptr(ptr: *const Node<'static>) -> String {
2074        if ptr.is_null() { return String::new(); }
2075        // SAFETY: caller's contract — see method doc.
2076        let n: &Node<'_> = unsafe { &*(ptr as *const Node<'_>) };
2077        n.content().to_string()
2078    }
2079
2080    /// Replace the text content of the node at `node_ptr` with
2081    /// `content` (allocated in this document's arena).
2082    /// SAFETY-encapsulated: the caller's contract is that
2083    /// `node_ptr` was minted by *this* document's `new_*` (so
2084    /// `Cell<…>::set` writes into our own arena's matching
2085    /// lifetime).  Mismatched docs are debug-asserted at the
2086    /// arena boundary.  Silently no-ops on null.
2087    pub fn set_node_text_content_by_ptr(&self, node_ptr: *const Node<'static>, content: &str) {
2088        if node_ptr.is_null() { return; }
2089        // SAFETY: caller's contract — `node_ptr` came from this doc's `new_*`.
2090        let node: &Node<'_> = unsafe { &*(node_ptr as *const Node<'_>) };
2091        self.set_node_text_content(node, content);
2092    }
2093
2094    /// Replace the text content of `node` with `content` (allocated
2095    /// in this document's arena).  Safe wrapper around the
2096    /// `Cell<…>`-typed content field — handles both the lean
2097    /// (`Cell<&str>`) and the c-abi (`Cell<ArenaCStr>`) builds.
2098    /// `node` must be a `Text` / `CData` / `Comment` / `Pi` node
2099    /// that lives in *this* document's arena; mismatched docs
2100    /// will silently store a pointer that drops with the wrong
2101    /// arena (debug-asserted to catch misuse early).
2102    pub fn set_node_text_content<'a>(&'a self, node: &'a Node<'a>, content: &str) {
2103        #[cfg(not(feature = "c-abi"))]
2104        {
2105            let s: &'a str = self.bump.alloc_str(content);
2106            node.content.set(Some(s));
2107        }
2108        #[cfg(feature = "c-abi")]
2109        {
2110            let dst: &mut [u8] = self.bump.alloc_slice_fill_with(content.len() + 1, |i| {
2111                if i < content.len() { content.as_bytes()[i] } else { 0 }
2112            });
2113            // SAFETY: `dst` is a NUL-terminated UTF-8 slice owned by the
2114            // arena.  `ArenaCStr::from_raw` requires exactly that.
2115            let new_content = unsafe { ArenaCStr::from_raw(dst.as_ptr()) };
2116            node.content.set(Some(new_content));
2117        }
2118    }
2119
2120    /// Borrow the full unparsed-entity map by reference.  Cheap to
2121    /// clone (it's an `Arc`); used by the XSLT engine to capture a
2122    /// snapshot for its function dispatcher.
2123    pub fn unparsed_entities(&self) -> &std::sync::Arc<std::collections::HashMap<String, UnparsedEntity>> {
2124        &self.unparsed_entities
2125    }
2126
2127    /// Replace the unparsed-entity table.  Called by the parser
2128    /// after DTD ingestion; not part of the stable public surface.
2129    #[doc(hidden)]
2130    pub fn set_unparsed_entities(
2131        &mut self,
2132        map: std::collections::HashMap<String, UnparsedEntity>,
2133    ) {
2134        self.unparsed_entities = std::sync::Arc::new(map);
2135    }
2136
2137    /// Borrow the DTD-derived ID-attribute map: element-name →
2138    /// list of attribute names declared with `<!ATTLIST e a ID>`.
2139    /// Empty when the document had no DTD-typed ID attributes.
2140    pub fn id_attributes(
2141        &self,
2142    ) -> &std::sync::Arc<std::collections::HashMap<String, Vec<String>>> {
2143        &self.id_attributes
2144    }
2145
2146    /// Replace the ID-attribute map.  Called by the parser after DTD
2147    /// ingestion; not part of the stable public surface.
2148    #[doc(hidden)]
2149    pub fn set_id_attributes(
2150        &mut self,
2151        map: std::collections::HashMap<String, Vec<String>>,
2152    ) {
2153        self.id_attributes = std::sync::Arc::new(map);
2154    }
2155
2156    /// Borrow the DTD-derived IDREF-attribute map: element-name → list
2157    /// of attribute names declared `<!ATTLIST e a IDREF>` / `IDREFS`.
2158    /// Empty when the document had no DTD-typed IDREF attributes.
2159    pub fn idref_attributes(
2160        &self,
2161    ) -> &std::sync::Arc<std::collections::HashMap<String, Vec<String>>> {
2162        &self.idref_attributes
2163    }
2164
2165    /// Replace the IDREF-attribute map.  Called by the parser after DTD
2166    /// ingestion; not part of the stable public surface.
2167    #[doc(hidden)]
2168    pub fn set_idref_attributes(
2169        &mut self,
2170        map: std::collections::HashMap<String, Vec<String>>,
2171    ) {
2172        self.idref_attributes = std::sync::Arc::new(map);
2173    }
2174
2175    /// URI the document was loaded from, if known.  See the
2176    /// [`base_url`](Self::base_url) field: this is the document node's
2177    /// base URI for `fn:base-uri()` / `fn:document-uri()`, distinct
2178    /// from any host stylesheet's static base URI.
2179    pub fn base_url(&self) -> Option<&str> {
2180        self.base_url.as_deref()
2181    }
2182
2183    /// Record the URI the document was loaded from.  Called by the
2184    /// parser / loader once the source URI is known; not part of the
2185    /// stable public surface.
2186    #[doc(hidden)]
2187    pub fn set_base_url(&mut self, uri: Option<String>) {
2188        self.base_url = uri;
2189    }
2190
2191    /// First sibling in the document's top-level chain (prolog
2192    /// comment / PI, or root if none).  Walking `next_sibling`
2193    /// from here visits every document-level node.  Equivalent to
2194    /// libxml2's `xmlDoc.children`.
2195    pub fn first_sibling<'a>(&'a self) -> &'a Node<'a> {
2196        let p = if self.first_sibling.is_null() { self.root } else { self.first_sibling };
2197        // SAFETY: same invariants as [`root`](Self::root).
2198        unsafe { &*(p as *const Node<'a>) }
2199    }
2200
2201    /// True when this document was produced by an HTML parser.
2202    pub fn is_html(&self) -> bool {
2203        self.html_metadata.is_some()
2204    }
2205
2206    /// Re-point the document's root.  Used by mutation APIs that
2207    /// replace the root post-build (libxml2's `xmlDocSetRootElement`).
2208    ///
2209    /// # Safety
2210    ///
2211    /// `node` must be a valid arena-resident pointer inside `self.bump`,
2212    /// OR NULL.  The previous root pointer is dropped — its target
2213    /// remains allocated in the arena (leaked unless still reachable
2214    /// via the new tree).
2215    pub unsafe fn set_root_ptr(&mut self, node: *const Node<'static>) {
2216        self.root = node;
2217    }
2218
2219    /// Set the document's first top-level node (the head of the
2220    /// document-level sibling chain — prolog comments/PIs precede the
2221    /// root element).  [`first_sibling`](Self::first_sibling) returns
2222    /// this when non-NULL, otherwise it falls back to
2223    /// [`root`](Self::root).
2224    ///
2225    /// # Safety
2226    ///
2227    /// `node` must be a valid arena-resident pointer, or NULL.
2228    pub unsafe fn set_first_sibling_ptr(&mut self, node: *const Node<'static>) {
2229        self.first_sibling = node;
2230    }
2231
2232    /// Direct access to the document's bumpalo arena.
2233    ///
2234    /// Use to allocate new nodes/attributes/strings into the same
2235    /// arena that owns the existing tree.  The caller is responsible
2236    /// for tree-invariant maintenance — e.g. when linking a freshly
2237    /// allocated node into the tree via `append_child`, the new
2238    /// node's parent/sibling pointers must be wired consistently.
2239    pub fn bump(&self) -> &Bump {
2240        &self.bump
2241    }
2242
2243    /// Clone this document's arena handle.  Used by the C-ABI shim to
2244    /// pin a foreign document's arena onto a destination when a node is
2245    /// grafted across documents (cross-thread), so the moved node's
2246    /// memory outlives a drop of its origin document.
2247    #[cfg(feature = "c-abi")]
2248    pub fn bump_arc(&self) -> Arc<Bump> {
2249        Arc::clone(&self.bump)
2250    }
2251
2252    // ── post-parse mutation helpers ──────────────────────────────────
2253    //
2254    // These mirror the `DocumentBuilder::new_*` set so callers can
2255    // allocate additional nodes into an existing `Document`'s arena.
2256    // Same allocation semantics (bumpalo), same field-init dance.
2257
2258    /// Allocate a fresh element node in the document's arena.  The
2259    /// returned node is detached — link it into the tree via
2260    /// [`append_child`](Self::append_child).
2261    pub fn new_element<'a>(&'a self, name: &'a str) -> &'a mut Node<'a> {
2262        self.alloc_node(NodeKind::Element, name, None)
2263    }
2264
2265    /// Allocate a text node.
2266    pub fn new_text<'a>(&'a self, content: &'a str) -> &'a mut Node<'a> {
2267        self.alloc_node(NodeKind::Text, "", Some(content))
2268    }
2269
2270    /// Allocate a CDATA section.
2271    pub fn new_cdata<'a>(&'a self, content: &'a str) -> &'a mut Node<'a> {
2272        self.alloc_node(NodeKind::CData, "", Some(content))
2273    }
2274
2275    /// Allocate a comment node.
2276    pub fn new_comment<'a>(&'a self, content: &'a str) -> &'a mut Node<'a> {
2277        self.alloc_node(NodeKind::Comment, "", Some(content))
2278    }
2279
2280    /// Allocate a processing-instruction node.  `content` is `None` for
2281    /// a PI with no data section, `Some` (possibly `""`) otherwise — see
2282    /// [`DocumentBuilder::new_pi`].
2283    pub fn new_pi<'a>(&'a self, target: &'a str, content: Option<&'a str>) -> &'a mut Node<'a> {
2284        self.alloc_node(NodeKind::Pi, target, content)
2285    }
2286
2287    /// Allocate a DTD internal-subset declaration node (raw markup
2288    /// declarations, newline-terminated).  Mirror of
2289    /// [`DocumentBuilder::new_dtd_decl`] for post-parse construction.
2290    pub fn new_dtd_decl<'a>(&'a self, content: &'a str) -> &'a mut Node<'a> {
2291        self.alloc_node(NodeKind::DtdDecl, "", Some(content))
2292    }
2293
2294    /// Allocate an empty document-fragment node.  Mirror of
2295    /// [`DocumentBuilder::new_fragment`] for post-parse construction.
2296    pub fn new_fragment<'a>(&'a self) -> &'a mut Node<'a> {
2297        self.alloc_node(NodeKind::DocumentFragment, "", None)
2298    }
2299
2300    /// Allocate an unresolved-entity-reference node.  See
2301    /// [`DocumentBuilder::new_entity_ref`] for semantics.
2302    pub fn new_entity_ref<'a>(&'a self, name: &'a str, content: &'a str) -> &'a mut Node<'a> {
2303        self.alloc_node(NodeKind::EntityRef, name, Some(content))
2304    }
2305
2306    /// Deep-copy a subtree from another arena into this document.
2307    ///
2308    /// Despite the name (chosen for familiarity with DOM's `adoptNode`),
2309    /// this is a **copy**, not a move — the source subtree stays in its
2310    /// original arena.  Arenas don't release individual allocations, so
2311    /// a true move isn't representable; in practice consumers either
2312    /// drop the source document afterward (handing ownership semantics)
2313    /// or keep both copies live (template-and-reuse semantics).
2314    ///
2315    /// Walks the source subtree depth-first.  Each foreign element,
2316    /// text, CDATA, comment, PI, entity-reference, or document-fragment
2317    /// node gets a fresh allocation in `self`'s arena.  Attributes are
2318    /// copied alongside their owning element.
2319    ///
2320    /// **Namespaces are not yet copied** — element `namespace` and
2321    /// `ns_def` pointers on the result are left `None`.  Callers that
2322    /// need namespace-aware adoption should set them up after the fact
2323    /// via `bump_new_namespace` + `attach_ns_def` (c-abi build).  A
2324    /// future revision will resolve namespaces by URI against the
2325    /// target document's existing declarations.
2326    ///
2327    /// Returns a fresh detached node — link it into the tree via
2328    /// [`append_child`](Self::append_child).
2329    ///
2330    /// # Examples
2331    ///
2332    /// ```ignore
2333    /// # // ignored: requires building two docs end-to-end
2334    /// let scratch = Document::new();
2335    /// let template = scratch.new_element("metadata");
2336    /// // ... build out template subtree ...
2337    ///
2338    /// let real_doc = parse_str("<root/>", &ParseOptions::default()).unwrap();
2339    /// let adopted = real_doc.adopt_subtree(template);
2340    /// real_doc.append_child(real_doc.root(), adopted);
2341    /// ```
2342    pub fn adopt_subtree<'a>(&'a self, foreign: &Node<'_>) -> &'a Node<'a> {
2343        self.adopt_node_inner(foreign)
2344    }
2345
2346    fn adopt_node_inner<'a>(&'a self, src: &Node<'_>) -> &'a Node<'a> {
2347        let copy: &Node<'a> = match src.kind {
2348            NodeKind::Element => {
2349                let name = self.bump().alloc_str(src.name());
2350                let new_el = self.new_element(name);
2351                for attr in src.attributes() {
2352                    let aname = self.bump().alloc_str(attr.name());
2353                    let aval  = self.bump().alloc_str(attr.value());
2354                    let new_attr = self.new_attribute(aname, aval);
2355                    self.append_attribute(new_el, new_attr);
2356                }
2357                new_el
2358            }
2359            NodeKind::Text => {
2360                let content = self.bump().alloc_str(src.content());
2361                self.new_text(content)
2362            }
2363            NodeKind::CData => {
2364                let content = self.bump().alloc_str(src.content());
2365                self.new_cdata(content)
2366            }
2367            NodeKind::Comment => {
2368                let content = self.bump().alloc_str(src.content());
2369                self.new_comment(content)
2370            }
2371            NodeKind::Pi => {
2372                let name    = self.bump().alloc_str(src.name());
2373                let content = src.content_opt().map(|c| &*self.bump().alloc_str(c));
2374                self.new_pi(name, content)
2375            }
2376            NodeKind::EntityRef => {
2377                let name    = self.bump().alloc_str(src.name());
2378                let content = self.bump().alloc_str(src.content());
2379                self.new_entity_ref(name, content)
2380            }
2381            NodeKind::DtdDecl => {
2382                let content = self.bump().alloc_str(src.content());
2383                self.new_dtd_decl(content)
2384            }
2385            NodeKind::DocumentFragment => self.new_fragment(),
2386            // c-abi-only discriminants — these never appear as a real
2387            // node-kind on a Node<'_> the caller could hold.
2388            NodeKind::Attribute => unreachable!(
2389                "adopt_subtree: NodeKind::Attribute is not a Node — use new_attribute directly"
2390            ),
2391            NodeKind::Document  => unreachable!(
2392                "adopt_subtree: NodeKind::Document marker never appears on a Node — pass the root element instead"
2393            ),
2394            NodeKind::Dtd => unreachable!(
2395                "adopt_subtree: NodeKind::Dtd is a compat-shim sibling node (xmlDtd), never an arena Node reached by a subtree copy"
2396            ),
2397        };
2398        // Recurse into children for container kinds.
2399        if matches!(src.kind, NodeKind::Element | NodeKind::DocumentFragment) {
2400            for child in src.children() {
2401                let child_copy = self.adopt_node_inner(child);
2402                self.append_child(copy, child_copy);
2403            }
2404        }
2405        copy
2406    }
2407
2408    /// Allocate an attribute (detached — link via
2409    /// [`append_attribute`](Self::append_attribute)).
2410    pub fn new_attribute<'a>(&'a self, name: &'a str, value: &'a str) -> &'a mut Attribute<'a> {
2411        #[cfg(not(feature = "c-abi"))]
2412        {
2413            self.bump.alloc(Attribute {
2414                name, value,
2415                namespace: Cell::new(None),
2416                next: Cell::new(None),
2417                prev: Cell::new(None),
2418                parent: Cell::new(None),
2419            })
2420        }
2421        #[cfg(feature = "c-abi")]
2422        {
2423            // See DocumentBuilder::new_attribute for the
2424            // "attribute child text-node" rationale — same
2425            // requirement applies to attributes allocated
2426            // post-build via the Document mutation API.
2427            let text_child: &Node = self.new_text(value);
2428            // Intern the name through the dict (as DocumentBuilder and
2429            // element allocation do): consumers that match attributes by
2430            // dict-canonical pointer — lxml's _MultiTagMatcher behind
2431            // strip_attributes / objectify.deannotate, and objectify's
2432            // own child lookup — only match when post-build attributes
2433            // carry the same canonical name pointer as parsed ones.
2434            let name_c  = self.intern_arena_cstr(name);
2435            let value_c = self.alloc_arena_cstr(value);
2436            self.bump.alloc(Attribute {
2437                _private:  Cell::new(std::ptr::null_mut()),
2438                kind:      NodeKind::Attribute,
2439                _pad_kind: 0,
2440                name:      name_c,
2441                children:  Cell::new(Some(text_child)),
2442                last:      Cell::new(Some(text_child)),
2443                parent:    Cell::new(None),
2444                next:      Cell::new(None),
2445                prev:      Cell::new(None),
2446                doc:       Cell::new(std::ptr::null_mut()),
2447                namespace: Cell::new(None),
2448                atype:     0,
2449                _pad_atype: 0,
2450                psvi:      Cell::new(std::ptr::null_mut()),
2451                value:     value_c,
2452            })
2453        }
2454    }
2455
2456    /// Link `child` as the last child of `parent`.  Updates
2457    /// parent/sibling pointers consistently.
2458    pub fn append_child<'a>(&'a self, parent: &'a Node<'a>, child: &'a Node<'a>) {
2459        debug_assert!(child.parent.get().is_none(),
2460            "Document::append_child: child is already attached");
2461        child.parent.set(Some(parent));
2462        match parent.last_child.get() {
2463            None => {
2464                parent.first_child.set(Some(child));
2465                parent.last_child.set(Some(child));
2466            }
2467            Some(last) => {
2468                last.next_sibling.set(Some(child));
2469                child.prev_sibling.set(Some(last));
2470                parent.last_child.set(Some(child));
2471            }
2472        }
2473    }
2474
2475    /// Allocate a namespace in this document's arena.  c-abi-only:
2476    /// the lean build's `Namespace` doesn't carry the chain pointer
2477    /// we'd need for tree-attached usage.
2478    #[cfg(feature = "c-abi")]
2479    pub fn bump_new_namespace<'a>(
2480        &'a self,
2481        prefix: Option<&'a str>,
2482        href:   &'a str,
2483    ) -> &'a Namespace<'a> {
2484        let href_c = self.alloc_arena_cstr(href);
2485        let prefix_c = prefix.map(|p| self.alloc_arena_cstr(p));
2486        self.bump.alloc(Namespace {
2487            next:      Cell::new(None),
2488            kind:      18, // XML_LOCAL_NAMESPACE
2489            _pad_kind: 0,
2490            href:      href_c,
2491            prefix:    prefix_c,
2492            _private:  Cell::new(std::ptr::null_mut()),
2493            context:   Cell::new(std::ptr::null_mut()),
2494        })
2495    }
2496
2497    /// Append `ns` to `element`'s `ns_def` chain.  Used by the
2498    /// mutation API after creating a fresh namespace via
2499    /// [`bump_new_namespace`].
2500    #[cfg(feature = "c-abi")]
2501    pub fn attach_ns_def<'a>(&'a self, element: &'a Node<'a>, ns: &'a Namespace<'a>) {
2502        match element.ns_def.get() {
2503            None => element.ns_def.set(Some(ns)),
2504            Some(head) => {
2505                // Walk to the tail and link.
2506                let mut cur = head;
2507                while let Some(n) = cur.next.get() {
2508                    cur = n;
2509                }
2510                cur.next.set(Some(ns));
2511            }
2512        }
2513    }
2514
2515    /// Link `attr` as the last attribute on `element`.
2516    pub fn append_attribute<'a>(&'a self, element: &'a Node<'a>, attr: &'a Attribute<'a>) {
2517        debug_assert!(element.is_element(),
2518            "Document::append_attribute: not an element");
2519        debug_assert!(attr.parent.get().is_none(),
2520            "Document::append_attribute: attr already attached");
2521        attr.parent.set(Some(element));
2522        match element.last_attribute.get() {
2523            None => {
2524                element.first_attribute.set(Some(attr));
2525                element.last_attribute.set(Some(attr));
2526            }
2527            Some(last) => {
2528                last.next.set(Some(attr));
2529                attr.prev.set(Some(last));
2530                element.last_attribute.set(Some(attr));
2531            }
2532        }
2533    }
2534
2535    fn alloc_node<'a>(
2536        &'a self,
2537        kind: NodeKind,
2538        name: &'a str,
2539        content: Option<&'a str>,
2540    ) -> &'a mut Node<'a> {
2541        #[cfg(not(feature = "c-abi"))]
2542        {
2543            self.bump.alloc(Node {
2544                kind,
2545                name,
2546                namespace:       Cell::new(None),
2547                first_attribute: Cell::new(None),
2548                last_attribute:  Cell::new(None),
2549                first_child:     Cell::new(None),
2550                last_child:      Cell::new(None),
2551                parent:          Cell::new(None),
2552                next_sibling:    Cell::new(None),
2553                prev_sibling:    Cell::new(None),
2554                content:         Cell::new(content),
2555                line:            0,
2556                source_offset:   0,
2557            })
2558        }
2559        #[cfg(feature = "c-abi")]
2560        {
2561            // Names dedup through the dict (pointer-equal across
2562            // duplicate tags); content stays in the arena (rarely
2563            // repeats).
2564            // Text / CData nodes pin `name` to the libxml2
2565            // `xmlStringText` / `xmlStringTextNoenc` statics — C
2566            // consumers (libxslt's xsltCopyText, lxml's smart-string
2567            // wrapping) compare against those by pointer to identify
2568            // text-kinds.  Any other `name` would silently break the
2569            // dispatch and surface as `Internal error in xsltCopyText`.
2570            let name_c = match kind {
2571                NodeKind::Text | NodeKind::CData => ArenaCStr::text_name(),
2572                _ if name.is_empty() => ArenaCStr::empty(),
2573                _ => self.intern_arena_cstr(name),
2574            };
2575            let content_c = content.map(|c| if c.is_empty() { ArenaCStr::empty() } else { self.alloc_arena_cstr(c) });
2576            self.bump.alloc(Node {
2577                _private:        Cell::new(std::ptr::null_mut()),
2578                kind,
2579                _pad_kind:       0,
2580                name:            name_c,
2581                first_child:     Cell::new(None),
2582                last_child:      Cell::new(None),
2583                parent:          Cell::new(None),
2584                next_sibling:    Cell::new(None),
2585                prev_sibling:    Cell::new(None),
2586                doc:             Cell::new(std::ptr::null_mut()),
2587                namespace:       Cell::new(None),
2588                content:         Cell::new(content_c),
2589                first_attribute: Cell::new(None),
2590                ns_def:          Cell::new(None),
2591                psvi:            Cell::new(std::ptr::null_mut()),
2592                line:            0,
2593                extra:           0,
2594                _pad_extra:      [0u8; 4],
2595                last_attribute:  Cell::new(None),
2596                full_line:       0,
2597                source_offset:   0,
2598            })
2599        }
2600    }
2601
2602    /// Internal — allocate a NUL-terminated copy of `s` in this
2603    /// document's bump arena, returning a c-abi-shaped `ArenaCStr`.
2604    /// Used for values (content / attribute values); for names
2605    /// prefer [`intern_arena_cstr`](Self::intern_arena_cstr).
2606    #[cfg(feature = "c-abi")]
2607    fn alloc_arena_cstr<'a>(&'a self, s: &str) -> ArenaCStr<'a> {
2608        let bytes = s.as_bytes();
2609        let dst: &mut [u8] = self.bump.alloc_slice_fill_with(bytes.len() + 1, |i| {
2610            if i < bytes.len() { bytes[i] } else { 0 }
2611        });
2612        // SAFETY: dst is bytes.len()+1 long with trailing 0; valid UTF-8.
2613        unsafe { ArenaCStr::from_raw(dst.as_ptr()) }
2614    }
2615
2616    /// Intern `s` through the document's name dict; same semantics
2617    /// as [`DocumentBuilder::intern_arena_cstr`].  Used by post-parse
2618    /// mutation paths that need name pointers compatible with the
2619    /// parser-built tree.
2620    #[cfg(feature = "c-abi")]
2621    fn intern_arena_cstr<'a>(&'a self, s: &str) -> ArenaCStr<'a> {
2622        // SAFETY: self.dict is refcount-managed by this Document for
2623        // as long as &self is live.
2624        let ptr = unsafe { (*self.dict).intern_str(s) };
2625        unsafe { ArenaCStr::from_raw(ptr) }
2626    }
2627
2628    /// Raw pointer to the document's name dict.  The dict is
2629    /// refcount-managed; callers wanting to retain a separate
2630    /// reference must invoke
2631    /// [`crate::dict::Dict::add_ref`] explicitly.
2632    #[cfg(feature = "c-abi")]
2633    pub fn dict_ptr(&self) -> *mut crate::dict::Dict {
2634        self.dict
2635    }
2636}
2637
2638impl std::fmt::Debug for Document {
2639    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2640        f.debug_struct("Document")
2641            .field("root", self.root())
2642            .field("memory_bytes", &self.memory_bytes())
2643            .finish()
2644    }
2645}
2646
2647// ── libxml2-shape document wrapper (c-abi only) ─────────────────────────────
2648//
2649// `XmlDoc` is the byte-exact mirror of libxml2's `_xmlDoc`.  Allocated on
2650// the heap by [`Document::into_xml_doc`]; consumed by [`XmlDoc::free`].
2651// The pointer returned to C callers IS the address of the libxml2 ABI
2652// window (the struct's first field is at offset 0 of the heap allocation,
2653// so `*mut XmlDoc` == address of `_private`).
2654//
2655// `_doc` lives at the *tail* of the struct (past the 176-byte ABI window).
2656// It owns the arena and source bytes that every pointer in the header
2657// reaches into; dropping the Box drops `_doc` last, which is fine because
2658// no one reads the header fields after free.
2659
2660/// libxml2-shape `xmlDoc`.  Byte-exact match with `_xmlDoc` (64-bit) for
2661/// the public ABI window (offsets 0..176).  The `_doc` tail field is
2662/// sup-xml-only — it owns the arena that backs every pointer in the
2663/// header — and never appears in the ABI contract.
2664///
2665/// Construction:
2666///   - [`Document::into_xml_doc`] consumes a `Document` and returns a
2667///     `*mut XmlDoc`.  Caller owns the allocation.
2668///   - [`XmlDoc::free`] reclaims a `*mut XmlDoc`, dropping the embedded
2669///     arena.  Idempotent on NULL.
2670///
2671/// All pointers in the header (`children`, `version`, `encoding`, etc.)
2672/// reach into `_doc`'s arena.  They become dangling at `free` time; no
2673/// one reads the header after that.
2674#[cfg(feature = "c-abi")]
2675#[repr(C)]
2676pub struct XmlDoc {
2677    pub _private:    Cell<*mut std::os::raw::c_void>,            //   0
2678    pub kind:        NodeKind,                                   //   8 (XML_DOCUMENT_NODE = 9)
2679    _pad_kind:       u32,                                        //  12
2680    /// libxml2 stores the doc's URL here as `char*`.  We populate it
2681    /// from the `url` argument to `xmlReadMemory` when provided; NULL
2682    /// otherwise.  Note: this is `char*` not `xmlChar*` (a libxml2
2683    /// quirk — every other string in xmlDoc is `xmlChar*`).
2684    pub name:        *const std::os::raw::c_char,                //  16
2685    /// First child (typically the root element; may also be a comment
2686    /// or PI that precedes/follows the root element).
2687    pub children:    Cell<*mut Node<'static>>,                   //  24
2688    pub last:        Cell<*mut Node<'static>>,                   //  32
2689    /// Always NULL for documents (docs have no parent).
2690    pub parent:      Cell<*mut Node<'static>>,                   //  40
2691    /// `next` / `prev` chain — used when a doc is linked into a
2692    /// container (libxslt does this).  We don't link our docs; NULL.
2693    pub next:        Cell<*mut XmlDoc>,                          //  48
2694    pub prev:        Cell<*mut XmlDoc>,                          //  56
2695    /// libxml2 sets `doc` to point at the doc itself.  We mirror that
2696    /// after heap-allocation (see [`Document::into_xml_doc`]).
2697    pub doc:         Cell<*mut XmlDoc>,                          //  64
2698    /// libxml2 compression level (gzip).  Always 0 for us — we don't
2699    /// compress output.
2700    pub compression: i32,                                        //  72
2701    /// `standalone` declaration: -2 (no decl), -1 (yes), 0 (no), 1 (yes).
2702    /// libxml2's quirky tri-state encoding; we mirror it.
2703    pub standalone:  i32,                                        //  76
2704    pub int_subset:  *mut std::os::raw::c_void,                  //  80
2705    pub ext_subset:  *mut std::os::raw::c_void,                  //  88
2706    /// Chain of "global" ns declarations not attached to any element —
2707    /// rare in modern XML, kept for ABI fidelity; we never populate it.
2708    pub old_ns:      *mut std::os::raw::c_void,                  //  96
2709    pub version:     ArenaCStr<'static>,                         // 104
2710    pub encoding:    ArenaCStr<'static>,                         // 112
2711    pub ids:         *mut std::os::raw::c_void,                  // 120
2712    pub refs:        *mut std::os::raw::c_void,                  // 128
2713    pub url:         *const std::os::raw::c_char,                // 136
2714    pub charset:     i32,                                        // 144
2715    _pad_charset:    u32,                                        // 148
2716    pub dict:        *mut std::os::raw::c_void,                  // 152
2717    pub psvi:        *mut std::os::raw::c_void,                  // 160
2718    pub parse_flags: i32,                                        // 168
2719    pub properties:  i32,                                        // 172
2720    // ── sup-xml-only tail (past the 176-byte ABI window) ──
2721    /// The Rust [`Document`] that owns every arena allocation reached
2722    /// by the header pointers above.  Stored as the last field so its
2723    /// offset doesn't pin the ABI.  Dropped last (declaration order),
2724    /// at which point the arena and source bytes are released.
2725    pub _doc: std::mem::ManuallyDrop<Document>,
2726}
2727
2728#[cfg(feature = "c-abi")]
2729const _: () = {
2730    use std::mem::offset_of;
2731    assert!(offset_of!(XmlDoc, _private)    ==   0, "XmlDoc::_private @ 0");
2732    assert!(offset_of!(XmlDoc, kind)        ==   8, "XmlDoc::kind @ 8");
2733    assert!(offset_of!(XmlDoc, name)        ==  16, "XmlDoc::name @ 16");
2734    assert!(offset_of!(XmlDoc, children)    ==  24, "XmlDoc::children @ 24");
2735    assert!(offset_of!(XmlDoc, last)        ==  32, "XmlDoc::last @ 32");
2736    assert!(offset_of!(XmlDoc, parent)      ==  40, "XmlDoc::parent @ 40");
2737    assert!(offset_of!(XmlDoc, next)        ==  48, "XmlDoc::next @ 48");
2738    assert!(offset_of!(XmlDoc, prev)        ==  56, "XmlDoc::prev @ 56");
2739    assert!(offset_of!(XmlDoc, doc)         ==  64, "XmlDoc::doc @ 64");
2740    assert!(offset_of!(XmlDoc, compression) ==  72, "XmlDoc::compression @ 72");
2741    assert!(offset_of!(XmlDoc, standalone)  ==  76, "XmlDoc::standalone @ 76");
2742    assert!(offset_of!(XmlDoc, int_subset)  ==  80, "XmlDoc::int_subset @ 80");
2743    assert!(offset_of!(XmlDoc, ext_subset)  ==  88, "XmlDoc::ext_subset @ 88");
2744    assert!(offset_of!(XmlDoc, old_ns)      ==  96, "XmlDoc::old_ns @ 96");
2745    assert!(offset_of!(XmlDoc, version)     == 104, "XmlDoc::version @ 104");
2746    assert!(offset_of!(XmlDoc, encoding)    == 112, "XmlDoc::encoding @ 112");
2747    assert!(offset_of!(XmlDoc, ids)         == 120, "XmlDoc::ids @ 120");
2748    assert!(offset_of!(XmlDoc, refs)        == 128, "XmlDoc::refs @ 128");
2749    assert!(offset_of!(XmlDoc, url)         == 136, "XmlDoc::url @ 136");
2750    assert!(offset_of!(XmlDoc, charset)     == 144, "XmlDoc::charset @ 144");
2751    assert!(offset_of!(XmlDoc, dict)        == 152, "XmlDoc::dict @ 152");
2752    assert!(offset_of!(XmlDoc, psvi)        == 160, "XmlDoc::psvi @ 160");
2753    assert!(offset_of!(XmlDoc, parse_flags) == 168, "XmlDoc::parse_flags @ 168");
2754    assert!(offset_of!(XmlDoc, properties)  == 172, "XmlDoc::properties @ 172");
2755    // The libxml2 ABI window ends at offset 176.  Our `_doc` tail starts
2756    // there or after (Rust may insert padding before `ManuallyDrop<Document>`
2757    // depending on Document's alignment).
2758    assert!(offset_of!(XmlDoc, _doc)        >= 176, "XmlDoc tail starts after ABI window");
2759};
2760
2761#[cfg(feature = "c-abi")]
2762impl Document {
2763    /// Consume `self` and produce a heap-allocated libxml2-shape
2764    /// [`XmlDoc`].  The returned pointer is what `xmlReadMemory`-style
2765    /// FFI entry points hand back to C callers.  Caller takes ownership;
2766    /// reclaim via [`XmlDoc::free`].
2767    ///
2768    /// All pointers in the resulting [`XmlDoc`] reach into the same arena
2769    /// that this `Document` owns — `_doc` keeps that arena alive for the
2770    /// lifetime of the heap allocation.
2771    pub fn into_xml_doc(self) -> *mut XmlDoc {
2772        // Allocate arena strings for version/encoding via the embedded
2773        // Document's bump.  These slots in libxml2's xmlDoc are
2774        // `xmlChar*` (NUL-terminated UTF-8); ArenaCStr matches that.
2775        let version_str = self.version.clone();
2776        let encoding_str = self.encoding.clone();
2777        // libxml2 uses -1 (not -2) when the XML declaration carried no
2778        // `standalone` attribute (or there was no declaration): xmlNewDoc
2779        // initialises the field to -1, and consumers treat -1 as
2780        // "unspecified" (lxml's `isstandalone` maps -1 -> None, 1 -> True,
2781        // and everything else, including 0, -> False).
2782        let standalone_i32 = match self.standalone {
2783            None        => -1,
2784            Some(true)  =>  1,
2785            Some(false) =>  0,
2786        };
2787        // First-child pointer: equals the first prolog sibling
2788        // (comment / PI before the root) when present, otherwise
2789        // the root element.  libxml2 consumers walk `xmlDoc.children`
2790        // expecting this prolog-first layout.
2791        let root_ptr: *mut Node<'static> =
2792            self.root as *const Node<'static> as *mut Node<'static>;
2793        let first_child_ptr: *mut Node<'static> = if self.first_sibling.is_null() {
2794            root_ptr
2795        } else {
2796            self.first_sibling as *const Node<'static> as *mut Node<'static>
2797        };
2798        // For `xmlDoc.last`, walk to the tail of the sibling chain
2799        // — root or the last epilogue node.
2800        let last_child_ptr: *mut Node<'static> = {
2801            // SAFETY: first_child_ptr is a valid Node pointer into
2802            // the arena owned by `self.bump`, which moves into the
2803            // returned XmlDoc and stays alive.
2804            let mut cur: &Node<'static> = unsafe { &*first_child_ptr };
2805            while let Some(next) = cur.next_sibling.get() {
2806                // Reborrow with 'static lifetime so the while loop
2807                // can keep updating `cur` without the previous
2808                // borrow blocking.
2809                let next_ptr = next as *const Node<'_> as *const Node<'static>;
2810                // SAFETY: next is a sibling pointer into the same arena.
2811                cur = unsafe { &*next_ptr };
2812            }
2813            cur as *const Node<'_> as *mut Node<'static>
2814        };
2815
2816        // Plant the document's name dict at offset 152 so consumers
2817        // walking the libxml2-shape `xmlDoc.dict` field can use it.
2818        // The refcount is bumped once *here* so the planted pointer
2819        // owns its own reference, independent of the embedded
2820        // `Document`'s own reference.  Consequences:
2821        //
2822        //   * `XmlDoc::free` releases the dict slot (one decrement)
2823        //     and then drops the embedded Document (another
2824        //     decrement for `Document.dict`).  Net: both refs
2825        //     released; the dict survives as long as any other
2826        //     holder (a different doc parsed on the same thread,
2827        //     the thread's own stash) still has a reference.
2828        //
2829        //   * Consumers that "free" `c_doc.dict` (e.g. lxml's
2830        //     `initThreadDictRef` decides our dict differs from its
2831        //     thread dict and calls `xmlDictFree` on it) are
2832        //     decrementing the slot's own reference; they may then
2833        //     overwrite the slot with their own dict pointer (with
2834        //     a fresh `xmlDictReference` of their own).  In either
2835        //     case our refcount math stays balanced.
2836        let dict_for_slot: *mut std::os::raw::c_void = {
2837            let d = self.dict;
2838            if !d.is_null() {
2839                // SAFETY: `self.dict` is a live, refcount-managed
2840                // Dict (set at builder construction and not yet
2841                // released — the embedded Document hasn't been
2842                // dropped).  Bumping is sound.
2843                unsafe { (*d).add_ref(); }
2844            }
2845            d as *mut std::os::raw::c_void
2846        };
2847
2848        // Allocate version + encoding inside the embedded bump via a
2849        // temporary borrow.  After this, no more allocations happen in
2850        // the bump.
2851        let (version_c, encoding_c) = {
2852            let bytes_v = version_str.as_bytes();
2853            let bytes_e = encoding_str.as_bytes();
2854            let dst_v: &mut [u8] = self.bump.alloc_slice_fill_with(bytes_v.len() + 1, |i| {
2855                if i < bytes_v.len() { bytes_v[i] } else { 0 }
2856            });
2857            let dst_e: &mut [u8] = self.bump.alloc_slice_fill_with(bytes_e.len() + 1, |i| {
2858                if i < bytes_e.len() { bytes_e[i] } else { 0 }
2859            });
2860            // SAFETY: NUL-terminated UTF-8, lifetime tied to the bump
2861            // which moves into `_doc` (heap-pinned via Pin<Box<Bump>>).
2862            unsafe {
2863                (
2864                    ArenaCStr::from_raw(dst_v.as_ptr()),
2865                    ArenaCStr::from_raw(dst_e.as_ptr()),
2866                )
2867            }
2868        };
2869
2870        let boxed = Box::new(XmlDoc {
2871            _private:    Cell::new(std::ptr::null_mut()),
2872            kind:        NodeKind::Document,
2873            _pad_kind:   0,
2874            name:        std::ptr::null(),
2875            children:    Cell::new(first_child_ptr),
2876            last:        Cell::new(last_child_ptr),
2877            parent:      Cell::new(std::ptr::null_mut()),
2878            next:        Cell::new(std::ptr::null_mut()),
2879            prev:        Cell::new(std::ptr::null_mut()),
2880            doc:         Cell::new(std::ptr::null_mut()),
2881            compression: 0,
2882            standalone:  standalone_i32,
2883            int_subset:  std::ptr::null_mut(),
2884            ext_subset:  std::ptr::null_mut(),
2885            old_ns:      std::ptr::null_mut(),
2886            version:     version_c,
2887            encoding:    encoding_c,
2888            ids:         std::ptr::null_mut(),
2889            refs:        std::ptr::null_mut(),
2890            url:         std::ptr::null(),
2891            charset:     1,  // libxml2's XML_CHAR_ENCODING_UTF8 = 1
2892            _pad_charset: 0,
2893            dict:        dict_for_slot,
2894            psvi:        std::ptr::null_mut(),
2895            parse_flags: 0,
2896            properties:  0,
2897            _doc:        std::mem::ManuallyDrop::new(self),
2898        });
2899        let raw = Box::into_raw(boxed);
2900        // Set the self-pointer for libxml2 compatibility (`doc->doc == doc`).
2901        // SAFETY: `raw` is a freshly allocated, valid pointer.
2902        unsafe { (*raw).doc.set(raw); }
2903        // Walk the tree once to stamp `node->doc = raw` on every node,
2904        // matching libxml2's invariant.  Mutation API (`xmlNewProp`,
2905        // `xmlAddChild` cross-doc detection) reads this; without it
2906        // every post-parse mutation would have to walk up to find the
2907        // owning doc.
2908        // SAFETY: raw is valid; the tree was just built by the parser.
2909        unsafe {
2910            let owned = &*raw;
2911            let raw_void = raw as *mut std::os::raw::c_void;
2912            let mut stack: Vec<*const Node<'static>> = Vec::new();
2913            stack.push(owned.children.get() as *const _);
2914            // Seed with every top-level sibling (prolog → root →
2915            // epilogue), not just `children`, so we stamp the whole
2916            // top-level chain in document-order.  Without this,
2917            // sibling chains after the first node would be missed.
2918            //
2919            // Top-level nodes (prolog comments, the root, epilogue
2920            // comments) also get their `parent` field stamped to the
2921            // doc-cast-as-Node.  libxml2 uses this so consumers can
2922            // walk up from any document-level node, and so that
2923            // `xmlUnlinkNode` on a prolog/epilogue node correctly
2924            // adjusts the doc's `children` / `last` pointers (the
2925            // sibling chain-update reads them off the parent).  The
2926            // type pun is sound because `XmlDoc` and `Node` share
2927            // identical layout at offsets 0–64 (private, kind, name,
2928            // children, last, parent, next, prev, doc).
2929            let doc_as_node: &Node<'static> = &*(raw as *const Node<'static>);
2930            let mut cur_sib: *const Node<'static> = owned.children.get() as *const _;
2931            while !cur_sib.is_null() {
2932                stack.push(cur_sib);
2933                let s_ref = &*cur_sib;
2934                s_ref.parent.set(Some(doc_as_node));
2935                cur_sib = s_ref.next_sibling.get()
2936                    .map(|n| n as *const _)
2937                    .unwrap_or(std::ptr::null());
2938            }
2939            while let Some(np) = stack.pop() {
2940                if np.is_null() { continue; }
2941                let n = &*np;
2942                n.doc.set(raw_void);
2943                // Stamp attributes' doc field too.
2944                let mut a = n.first_attribute.get();
2945                while let Some(attr) = a {
2946                    attr.doc.set(raw_void);
2947                    a = attr.next.get();
2948                }
2949                // Recurse via stack into children only — siblings
2950                // of the top-level sequence are already enqueued.
2951                let mut c = n.first_child.get();
2952                while let Some(ch) = c {
2953                    stack.push(ch as *const _);
2954                    c = ch.next_sibling.get();
2955                }
2956            }
2957        }
2958        raw
2959    }
2960}
2961
2962#[cfg(feature = "c-abi")]
2963impl XmlDoc {
2964    /// Reclaim a heap-allocated [`XmlDoc`].  No-op on NULL.  After this
2965    /// returns, every pointer that was read out of the doc (children,
2966    /// version, encoding, etc.) is dangling — caller is responsible for
2967    /// not retaining them.
2968    ///
2969    /// # Safety
2970    /// `ptr` must be NULL or a pointer returned by
2971    /// [`Document::into_xml_doc`] that has not yet been freed.
2972    pub unsafe fn free(ptr: *mut XmlDoc) {
2973        if ptr.is_null() { return; }
2974        // SAFETY: precondition — caller guarantees ptr was from
2975        // into_xml_doc and not yet freed.  Box::from_raw reconstructs
2976        // ownership; the Box drops at end-of-scope.  Inside the drop,
2977        // _doc (ManuallyDrop) needs explicit drop to release the
2978        // embedded Document's arena and source bytes.
2979        let mut boxed = unsafe { Box::from_raw(ptr) };
2980        // Reclaim the leaked URL CString (set by C-ABI consumers
2981        // that record a source URL post-build).  NULL when no URL
2982        // was recorded; safe to skip.
2983        if !boxed.url.is_null() {
2984            // SAFETY: url was `CString::into_raw`'d by the consumer
2985            // (e.g. xml_read_memory_with_dict).  Reclaim and drop.
2986            unsafe { let _ = std::ffi::CString::from_raw(boxed.url as *mut std::os::raw::c_char); }
2987        }
2988        // Release the dict reference planted in the XmlDoc.dict slot.
2989        // libxml2's `xmlFreeDoc` semantically calls `xmlDictFree` on
2990        // `doc->dict` — consumers (like lxml) may have swapped the
2991        // pointer out for their own thread-shared dict before
2992        // freeing, but the reference is owned by the field regardless
2993        // of which dict it currently points at.  Mirroring this
2994        // matches the libxml2 ABI contract.
2995        let dict_at_free = boxed.dict;
2996        if !dict_at_free.is_null() {
2997            // SAFETY: `dict_at_free` was either planted by
2998            // `into_xml_doc` (with a bumped refcount) or swapped in
2999            // by a consumer that bumped the refcount itself.  Either
3000            // way one outstanding reference belongs to this slot.
3001            unsafe { crate::dict::Dict::release(dict_at_free as *mut crate::dict::Dict); }
3002        }
3003        unsafe { std::mem::ManuallyDrop::drop(&mut boxed._doc); }
3004        drop(boxed);
3005    }
3006}
3007
3008// ── tests ───────────────────────────────────────────────────────────────────
3009
3010#[cfg(test)]
3011mod tests {
3012    use super::*;
3013
3014    /// Every [`NodeKind`] discriminant must match libxml2's
3015    /// `xmlElementType` value for the corresponding node type.
3016    ///
3017    /// C consumers do `if (node->type == XML_ELEMENT_NODE)` against
3018    /// the integer; drift here silently misclassifies nodes in any
3019    /// tree walker linked through the cdylib.  Numbers verified
3020    /// against `xmlElementType` in
3021    /// `/opt/homebrew/Cellar/libxml2/<version>/include/libxml2/libxml/tree.h`.
3022    ///
3023    /// We model 8 of libxml2's 20 element types today.  The missing
3024    /// 12 (XML_ENTITY_NODE=6, XML_DOCUMENT_TYPE_NODE=10,
3025    /// XML_DOCUMENT_FRAG_NODE=11, XML_NOTATION_NODE=12,
3026    /// XML_HTML_DOCUMENT_NODE=13, XML_DTD_NODE=14,
3027    /// XML_ELEMENT_DECL=15, XML_ATTRIBUTE_DECL=16,
3028    /// XML_ENTITY_DECL=17, XML_NAMESPACE_DECL=18,
3029    /// XML_XINCLUDE_START=19, XML_XINCLUDE_END=20) are intentionally
3030    /// absent — their slot numbers stay free for future variants
3031    /// rather than being shadowed.  Any addition lands here too.
3032    #[test]
3033    fn node_kind_libxml2_values_match() {
3034        assert_eq!(NodeKind::Element   as u32,  1);
3035        assert_eq!(NodeKind::Attribute as u32,  2);
3036        assert_eq!(NodeKind::Text      as u32,  3);
3037        assert_eq!(NodeKind::CData     as u32,  4);
3038        assert_eq!(NodeKind::EntityRef as u32,  5);
3039        assert_eq!(NodeKind::Pi        as u32,  7);
3040        assert_eq!(NodeKind::Comment   as u32,  8);
3041        assert_eq!(NodeKind::Document  as u32,  9);
3042    }
3043
3044    fn build_simple_tree() -> Document {
3045        let b = DocumentBuilder::new();
3046        let root = b.new_element(b.alloc_str("catalog"));
3047        let book = b.new_element(b.alloc_str("book"));
3048        let id   = b.new_attribute(b.alloc_str("id"), b.alloc_str("1"));
3049        b.append_attribute(book, id);
3050        let title = b.new_element(b.alloc_str("title"));
3051        let title_text = b.new_text(b.alloc_str("Dune"));
3052        b.append_child(title, title_text);
3053        b.append_child(book, title);
3054        b.append_child(root, book);
3055        b.set_root(root);
3056        b.build()
3057    }
3058
3059    #[test]
3060    fn basic_tree_navigation() {
3061        let doc = build_simple_tree();
3062        let root = doc.root();
3063        assert_eq!(root.name(), "catalog");
3064        assert!(root.is_element());
3065
3066        let book = root.children().next().unwrap();
3067        assert_eq!(book.name(), "book");
3068        assert!(book.parent.get().is_some());
3069
3070        let title = book.find_child("title").unwrap();
3071        assert_eq!(title.name(), "title");
3072        assert_eq!(title.text_content(), Some("Dune"));
3073    }
3074
3075    #[test]
3076    fn attribute_iteration() {
3077        let b = DocumentBuilder::new();
3078        let el = b.new_element(b.alloc_str("el"));
3079        for (n, v) in [("a", "1"), ("b", "2"), ("c", "3")] {
3080            let attr = b.new_attribute(b.alloc_str(n), b.alloc_str(v));
3081            b.append_attribute(el, attr);
3082        }
3083        b.set_root(el); let doc = b.build();
3084        let pairs: Vec<(String, String)> = doc.root().attributes()
3085            .map(|a| (a.name().to_owned(), a.value().to_owned()))
3086            .collect();
3087        assert_eq!(pairs, vec![
3088            ("a".into(), "1".into()),
3089            ("b".into(), "2".into()),
3090            ("c".into(), "3".into()),
3091        ]);
3092    }
3093
3094    #[test]
3095    fn sibling_links_are_doubly_threaded() {
3096        let b = DocumentBuilder::new();
3097        let root = b.new_element(b.alloc_str("r"));
3098        for n in &["a", "b", "c"] {
3099            let child = b.new_element(b.alloc_str(*n));
3100            b.append_child(root, child);
3101        }
3102        b.set_root(root); let doc = b.build();
3103        let r = doc.root();
3104
3105        let names_fwd: Vec<&str> = r.children().map(|c| c.name()).collect();
3106        assert_eq!(names_fwd, vec!["a", "b", "c"]);
3107
3108        // Walk backwards from last_child via prev_sibling
3109        let mut names_back: Vec<&str> = Vec::new();
3110        let mut cur = r.last_child.get();
3111        while let Some(n) = cur {
3112            names_back.push(n.name());
3113            cur = n.prev_sibling.get();
3114        }
3115        assert_eq!(names_back, vec!["c", "b", "a"]);
3116
3117        // Parent pointers are set
3118        for c in r.children() {
3119            assert!(std::ptr::eq(c.parent.get().unwrap(), r));
3120        }
3121    }
3122
3123    #[test]
3124    fn detach_middle_child_repairs_links() {
3125        let b = DocumentBuilder::new();
3126        let root = b.new_element(b.alloc_str("r"));
3127        let a = b.new_element(b.alloc_str("a"));
3128        let b_node = b.new_element(b.alloc_str("b"));
3129        let c = b.new_element(b.alloc_str("c"));
3130        b.append_child(root, a);
3131        b.append_child(root, b_node);
3132        b.append_child(root, c);
3133
3134        b.detach(b_node);
3135
3136        let names: Vec<&str> = root.children().map(|n| n.name()).collect();
3137        assert_eq!(names, vec!["a", "c"]);
3138        assert!(b_node.parent.get().is_none());
3139        assert!(b_node.prev_sibling.get().is_none());
3140        assert!(b_node.next_sibling.get().is_none());
3141        // a.next now points to c (skipping b_node)
3142        assert!(std::ptr::eq(a.next_sibling.get().unwrap(), c));
3143        assert!(std::ptr::eq(c.prev_sibling.get().unwrap(), a));
3144    }
3145
3146    #[test]
3147    fn detach_first_and_last() {
3148        let b = DocumentBuilder::new();
3149        let root = b.new_element(b.alloc_str("r"));
3150        let a = b.new_element(b.alloc_str("a"));
3151        let c = b.new_element(b.alloc_str("c"));
3152        b.append_child(root, a);
3153        b.append_child(root, c);
3154
3155        b.detach(a);  // first
3156        assert!(std::ptr::eq(root.first_child.get().unwrap(), c));
3157        assert!(root.last_child.get().is_some());
3158        assert!(c.prev_sibling.get().is_none());
3159
3160        b.detach(c);  // last (now only child)
3161        assert!(root.first_child.get().is_none());
3162        assert!(root.last_child.get().is_none());
3163    }
3164
3165    #[test]
3166    fn document_is_send() {
3167        // Compile-time check: Document: Send.
3168        fn assert_send<T: Send>() {}
3169        assert_send::<Document>();
3170    }
3171
3172    #[test]
3173    fn root_lifetime_bounded_by_document() {
3174        // This test exists to document the property; the trybuild-style
3175        // "this should fail to compile" check is below in a doc comment.
3176        let doc = build_simple_tree();
3177        let root = doc.root();
3178        assert_eq!(root.name(), "catalog");
3179        // `root` cannot outlive `doc` — the lifetime is tied to `&doc`.
3180        drop(doc);
3181        // (We intentionally do NOT use `root` here — it would not compile.)
3182    }
3183
3184    #[test]
3185    fn mixed_content_children() {
3186        let b = DocumentBuilder::new();
3187        let root = b.new_element(b.alloc_str("r"));
3188        b.append_child(root, b.new_text(b.alloc_str("before ")));
3189        let em = b.new_element(b.alloc_str("em"));
3190        b.append_child(em, b.new_text(b.alloc_str("middle")));
3191        b.append_child(root, em);
3192        b.append_child(root, b.new_text(b.alloc_str(" after")));
3193        b.append_child(root, b.new_comment(b.alloc_str(" note ")));
3194        b.append_child(root, b.new_cdata(b.alloc_str("<raw>")));
3195
3196        b.set_root(root); let doc = b.build();
3197        let r = doc.root();
3198        let kinds: Vec<NodeKind> = r.children().map(|c| c.kind).collect();
3199        assert_eq!(kinds, vec![NodeKind::Text, NodeKind::Element, NodeKind::Text,
3200                               NodeKind::Comment, NodeKind::CData]);
3201
3202        // text_content() on a mixed element returns first text/cdata
3203        assert_eq!(r.text_content(), Some("before "));
3204    }
3205
3206    #[test]
3207    fn namespace_attached_to_element() {
3208        let b = DocumentBuilder::new();
3209        let ns = b.new_namespace(Some(b.alloc_str("dc")),
3210                                 b.alloc_str("http://purl.org/dc/elements/1.1/"));
3211        let el = b.new_element(b.alloc_str("dc:title"));
3212        el.namespace.set(Some(ns));
3213        b.set_root(el); let doc = b.build();
3214        let ns_got = doc.root().namespace.get().unwrap();
3215        assert_eq!(ns_got.prefix(), Some("dc"));
3216        assert_eq!(ns_got.href(),   "http://purl.org/dc/elements/1.1/");
3217    }
3218
3219    #[test]
3220    fn memory_bytes_grows_with_alloc() {
3221        let b = DocumentBuilder::new();
3222        let root = b.new_element(b.alloc_str("r"));
3223        for i in 0..100 {
3224            let child = b.new_element(b.alloc_str(&format!("c{i}")));
3225            b.append_child(root, child);
3226        }
3227        b.set_root(root); let doc = b.build();
3228        assert!(doc.memory_bytes() > 0);
3229        assert_eq!(doc.root().children().count(), 100);
3230    }
3231
3232    #[test]
3233    fn pi_node_holds_target_and_content() {
3234        let b = DocumentBuilder::new();
3235        let root = b.new_element(b.alloc_str("r"));
3236        let pi = b.new_pi(b.alloc_str("xml-stylesheet"),
3237                          Some(b.alloc_str(r#"type="text/xsl" href="s.xsl""#)));
3238        b.append_child(root, pi);
3239        b.set_root(root); let doc = b.build();
3240        let pi = doc.root().children().next().unwrap();
3241        assert_eq!(pi.kind, NodeKind::Pi);
3242        assert_eq!(pi.name(), "xml-stylesheet");
3243        assert_eq!(pi.content(), r#"type="text/xsl" href="s.xsl""#);
3244    }
3245
3246    // ── builder default + with_capacity ──────────────────────────
3247
3248    #[test]
3249    fn builder_default_is_same_as_new() {
3250        let b = DocumentBuilder::default();
3251        // Same shape — should let us build an empty-ish doc.
3252        let root = b.new_element(b.alloc_str("r"));
3253        b.set_root(root);
3254        let doc = b.build();
3255        assert_eq!(doc.root().name(), "r");
3256    }
3257
3258    #[test]
3259    fn builder_with_capacity_reserves_arena() {
3260        let b = DocumentBuilder::with_capacity(8 * 1024);
3261        let root = b.new_element(b.alloc_str("r"));
3262        b.set_root(root);
3263        let doc = b.build();
3264        // Smoke check — capacity matters for performance, not behaviour.
3265        assert!(doc.memory_bytes() > 0);
3266        assert_eq!(doc.root().name(), "r");
3267    }
3268
3269    #[test]
3270    fn builder_bump_accessor() {
3271        // Direct access to the underlying Bump.
3272        let b = DocumentBuilder::new();
3273        let _: &bumpalo::Bump = b.bump();
3274    }
3275
3276    // ── source() returns None until set_source_inplace_buffer is called ──
3277
3278    #[test]
3279    fn builder_source_returns_none_when_no_inplace_buffer() {
3280        let b = DocumentBuilder::new();
3281        assert!(b.source().is_none());
3282    }
3283
3284    // ── is_entity_ref / entity-ref allocation ────────────────────
3285
3286    #[test]
3287    fn entity_ref_node_via_builder() {
3288        let b = DocumentBuilder::new();
3289        let root = b.new_element(b.alloc_str("r"));
3290        let er = b.new_entity_ref(b.alloc_str("foo"), b.alloc_str("&foo;"));
3291        b.append_child(root, er);
3292        b.set_root(root); let doc = b.build();
3293        let e = doc.root().children().next().unwrap();
3294        assert!(e.is_entity_ref());
3295        assert!(!e.is_element());
3296        assert!(!e.is_text());
3297        assert_eq!(e.name(), "foo");
3298        assert_eq!(e.content(), "&foo;");
3299    }
3300
3301    // ── text_content fallthroughs ────────────────────────────────
3302
3303    #[test]
3304    fn text_content_on_element_without_text_returns_none() {
3305        // Element with only element children → text_content returns None
3306        // (text_content's find_map exhausts without finding Text/CData,
3307        // hitting the `_ => None` arm).
3308        let b = DocumentBuilder::new();
3309        let root = b.new_element(b.alloc_str("r"));
3310        let child = b.new_element(b.alloc_str("c"));
3311        b.append_child(root, child);
3312        b.set_root(root); let doc = b.build();
3313        assert_eq!(doc.root().text_content(), None);
3314    }
3315
3316    #[test]
3317    fn text_content_on_comment_returns_none() {
3318        // Comment kind → outer `_ => None` arm.
3319        let b = DocumentBuilder::new();
3320        let root = b.new_element(b.alloc_str("r"));
3321        let c = b.new_comment(b.alloc_str(" hi "));
3322        b.append_child(root, c);
3323        b.set_root(root); let doc = b.build();
3324        let comment = doc.root().children().next().unwrap();
3325        assert_eq!(comment.text_content(), None);
3326    }
3327
3328    // ── Debug impls ──────────────────────────────────────────────
3329
3330    #[test]
3331    fn node_debug_shows_kind_and_relevant_fields() {
3332        let b = DocumentBuilder::new();
3333        let root = b.new_element(b.alloc_str("foo"));
3334        b.append_child(root, b.new_text(b.alloc_str("hello")));
3335        b.set_root(root); let doc = b.build();
3336        let s = format!("{:?}", doc.root());
3337        assert!(s.contains("Element"), "got {s}");
3338        assert!(s.contains("foo"), "got {s}");
3339
3340        // Text node — name is empty, content carries.
3341        let t = doc.root().children().next().unwrap();
3342        let s = format!("{t:?}");
3343        assert!(s.contains("Text"), "got {s}");
3344        assert!(s.contains("hello"), "got {s}");
3345    }
3346
3347    #[test]
3348    fn attribute_debug_shows_name_and_value() {
3349        let b = DocumentBuilder::new();
3350        let el = b.new_element(b.alloc_str("el"));
3351        let attr = b.new_attribute(b.alloc_str("id"), b.alloc_str("123"));
3352        b.append_attribute(el, attr);
3353        b.set_root(el); let doc = b.build();
3354        let attr = doc.root().attributes().next().unwrap();
3355        let s = format!("{attr:?}");
3356        assert!(s.contains("Attribute"), "got {s}");
3357        assert!(s.contains("id"),  "got {s}");
3358        assert!(s.contains("123"), "got {s}");
3359    }
3360
3361    #[test]
3362    fn document_debug_shows_root_and_memory() {
3363        let b = DocumentBuilder::new();
3364        b.set_root(b.new_element(b.alloc_str("rootname")));
3365        let doc = b.build();
3366        let s = format!("{doc:?}");
3367        assert!(s.contains("Document"),     "got {s}");
3368        assert!(s.contains("memory_bytes"), "got {s}");
3369        assert!(s.contains("rootname"),     "got {s}");
3370    }
3371
3372    // ── ChildIter::from_head ─────────────────────────────────────
3373
3374    #[test]
3375    fn child_iter_from_head_walks_chain() {
3376        let b = DocumentBuilder::new();
3377        let root = b.new_element(b.alloc_str("r"));
3378        for n in &["a", "b", "c"] {
3379            b.append_child(root, b.new_element(b.alloc_str(n)));
3380        }
3381        b.set_root(root); let doc = b.build();
3382        // ChildIter::from_head used internally by Attribute::children.
3383        // Test it directly with the root's first_child.
3384        let head = doc.root().first_child.get();
3385        let names: Vec<&str> = ChildIter::from_head(head).map(|c| c.name()).collect();
3386        assert_eq!(names, vec!["a", "b", "c"]);
3387
3388        // None head yields no nodes.
3389        let empty: Vec<&str> = ChildIter::from_head(None).map(|c| c.name()).collect();
3390        assert!(empty.is_empty());
3391    }
3392
3393    // ── Document::first_sibling and is_html ─────────────────────
3394
3395    #[test]
3396    fn document_first_sibling_equals_root_by_default() {
3397        let b = DocumentBuilder::new();
3398        b.set_root(b.new_element(b.alloc_str("r")));
3399        let doc = b.build();
3400        // No prolog → first_sibling is the root itself.
3401        let first = doc.first_sibling();
3402        assert_eq!(first.name(), "r");
3403    }
3404
3405    #[test]
3406    fn document_is_html_false_without_metadata() {
3407        let b = DocumentBuilder::new();
3408        b.set_root(b.new_element(b.alloc_str("r")));
3409        let doc = b.build();
3410        assert!(!doc.is_html());
3411    }
3412
3413    // ── Document post-build mutation API ────────────────────────
3414
3415    #[test]
3416    fn document_post_build_new_element_and_append_child() {
3417        let b = DocumentBuilder::new();
3418        b.set_root(b.new_element(b.alloc_str("r")));
3419        let doc = b.build();
3420        let root = doc.root();
3421        let added = doc.new_element(doc.bump().alloc_str("late"));
3422        doc.append_child(root, added);
3423        let names: Vec<&str> = root.children().map(|c| c.name()).collect();
3424        assert_eq!(names, vec!["late"]);
3425    }
3426
3427    #[test]
3428    fn document_post_build_append_two_children_threads_siblings() {
3429        let b = DocumentBuilder::new();
3430        b.set_root(b.new_element(b.alloc_str("r")));
3431        let doc = b.build();
3432        let root = doc.root();
3433        let a = doc.new_element(doc.bump().alloc_str("a"));
3434        let bn = doc.new_element(doc.bump().alloc_str("b"));
3435        doc.append_child(root, a);
3436        doc.append_child(root, bn);
3437        // First+second-append both branches in append_child (None / Some(last)).
3438        let names: Vec<&str> = root.children().map(|c| c.name()).collect();
3439        assert_eq!(names, vec!["a", "b"]);
3440        // Sibling links between a and b set up.
3441        assert!(std::ptr::eq(a.next_sibling.get().unwrap(), bn));
3442        assert!(std::ptr::eq(bn.prev_sibling.get().unwrap(), a));
3443    }
3444
3445    #[test]
3446    fn document_post_build_append_attribute_two_threads_links() {
3447        let b = DocumentBuilder::new();
3448        b.set_root(b.new_element(b.alloc_str("r")));
3449        let doc = b.build();
3450        let root = doc.root();
3451        let a1 = doc.new_attribute(doc.bump().alloc_str("id"),    doc.bump().alloc_str("1"));
3452        let a2 = doc.new_attribute(doc.bump().alloc_str("class"), doc.bump().alloc_str("c"));
3453        doc.append_attribute(root, a1);
3454        doc.append_attribute(root, a2);
3455        let pairs: Vec<(&str, &str)> = root.attributes()
3456            .map(|a| (a.name(), a.value())).collect();
3457        assert_eq!(pairs, vec![("id", "1"), ("class", "c")]);
3458    }
3459
3460    #[test]
3461    fn document_post_build_allocator_variants() {
3462        // Touch every Document-level allocator to cover their bodies.
3463        let b = DocumentBuilder::new();
3464        b.set_root(b.new_element(b.alloc_str("r")));
3465        let doc = b.build();
3466        let root = doc.root();
3467
3468        let t  = doc.new_text(doc.bump().alloc_str("hi"));
3469        let cd = doc.new_cdata(doc.bump().alloc_str("raw"));
3470        let cm = doc.new_comment(doc.bump().alloc_str(" c "));
3471        let pi = doc.new_pi(doc.bump().alloc_str("php"), Some(doc.bump().alloc_str("")));
3472        let er = doc.new_entity_ref(doc.bump().alloc_str("foo"), doc.bump().alloc_str("&foo;"));
3473
3474        doc.append_child(root, t);
3475        doc.append_child(root, cd);
3476        doc.append_child(root, cm);
3477        doc.append_child(root, pi);
3478        doc.append_child(root, er);
3479
3480        let kinds: Vec<NodeKind> = root.children().map(|c| c.kind).collect();
3481        assert_eq!(kinds, vec![
3482            NodeKind::Text, NodeKind::CData, NodeKind::Comment,
3483            NodeKind::Pi, NodeKind::EntityRef,
3484        ]);
3485    }
3486
3487    #[test]
3488    fn document_bump_accessor() {
3489        let b = DocumentBuilder::new();
3490        b.set_root(b.new_element(b.alloc_str("r")));
3491        let doc = b.build();
3492        let _: &bumpalo::Bump = doc.bump();
3493    }
3494}