Skip to main content

parsec_xpath/
html.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! parsec-web's tree as a [`Tree`]: an HTML page as lxml reads one, and
5//! through [`XmlTree`] an XML document built into the same tree.
6
7use parsec::{AttrNs, Document, Kind, Ns};
8
9use crate::tree::{Attr, NodeId, NodeType, TagKey, Tree};
10
11/// An HTML page. Names are the parser's lowercase ones in no namespace,
12/// and a colon is part of a name (`fb:like`), as in lxml.
13impl Tree for Document {
14    fn len(&self) -> usize {
15        Document::len(self)
16    }
17
18    fn kind(&self, n: NodeId) -> NodeType {
19        match Document::kind(self, n) {
20            Kind::Element { .. } => NodeType::Element,
21            Kind::Text(_) => NodeType::Text,
22            Kind::Cdata(_) => NodeType::Cdata,
23            Kind::ProcessingInstruction { .. } => NodeType::ProcessingInstruction,
24            Kind::Comment(_) => NodeType::Comment,
25            Kind::Document => NodeType::Document,
26            Kind::Doctype { .. } => NodeType::Doctype,
27            Kind::Fragment | Kind::ShadowRoot(_) => NodeType::Other,
28        }
29    }
30
31    fn parent(&self, n: NodeId) -> Option<NodeId> {
32        Document::parent(self, n)
33    }
34
35    fn first_child(&self, n: NodeId) -> Option<NodeId> {
36        Document::first_child(self, n)
37    }
38
39    fn next_sibling(&self, n: NodeId) -> Option<NodeId> {
40        Document::next_sibling(self, n)
41    }
42
43    fn prev_sibling(&self, n: NodeId) -> Option<NodeId> {
44        Document::prev_sibling(self, n)
45    }
46
47    fn qualified_name(&self, n: NodeId) -> &str {
48        self.lower_name(n).unwrap_or("")
49    }
50
51    fn local_name(&self, n: NodeId) -> &str {
52        self.lower_name(n).unwrap_or("")
53    }
54
55    fn namespace_uri(&self, _: NodeId) -> &str {
56        ""
57    }
58
59    fn tag_key(&self, n: NodeId) -> TagKey<'_> {
60        if let Some(t) = self.known_tag(n) {
61            return TagKey::Known(t.into());
62        }
63        let name = self.lower_name(n).unwrap_or("");
64        // Only XML has prefixes: in HTML, <o:p> is an element called "o:p".
65        TagKey::Name(match Document::kind(self, n) {
66            Kind::Element { ns: Ns::Xml, .. } => {
67                name.split_once(':').map_or(name, |(_, local)| local)
68            }
69            _ => name,
70        })
71    }
72
73    fn attribute_count(&self, n: NodeId) -> u32 {
74        self.attr_count(n) as u32
75    }
76
77    fn attribute(&self, n: NodeId, i: u32) -> Option<Attr<'_>> {
78        self.attr_at(n, i as usize).map(|(_, name, value)| Attr {
79            qualified_name: name,
80            local_name: name,
81            namespace_uri: "",
82            value,
83        })
84    }
85
86    fn data(&self, n: NodeId) -> &str {
87        match Document::kind(self, n) {
88            Kind::Text(t) | Kind::Cdata(t) | Kind::Comment(t) => t,
89            Kind::ProcessingInstruction { data, .. } => data,
90            _ => "",
91        }
92    }
93
94    fn pi_target(&self, n: NodeId) -> Option<&str> {
95        match Document::kind(self, n) {
96            Kind::ProcessingInstruction { target, .. } => Some(target),
97            _ => None,
98        }
99    }
100
101    fn is_xml(&self) -> bool {
102        false
103    }
104
105    fn id(&self, n: NodeId) -> Option<&str> {
106        attr_ignoring_case(self, n, "id")
107    }
108
109    fn lang(&self, n: NodeId) -> Option<&str> {
110        attr_ignoring_case(self, n, "xml:lang").or_else(|| attr_ignoring_case(self, n, "lang"))
111    }
112}
113
114/// HTML names are lowercase, so a name is looked up ignoring case.
115fn attr_ignoring_case<'t>(tree: &'t Document, n: NodeId, name: &str) -> Option<&'t str> {
116    tree.attrs(n)
117        .find(|(_, k, _)| k.eq_ignore_ascii_case(name))
118        .map(|(_, _, v)| v)
119}
120
121/// The namespaces of an XML document built into a parsec-web tree,
122/// which the tree leaves to its host. Ids are the host's; 0 is no
123/// namespace.
124pub trait Namespaces: Sync {
125    /// The namespace id of an element.
126    fn ns_of(&self, element: NodeId) -> u32;
127    /// The URI with id `id`; "" for 0.
128    fn uri(&self, id: u32) -> &str;
129    /// How many namespaces `node` declares (see
130    /// [`Tree::namespace_declaration_count`]).
131    fn declaration_count(&self, _node: NodeId) -> u32 {
132        0
133    }
134    /// `node`'s `i`th declaration: its prefix ("" for the default
135    /// namespace) and the id of its URI (0 for `xmlns=""`).
136    fn declaration(&self, _node: NodeId, _i: u32) -> Option<(&str, u32)> {
137        None
138    }
139}
140
141/// An XML document built into a parsec-web tree: its elements are
142/// [`Ns::Xml`] with their names as written, its attributes' namespaces are
143/// [`AttrNs::Host`] ids, and `names` holds what those ids stand for. The
144/// host keeps namespace declarations out of the attributes.
145#[derive(Clone, Copy)]
146pub struct XmlTree<'a> {
147    tree: &'a Document,
148    names: &'a dyn Namespaces,
149}
150
151impl<'a> XmlTree<'a> {
152    pub fn new(tree: &'a Document, names: &'a dyn Namespaces) -> XmlTree<'a> {
153        XmlTree { tree, names }
154    }
155}
156
157fn local_part(name: &str) -> &str {
158    name.split_once(':').map_or(name, |(_, local)| local)
159}
160
161impl XmlTree<'_> {
162    fn attr(&self, n: NodeId, name: &str) -> Option<&str> {
163        self.tree
164            .attrs(n)
165            .find(|(_, k, _)| *k == name)
166            .map(|(_, _, v)| v)
167    }
168}
169
170impl Tree for XmlTree<'_> {
171    fn len(&self) -> usize {
172        self.tree.len()
173    }
174
175    fn kind(&self, n: NodeId) -> NodeType {
176        Tree::kind(self.tree, n)
177    }
178
179    fn parent(&self, n: NodeId) -> Option<NodeId> {
180        self.tree.parent(n)
181    }
182
183    fn first_child(&self, n: NodeId) -> Option<NodeId> {
184        self.tree.first_child(n)
185    }
186
187    fn next_sibling(&self, n: NodeId) -> Option<NodeId> {
188        self.tree.next_sibling(n)
189    }
190
191    fn prev_sibling(&self, n: NodeId) -> Option<NodeId> {
192        self.tree.prev_sibling(n)
193    }
194
195    fn qualified_name(&self, n: NodeId) -> &str {
196        self.tree.lower_name(n).unwrap_or("")
197    }
198
199    fn local_name(&self, n: NodeId) -> &str {
200        local_part(self.tree.lower_name(n).unwrap_or(""))
201    }
202
203    fn namespace_uri(&self, n: NodeId) -> &str {
204        self.names.uri(self.names.ns_of(n))
205    }
206
207    fn tag_key(&self, n: NodeId) -> TagKey<'_> {
208        self.tree.tag_key(n)
209    }
210
211    fn attribute_count(&self, n: NodeId) -> u32 {
212        self.tree.attribute_count(n)
213    }
214
215    fn attribute(&self, n: NodeId, i: u32) -> Option<Attr<'_>> {
216        self.tree
217            .attr_at(n, i as usize)
218            .map(|(ns, name, value)| Attr {
219                qualified_name: name,
220                local_name: local_part(name),
221                namespace_uri: match ns {
222                    AttrNs::Host(id) => self.names.uri(id),
223                    _ => "",
224                },
225                value,
226            })
227    }
228
229    fn namespace_declaration_count(&self, n: NodeId) -> u32 {
230        self.names.declaration_count(n)
231    }
232
233    fn namespace_declaration(&self, n: NodeId, i: u32) -> Option<(&str, &str)> {
234        self.names
235            .declaration(n, i)
236            .map(|(prefix, id)| (prefix, self.names.uri(id)))
237    }
238
239    fn data(&self, n: NodeId) -> &str {
240        self.tree.data(n)
241    }
242
243    fn pi_target(&self, n: NodeId) -> Option<&str> {
244        self.tree.pi_target(n)
245    }
246
247    fn is_xml(&self) -> bool {
248        true
249    }
250
251    fn id(&self, n: NodeId) -> Option<&str> {
252        self.attr(n, "id")
253    }
254
255    fn lang(&self, n: NodeId) -> Option<&str> {
256        self.attr(n, "xml:lang").or_else(|| self.attr(n, "lang"))
257    }
258}