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