lobzique 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +5 -0
  3. data/Cargo.lock +520 -0
  4. data/Cargo.toml +11 -0
  5. data/LICENSE-NOKOGIRI.md +15 -0
  6. data/LICENSE.txt +21 -0
  7. data/README.md +144 -0
  8. data/crates/lobzique-core/Cargo.toml +14 -0
  9. data/crates/lobzique-core/src/css/mod.rs +127 -0
  10. data/crates/lobzique-core/src/css/parser.rs +805 -0
  11. data/crates/lobzique-core/src/css/tables.rs +282 -0
  12. data/crates/lobzique-core/src/css/tests.rs +476 -0
  13. data/crates/lobzique-core/src/css/tokenizer.rs +215 -0
  14. data/crates/lobzique-core/src/css/translate.rs +806 -0
  15. data/crates/lobzique-core/src/css/write.rs +370 -0
  16. data/crates/lobzique-core/src/dom/attribute.rs +144 -0
  17. data/crates/lobzique-core/src/dom/check.rs +160 -0
  18. data/crates/lobzique-core/src/dom/copy.rs +229 -0
  19. data/crates/lobzique-core/src/dom/mod.rs +298 -0
  20. data/crates/lobzique-core/src/dom/namespace.rs +134 -0
  21. data/crates/lobzique-core/src/dom/node.rs +129 -0
  22. data/crates/lobzique-core/src/dom/path.rs +116 -0
  23. data/crates/lobzique-core/src/dom/reparent.rs +308 -0
  24. data/crates/lobzique-core/src/dom/tests.rs +1057 -0
  25. data/crates/lobzique-core/src/dom/text.rs +159 -0
  26. data/crates/lobzique-core/src/dom/tree.rs +446 -0
  27. data/crates/lobzique-core/src/html5/mod.rs +28 -0
  28. data/crates/lobzique-core/src/html5/parse.rs +838 -0
  29. data/crates/lobzique-core/src/html5/serialize.rs +181 -0
  30. data/crates/lobzique-core/src/html5/tests.rs +548 -0
  31. data/crates/lobzique-core/src/lib.rs +12 -0
  32. data/crates/lobzique-core/src/work.rs +26 -0
  33. data/crates/lobzique-core/src/xml/mod.rs +8 -0
  34. data/crates/lobzique-core/src/xml/serialize.rs +681 -0
  35. data/crates/lobzique-core/src/xml/tests.rs +174 -0
  36. data/crates/lobzique-core/src/xpath/ast.rs +415 -0
  37. data/crates/lobzique-core/src/xpath/chars.rs +139 -0
  38. data/crates/lobzique-core/src/xpath/eval.rs +1305 -0
  39. data/crates/lobzique-core/src/xpath/mod.rs +118 -0
  40. data/crates/lobzique-core/src/xpath/parse.rs +729 -0
  41. data/crates/lobzique-core/src/xpath/tests.rs +921 -0
  42. data/ext/lobzique/Cargo.toml +22 -0
  43. data/ext/lobzique/build.rs +5 -0
  44. data/ext/lobzique/clippy.toml +15 -0
  45. data/ext/lobzique/extconf.rb +6 -0
  46. data/ext/lobzique/src/css/mod.rs +9 -0
  47. data/ext/lobzique/src/css/parser.rs +44 -0
  48. data/ext/lobzique/src/css/selector.rs +101 -0
  49. data/ext/lobzique/src/html4/document.rs +31 -0
  50. data/ext/lobzique/src/html4/mod.rs +7 -0
  51. data/ext/lobzique/src/html5/mod.rs +16 -0
  52. data/ext/lobzique/src/html5ever.rs +278 -0
  53. data/ext/lobzique/src/lib.rs +45 -0
  54. data/ext/lobzique/src/support.rs +156 -0
  55. data/ext/lobzique/src/xml/attr.rs +27 -0
  56. data/ext/lobzique/src/xml/cdata.rs +33 -0
  57. data/ext/lobzique/src/xml/comment.rs +34 -0
  58. data/ext/lobzique/src/xml/document.rs +199 -0
  59. data/ext/lobzique/src/xml/document_fragment.rs +27 -0
  60. data/ext/lobzique/src/xml/dtd.rs +37 -0
  61. data/ext/lobzique/src/xml/mod.rs +44 -0
  62. data/ext/lobzique/src/xml/namespace.rs +56 -0
  63. data/ext/lobzique/src/xml/node.rs +944 -0
  64. data/ext/lobzique/src/xml/node_set.rs +20 -0
  65. data/ext/lobzique/src/xml/syntax_error.rs +33 -0
  66. data/ext/lobzique/src/xml/text.rs +44 -0
  67. data/ext/lobzique/src/xml/xpath_context.rs +305 -0
  68. data/lib/lobzique/action_text.rb +29 -0
  69. data/lib/lobzique/class_resolver.rb +33 -0
  70. data/lib/lobzique/css/selector_cache.rb +36 -0
  71. data/lib/lobzique/css/syntax_error.rb +12 -0
  72. data/lib/lobzique/css/xpath_visitor.rb +60 -0
  73. data/lib/lobzique/css.rb +57 -0
  74. data/lib/lobzique/extension.rb +31 -0
  75. data/lib/lobzique/html.rb +14 -0
  76. data/lib/lobzique/html4/document.rb +235 -0
  77. data/lib/lobzique/html4/document_fragment.rb +75 -0
  78. data/lib/lobzique/html4/encoding_reader.rb +374 -0
  79. data/lib/lobzique/html4.rb +35 -0
  80. data/lib/lobzique/html5/document.rb +106 -0
  81. data/lib/lobzique/html5/document_fragment.rb +113 -0
  82. data/lib/lobzique/html5/node.rb +66 -0
  83. data/lib/lobzique/html5.rb +92 -0
  84. data/lib/lobzique/html5ever.rb +14 -0
  85. data/lib/lobzique/rails_dom_testing.rb +95 -0
  86. data/lib/lobzique/sanitizer/concerns.rb +110 -0
  87. data/lib/lobzique/sanitizer/document.rb +14 -0
  88. data/lib/lobzique/sanitizer/document_fragment.rb +12 -0
  89. data/lib/lobzique/sanitizer/escape_raw_text_in_select.rb +31 -0
  90. data/lib/lobzique/sanitizer/scrubbers.rb +46 -0
  91. data/lib/lobzique/sanitizer.rb +96 -0
  92. data/lib/lobzique/syntax_error.rb +8 -0
  93. data/lib/lobzique/version.rb +6 -0
  94. data/lib/lobzique/xml/attr.rb +23 -0
  95. data/lib/lobzique/xml/cdata.rb +13 -0
  96. data/lib/lobzique/xml/character_data.rb +11 -0
  97. data/lib/lobzique/xml/document.rb +149 -0
  98. data/lib/lobzique/xml/document_fragment.rb +109 -0
  99. data/lib/lobzique/xml/dtd.rb +28 -0
  100. data/lib/lobzique/xml/namespace.rb +19 -0
  101. data/lib/lobzique/xml/node/save_options.rb +52 -0
  102. data/lib/lobzique/xml/node.rb +629 -0
  103. data/lib/lobzique/xml/node_set.rb +329 -0
  104. data/lib/lobzique/xml/parse_options.rb +89 -0
  105. data/lib/lobzique/xml/pp/character_data.rb +22 -0
  106. data/lib/lobzique/xml/pp/node.rb +73 -0
  107. data/lib/lobzique/xml/pp.rb +6 -0
  108. data/lib/lobzique/xml/searchable.rb +123 -0
  109. data/lib/lobzique/xml/syntax_error.rb +77 -0
  110. data/lib/lobzique/xml/text.rb +14 -0
  111. data/lib/lobzique/xml/xpath/syntax_error.rb +20 -0
  112. data/lib/lobzique/xml/xpath.rb +16 -0
  113. data/lib/lobzique/xml/xpath_context.rb +27 -0
  114. data/lib/lobzique/xml.rb +22 -0
  115. data/lib/lobzique.rb +15 -0
  116. metadata +177 -0
@@ -0,0 +1,229 @@
1
+ //! Copies nodes as libxml2's `xmlDocCopyNode` and `xmlCopyDoc` do. Used
2
+ //! for Nokogiri's `dup`, for nodes that move between documents, and for nodes
3
+ //! that are reparented as text.
4
+
5
+ use super::{Document, DocumentKind, NodeId, NodeKind, QualName};
6
+ use html5ever::{ns, LocalName, Namespace, Prefix};
7
+ use std::iter;
8
+
9
+ /// How much of a node a copy takes: Nokogiri's `dup(level)`. libxml2 reads
10
+ /// the level as 0, 2, or anything else.
11
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
12
+ pub enum CopyDepth {
13
+ /// The node alone. An element loses its attributes, namespace
14
+ /// definitions and namespace.
15
+ Shallow,
16
+ /// The node with its attributes and namespace definitions.
17
+ Attributes,
18
+ Deep,
19
+ }
20
+
21
+ impl CopyDepth {
22
+ pub fn from_level(level: i32) -> CopyDepth {
23
+ match level {
24
+ 0 => CopyDepth::Shallow,
25
+ 2 => CopyDepth::Attributes,
26
+ _ => CopyDepth::Deep,
27
+ }
28
+ }
29
+ }
30
+
31
+ impl Document {
32
+ /// A detached copy of a node of this document. Documents and doctypes
33
+ /// are not copied as nodes, so there is no copy for them.
34
+ pub fn copy(&mut self, id: NodeId, depth: CopyDepth) -> Option<NodeId> {
35
+ self.copy_from(None, id, depth)
36
+ }
37
+
38
+ pub fn import(&mut self, source: &Document, id: NodeId, depth: CopyDepth) -> Option<NodeId> {
39
+ self.copy_from(Some(source), id, depth)
40
+ }
41
+
42
+ /// `xmlCopyDoc`: the encoding and version. With `deep`, the whole tree.
43
+ /// Unlinked nodes stay behind.
44
+ pub fn copy_document(&self, deep: bool) -> Document {
45
+ let mut copy = Document::new(self.kind);
46
+ copy.encoding.clone_from(&self.encoding);
47
+ copy.version.clone_from(&self.version);
48
+ if !deep {
49
+ return copy;
50
+ }
51
+ for child in self.children(NodeId::DOCUMENT) {
52
+ let child = match self.node_kind(child) {
53
+ NodeKind::Doctype(doctype) => Some(copy.create_doctype(doctype.clone())),
54
+ _ => copy.import(self, child, CopyDepth::Deep),
55
+ };
56
+ if let Some(child) = child {
57
+ copy.append_child(NodeId::DOCUMENT, child)
58
+ .expect("a document takes what another document had");
59
+ }
60
+ }
61
+ copy
62
+ }
63
+
64
+ /// Walks the source subtree by its links, as `descendants` does. Depth then
65
+ /// uses no stack, and no borrow of a same-document source is held
66
+ /// while copies are made.
67
+ fn copy_from(
68
+ &mut self,
69
+ source: Option<&Document>,
70
+ id: NodeId,
71
+ depth: CopyDepth,
72
+ ) -> Option<NodeId> {
73
+ let root = self.copy_node(source, id, depth, None)?;
74
+ if depth != CopyDepth::Deep {
75
+ return Some(root);
76
+ }
77
+ // Each source node whose children are being copied, with its copy.
78
+ let mut open = vec![(id, root)];
79
+ let mut next = source.unwrap_or(self).first_child(id);
80
+ while let Some(node) = next {
81
+ let &(_, parent) = open.last().expect("the root stays open until the end");
82
+ let copy = self.copy_node(source, node, depth, Some((parent, root)));
83
+ let first_child = source.unwrap_or(self).first_child(node);
84
+ if let (Some(copy), Some(first_child)) = (copy, first_child) {
85
+ open.push((node, copy));
86
+ next = Some(first_child);
87
+ continue;
88
+ }
89
+ let mut finished = node;
90
+ next = loop {
91
+ if let Some(sibling) = source.unwrap_or(self).next_sibling(finished) {
92
+ break Some(sibling);
93
+ }
94
+ let (parent, _) = open.pop().expect("the root stays open until the end");
95
+ if open.is_empty() {
96
+ break None;
97
+ }
98
+ finished = parent;
99
+ };
100
+ }
101
+ Some(root)
102
+ }
103
+
104
+ /// Copies one node with its attributes and appends it to `parent`,
105
+ /// the first of `placement`. The second is the root of the copy,
106
+ /// where the namespaces that the copy needs are defined.
107
+ fn copy_node(
108
+ &mut self,
109
+ source: Option<&Document>,
110
+ id: NodeId,
111
+ depth: CopyDepth,
112
+ placement: Option<(NodeId, NodeId)>,
113
+ ) -> Option<NodeId> {
114
+ let src = source.unwrap_or(self);
115
+ let mut attributes = Vec::new();
116
+ let kind = match src.node_kind(id) {
117
+ NodeKind::Document | NodeKind::Doctype(_) => return None,
118
+ NodeKind::Element(element) if depth == CopyDepth::Shallow => {
119
+ let mut copy = element.clone();
120
+ copy.name = QualName::new(None, self.default_namespace(), copy.name.local);
121
+ copy.attributes.clear();
122
+ copy.namespace_definitions.clear();
123
+ NodeKind::Element(copy)
124
+ }
125
+ NodeKind::Element(element) => {
126
+ attributes = element
127
+ .attributes
128
+ .iter()
129
+ .filter_map(|&attribute| match src.node_kind(attribute) {
130
+ NodeKind::Attribute(attribute) => Some(attribute.clone()),
131
+ _ => None,
132
+ })
133
+ .collect();
134
+ let mut copy = element.clone();
135
+ copy.attributes.clear();
136
+ copy.name = adopt_name(copy.name, src.kind, self.kind);
137
+ NodeKind::Element(copy)
138
+ }
139
+ kind => kind.clone(),
140
+ };
141
+ let reconciles = matches!(kind, NodeKind::Element(_)) && depth != CopyDepth::Shallow
142
+ || matches!(kind, NodeKind::Attribute(_));
143
+ let copy = self.create(kind);
144
+ let root = match placement {
145
+ Some((parent, root)) => {
146
+ self.append_child(parent, copy)
147
+ .expect("a copy goes where its original was");
148
+ root
149
+ }
150
+ None => copy,
151
+ };
152
+ if reconciles {
153
+ self.reconcile_namespace(copy, root);
154
+ }
155
+ for attribute in attributes {
156
+ let attribute = self.create(NodeKind::Attribute(attribute));
157
+ self.append_attribute(copy, attribute)
158
+ .expect("attributes go on the element copy");
159
+ self.reconcile_namespace(attribute, root);
160
+ }
161
+ Some(copy)
162
+ }
163
+
164
+ /// A copied element or attribute whose namespace prefix has no definition
165
+ /// in the copy gets one on the root of the copy, as libxml2 defines
166
+ /// it when it copies. Only an element root can take one.
167
+ fn reconcile_namespace(&mut self, id: NodeId, root: NodeId) {
168
+ let Some(namespace) = self.namespace(id) else {
169
+ return;
170
+ };
171
+ let Some(prefix) = namespace.prefix.filter(|&prefix| prefix != "xml") else {
172
+ return;
173
+ };
174
+ let element = match self.node_kind(id) {
175
+ NodeKind::Attribute(_) => self.parent(id),
176
+ _ => Some(id),
177
+ };
178
+ let defined = element.is_some_and(|element| {
179
+ iter::once(element)
180
+ .chain(self.ancestors(element))
181
+ .flat_map(|node| self.namespace_definitions(node))
182
+ .any(|definition| definition.prefix.as_deref() == Some(prefix))
183
+ });
184
+ if !defined {
185
+ let (prefix, href) = (Prefix::from(prefix), Namespace::from(namespace.href));
186
+ self.define_namespace(root, Some(prefix), href);
187
+ }
188
+ }
189
+
190
+ /// The namespace of an element with none in libxml2's terms: HTML in HTML
191
+ /// documents, as for `Node.new`.
192
+ pub(super) fn default_namespace(&self) -> Namespace {
193
+ no_namespace(self.kind)
194
+ }
195
+
196
+ pub(super) fn rename(&mut self, id: NodeId, name: QualName) {
197
+ match &mut self.node_mut(id).kind {
198
+ NodeKind::Element(element) => element.name = name,
199
+ NodeKind::Attribute(attribute) => attribute.name = name,
200
+ _ => {}
201
+ }
202
+ }
203
+
204
+ pub(super) fn local_name(&self, id: NodeId) -> Option<&LocalName> {
205
+ match self.node_kind(id) {
206
+ NodeKind::Element(element) => Some(&element.name.local),
207
+ NodeKind::Attribute(attribute) => Some(&attribute.name.local),
208
+ _ => None,
209
+ }
210
+ }
211
+ }
212
+
213
+ /// What stands for no namespace, in libxml2's terms, in a kind of document.
214
+ fn no_namespace(kind: DocumentKind) -> Namespace {
215
+ match kind {
216
+ DocumentKind::Html => ns!(html),
217
+ DocumentKind::Xml => ns!(),
218
+ }
219
+ }
220
+
221
+ /// An element name from a document of kind `from`, as a document of kind
222
+ /// `to` writes it.
223
+ fn adopt_name(name: QualName, from: DocumentKind, to: DocumentKind) -> QualName {
224
+ if name.prefix.is_none() && name.ns == no_namespace(from) {
225
+ QualName::new(None, no_namespace(to), name.local)
226
+ } else {
227
+ name
228
+ }
229
+ }
@@ -0,0 +1,298 @@
1
+ //! The arena DOM. A [`Document`] owns every node created for it. It frees none
2
+ //! of them before it is dropped. Unlinked nodes stay valid, as in a libxml2
3
+ //! document that Nokogiri keeps them pinned to.
4
+ //!
5
+ //! Element and attribute names follow the HTML standard, so HTML elements
6
+ //! are in the HTML namespace. The bindings show that namespace as `nil`,
7
+ //! as Nokogiri does. Names are UTF-8 atoms that the parser and the selector
8
+ //! engine share. Everything else (text, attribute values, doctype fields)
9
+ //! is bytes kept exactly as given, as libxml2 keeps what Nokogiri passes it.
10
+
11
+ mod attribute;
12
+ mod check;
13
+ mod copy;
14
+ mod namespace;
15
+ mod node;
16
+ mod path;
17
+ mod reparent;
18
+ #[cfg(test)]
19
+ mod tests;
20
+ mod text;
21
+ mod tree;
22
+
23
+ pub use copy::CopyDepth;
24
+ pub use html5ever::{LocalName, Namespace, Prefix, QualName};
25
+ pub use namespace::{NamespaceDefinition, NamespaceRef};
26
+ pub use node::{Attribute, Doctype, Element, NodeKind, NodeType, ProcessingInstruction};
27
+ pub use reparent::{Position, ReparentError};
28
+ pub use text::{c_string, encode_special_chars};
29
+ pub use tree::{Ancestors, Children, Descendants, HierarchyError};
30
+
31
+ use node::Node;
32
+ use std::cell::{Cell, OnceCell};
33
+ use std::mem::size_of;
34
+ use std::num::NonZeroU32;
35
+
36
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
37
+ pub struct NodeId(NonZeroU32);
38
+
39
+ impl NodeId {
40
+ pub const DOCUMENT: NodeId = NodeId(NonZeroU32::MIN);
41
+
42
+ pub fn index(self) -> usize {
43
+ self.0.get() as usize - 1
44
+ }
45
+
46
+ fn from_index(index: usize) -> NodeId {
47
+ u32::try_from(index + 1)
48
+ .ok()
49
+ .and_then(NonZeroU32::new)
50
+ .map(NodeId)
51
+ .expect("a document holds fewer than 2^32 nodes")
52
+ }
53
+ }
54
+
55
+ /// Whether a document came from the HTML or the XML side. This decides its node
56
+ /// type, as libxml2's `htmlDocPtr` and `xmlDocPtr` do.
57
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
58
+ pub enum DocumentKind {
59
+ Html,
60
+ Xml,
61
+ }
62
+
63
+ #[derive(Clone, Debug)]
64
+ pub struct Document {
65
+ kind: DocumentKind,
66
+ nodes: Vec<Node>,
67
+ /// libxml2's `doc->encoding`: a label, kept as given.
68
+ encoding: Option<Vec<u8>>,
69
+ /// libxml2's `doc->version`. Only XML documents have it.
70
+ version: Option<Vec<u8>>,
71
+ /// The tree root and position in that tree of each node. Built
72
+ /// when comparisons have walked as many links as there are nodes. Dropped
73
+ /// when the tree changes (`tree::document_order`).
74
+ order: OnceCell<Vec<(NodeId, u32)>>,
75
+ order_walked: Cell<usize>,
76
+ }
77
+
78
+ impl Document {
79
+ pub fn new(kind: DocumentKind) -> Document {
80
+ Document {
81
+ kind,
82
+ nodes: vec![Node::new(NodeKind::Document)],
83
+ encoding: None,
84
+ version: None,
85
+ order: OnceCell::new(),
86
+ order_walked: Cell::new(0),
87
+ }
88
+ }
89
+
90
+ /// An HTML document with the doctype that libxml2's `htmlNewDoc` gives
91
+ /// it. `HTML4::Document.new`, and so `HTML5::Document.new`, start with it.
92
+ pub fn new_html4(system_id: Option<Vec<u8>>, public_id: Option<Vec<u8>>) -> Document {
93
+ let mut document = Document::new(DocumentKind::Html);
94
+ let doctype = if system_id.is_none() && public_id.is_none() {
95
+ Doctype {
96
+ name: "html".into(),
97
+ public_id: Some("-//W3C//DTD HTML 4.0 Transitional//EN".into()),
98
+ system_id: Some("http://www.w3.org/TR/REC-html40/loose.dtd".into()),
99
+ }
100
+ } else {
101
+ Doctype {
102
+ name: "html".into(),
103
+ public_id,
104
+ system_id,
105
+ }
106
+ };
107
+ let doctype = document.create_doctype(doctype);
108
+ document
109
+ .append_child(NodeId::DOCUMENT, doctype)
110
+ .expect("a new document takes a doctype");
111
+ document
112
+ }
113
+
114
+ pub fn kind(&self) -> DocumentKind {
115
+ self.kind
116
+ }
117
+
118
+ pub fn encoding(&self) -> Option<&[u8]> {
119
+ self.encoding.as_deref()
120
+ }
121
+
122
+ pub fn set_encoding(&mut self, encoding: Option<Vec<u8>>) {
123
+ self.encoding = encoding;
124
+ }
125
+
126
+ pub fn version(&self) -> Option<&[u8]> {
127
+ self.version.as_deref()
128
+ }
129
+
130
+ pub fn set_version(&mut self, version: Option<Vec<u8>>) {
131
+ self.version = version;
132
+ }
133
+
134
+ pub fn node_ids(&self) -> impl ExactSizeIterator<Item = NodeId> {
135
+ (0..self.nodes.len()).map(NodeId::from_index)
136
+ }
137
+
138
+ pub fn node_kind(&self, id: NodeId) -> &NodeKind {
139
+ &self.node(id).kind
140
+ }
141
+
142
+ pub fn node_type(&self, id: NodeId) -> NodeType {
143
+ match self.node_kind(id) {
144
+ NodeKind::Document => match self.kind {
145
+ DocumentKind::Html => NodeType::HtmlDocument,
146
+ DocumentKind::Xml => NodeType::Document,
147
+ },
148
+ kind => kind.node_type(),
149
+ }
150
+ }
151
+
152
+ pub fn node_name(&self, id: NodeId) -> Option<&[u8]> {
153
+ match self.node_kind(id) {
154
+ NodeKind::Element(element) => Some(element.name.local.as_bytes()),
155
+ NodeKind::Attribute(attribute) => Some(attribute.name.local.as_bytes()),
156
+ NodeKind::Text(_) => Some(b"text"),
157
+ NodeKind::Comment(_) => Some(b"comment"),
158
+ NodeKind::Doctype(doctype) => Some(&doctype.name),
159
+ NodeKind::ProcessingInstruction(pi) => Some(&pi.target),
160
+ NodeKind::Document | NodeKind::DocumentFragment | NodeKind::CData(_) => None,
161
+ }
162
+ }
163
+
164
+ /// libxml2's `xmlNodeSetName`: renames an element or attribute and keeps
165
+ /// its namespace, or renames a doctype or processing instruction. Other
166
+ /// nodes keep their fixed names.
167
+ pub fn set_name(&mut self, id: NodeId, name: &str) {
168
+ match &mut self.node_mut(id).kind {
169
+ NodeKind::Element(Element {
170
+ name: qual_name, ..
171
+ })
172
+ | NodeKind::Attribute(Attribute {
173
+ name: qual_name, ..
174
+ }) => qual_name.local = LocalName::from(name),
175
+ NodeKind::Doctype(doctype) => doctype.name = name.into(),
176
+ NodeKind::ProcessingInstruction(pi) => pi.target = name.into(),
177
+ _ => {}
178
+ }
179
+ }
180
+
181
+ pub fn create_element(&mut self, name: QualName) -> NodeId {
182
+ self.create(NodeKind::Element(Element {
183
+ name,
184
+ attributes: Vec::new(),
185
+ namespace_definitions: Vec::new(),
186
+ }))
187
+ }
188
+
189
+ /// An element as `Node.new` makes it: the name is taken
190
+ /// as is. It is in the HTML namespace in HTML documents and in none in XML
191
+ /// documents.
192
+ pub fn create_element_named(&mut self, name: &str) -> NodeId {
193
+ let namespace = self.default_namespace();
194
+ self.create_element(QualName::new(None, namespace, LocalName::from(name)))
195
+ }
196
+
197
+ pub fn doctype(&self) -> Option<NodeId> {
198
+ self.children(NodeId::DOCUMENT)
199
+ .find(|&child| matches!(self.node_kind(child), NodeKind::Doctype(_)))
200
+ }
201
+
202
+ /// `Document#root=`, libxml2's `xmlDocSetRootElement`: the root element
203
+ /// is unlinked and the new one, if any, is appended to the document.
204
+ pub fn set_root(&mut self, root: Option<NodeId>) -> Result<(), HierarchyError> {
205
+ if root.is_some_and(|root| !matches!(self.node_kind(root), NodeKind::Element(_))) {
206
+ return Err(HierarchyError::NotAnElement);
207
+ }
208
+ let current = self.element_children(NodeId::DOCUMENT).next();
209
+ if let Some(current) = current {
210
+ self.detach(current);
211
+ }
212
+ root.map_or(Ok(()), |root| self.append_child(NodeId::DOCUMENT, root))
213
+ }
214
+
215
+ /// libxml2's `xmlCreateIntSubset`: first in an HTML document, before
216
+ /// the root element in an XML document. `None` if there is a doctype
217
+ /// already.
218
+ pub fn create_internal_subset(&mut self, doctype: Doctype) -> Option<NodeId> {
219
+ if self.doctype().is_some() {
220
+ return None;
221
+ }
222
+ let next = match self.kind {
223
+ DocumentKind::Html => self.first_child(NodeId::DOCUMENT),
224
+ DocumentKind::Xml => self.element_children(NodeId::DOCUMENT).next(),
225
+ };
226
+ let doctype = self.create_doctype(doctype);
227
+ match next {
228
+ Some(next) => self.insert_before(next, doctype),
229
+ None => self.append_child(NodeId::DOCUMENT, doctype),
230
+ }
231
+ .expect("a document takes a doctype");
232
+ Some(doctype)
233
+ }
234
+
235
+ pub fn create_attribute(&mut self, name: QualName, value: Vec<u8>) -> NodeId {
236
+ self.create(NodeKind::Attribute(Attribute { name, value }))
237
+ }
238
+
239
+ pub fn create_text(&mut self, text: Vec<u8>) -> NodeId {
240
+ self.create(NodeKind::Text(text))
241
+ }
242
+
243
+ pub fn create_cdata(&mut self, text: Vec<u8>) -> NodeId {
244
+ self.create(NodeKind::CData(text))
245
+ }
246
+
247
+ pub fn create_comment(&mut self, text: Vec<u8>) -> NodeId {
248
+ self.create(NodeKind::Comment(text))
249
+ }
250
+
251
+ pub fn create_fragment(&mut self) -> NodeId {
252
+ self.create(NodeKind::DocumentFragment)
253
+ }
254
+
255
+ pub fn create_doctype(&mut self, doctype: Doctype) -> NodeId {
256
+ self.create(NodeKind::Doctype(doctype))
257
+ }
258
+
259
+ pub fn create_processing_instruction(&mut self, target: Vec<u8>, data: Vec<u8>) -> NodeId {
260
+ self.create(NodeKind::ProcessingInstruction(ProcessingInstruction {
261
+ target,
262
+ data,
263
+ }))
264
+ }
265
+
266
+ /// Bytes that the arena holds on the heap, for `ObjectSpace.memsize_of`.
267
+ /// Walks every node.
268
+ pub fn heap_size(&self) -> usize {
269
+ self.nodes.capacity() * size_of::<Node>()
270
+ + self.encoding.as_ref().map_or(0, Vec::capacity)
271
+ + self
272
+ .order
273
+ .get()
274
+ .map_or(0, |order| order.capacity() * size_of::<(NodeId, u32)>())
275
+ + self
276
+ .nodes
277
+ .iter()
278
+ .map(|node| node.kind.heap_size())
279
+ .sum::<usize>()
280
+ }
281
+
282
+ fn create(&mut self, kind: NodeKind) -> NodeId {
283
+ crate::work::add(1);
284
+ let id = NodeId::from_index(self.nodes.len());
285
+ self.nodes.push(Node::new(kind));
286
+ id
287
+ }
288
+
289
+ fn node(&self, id: NodeId) -> &Node {
290
+ crate::work::add(1);
291
+ &self.nodes[id.index()]
292
+ }
293
+
294
+ fn node_mut(&mut self, id: NodeId) -> &mut Node {
295
+ crate::work::add(1);
296
+ &mut self.nodes[id.index()]
297
+ }
298
+ }
@@ -0,0 +1,134 @@
1
+ //! Namespaces as libxml2 records them for Nokogiri. An element or attribute
2
+ //! is in at most one namespace. Elements carry the definitions that bring
3
+ //! prefixes into scope (libxml2's `nsDef`).
4
+
5
+ use super::{Document, NodeId, NodeKind};
6
+ use html5ever::{ns, Namespace, Prefix};
7
+ use std::iter;
8
+
9
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
10
+ pub struct NamespaceRef<'a> {
11
+ pub prefix: Option<&'a str>,
12
+ pub href: &'a str,
13
+ }
14
+
15
+ #[derive(Clone, Debug, PartialEq, Eq)]
16
+ pub struct NamespaceDefinition {
17
+ pub prefix: Option<Prefix>,
18
+ pub href: Namespace,
19
+ }
20
+
21
+ impl<'a> From<&'a NamespaceDefinition> for NamespaceRef<'a> {
22
+ fn from(definition: &'a NamespaceDefinition) -> NamespaceRef<'a> {
23
+ NamespaceRef {
24
+ prefix: definition.prefix.as_deref(),
25
+ href: &definition.href,
26
+ }
27
+ }
28
+ }
29
+
30
+ /// `prefix:local` split at the first colon, as libxml2's `xmlSplitQName2`
31
+ /// splits it. `None` when either side would be empty.
32
+ pub(super) fn split_qualified_name(name: &str) -> Option<(&str, &str)> {
33
+ name.split_once(':')
34
+ .filter(|(prefix, local)| !prefix.is_empty() && !local.is_empty())
35
+ }
36
+
37
+ const XML: NamespaceRef<'static> = NamespaceRef {
38
+ prefix: Some("xml"),
39
+ href: "http://www.w3.org/XML/1998/namespace",
40
+ };
41
+
42
+ impl Document {
43
+ /// The namespace of the node as Nokogiri shows it after an HTML5 parse:
44
+ /// none for HTML elements, and the prefix that gumbo gives each foreign
45
+ /// namespace.
46
+ pub fn namespace(&self, id: NodeId) -> Option<NamespaceRef<'_>> {
47
+ let (name, prefixes): (_, &[(Namespace, &str)]) = match self.node_kind(id) {
48
+ NodeKind::Element(element) => {
49
+ (&element.name, &[(ns!(svg), "svg"), (ns!(mathml), "math")])
50
+ }
51
+ NodeKind::Attribute(attribute) => (
52
+ &attribute.name,
53
+ &[
54
+ (ns!(xlink), "xlink"),
55
+ (ns!(xml), "xml"),
56
+ (ns!(xmlns), "xmlns"),
57
+ ],
58
+ ),
59
+ _ => return None,
60
+ };
61
+ if name.ns == ns!() || name.ns == ns!(html) {
62
+ return None;
63
+ }
64
+ let prefix = prefixes
65
+ .iter()
66
+ .find(|(namespace, _)| *namespace == name.ns)
67
+ .map(|&(_, prefix)| prefix)
68
+ .or(name.prefix.as_deref());
69
+ Some(NamespaceRef {
70
+ prefix,
71
+ href: &name.ns,
72
+ })
73
+ }
74
+
75
+ pub fn namespace_definitions(&self, id: NodeId) -> &[NamespaceDefinition] {
76
+ match self.node_kind(id) {
77
+ NodeKind::Element(element) => &element.namespace_definitions,
78
+ _ => &[],
79
+ }
80
+ }
81
+
82
+ /// Defines a namespace on an element, unless its prefix already has a
83
+ /// definition there, as libxml2's `xmlNewNs` does. Other nodes take none.
84
+ pub fn define_namespace(&mut self, element: NodeId, prefix: Option<Prefix>, href: Namespace) {
85
+ if let NodeKind::Element(element) = &mut self.node_mut(element).kind {
86
+ let definitions = &mut element.namespace_definitions;
87
+ if definitions.iter().all(|defined| defined.prefix != prefix) {
88
+ definitions.push(NamespaceDefinition { prefix, href });
89
+ }
90
+ }
91
+ }
92
+
93
+ /// Every namespace in scope at the node, nearest definition first, one
94
+ /// per prefix: libxml2's `xmlGetNsList`.
95
+ pub fn namespace_scopes(&self, id: NodeId) -> Vec<NamespaceRef<'_>> {
96
+ let mut scopes: Vec<NamespaceRef<'_>> = Vec::new();
97
+ for node in iter::once(id).chain(self.ancestors(id)) {
98
+ for definition in self.namespace_definitions(node) {
99
+ let definition = NamespaceRef::from(definition);
100
+ if scopes.iter().all(|scope| scope.prefix != definition.prefix) {
101
+ scopes.push(definition);
102
+ }
103
+ }
104
+ }
105
+ scopes
106
+ }
107
+
108
+ /// The namespace that `prefix` refers to at the node: libxml2's
109
+ /// `xmlSearchNs`. It also accepts the namespace of an ancestor element
110
+ /// that has no definition in scope.
111
+ pub fn search_namespace(&self, id: NodeId, prefix: &[u8]) -> Option<NamespaceRef<'_>> {
112
+ if prefix == b"xml" {
113
+ return Some(XML);
114
+ }
115
+ let has_prefix =
116
+ |namespace: &NamespaceRef<'_>| namespace.prefix.map(str::as_bytes) == Some(prefix);
117
+ for node in iter::once(id).chain(self.ancestors(id)) {
118
+ let defined = self
119
+ .namespace_definitions(node)
120
+ .iter()
121
+ .map(NamespaceRef::from)
122
+ .find(has_prefix);
123
+ if defined.is_some() {
124
+ return defined;
125
+ }
126
+ if node != id && matches!(self.node_kind(node), NodeKind::Element(_)) {
127
+ if let Some(namespace) = self.namespace(node).filter(has_prefix) {
128
+ return Some(namespace);
129
+ }
130
+ }
131
+ }
132
+ None
133
+ }
134
+ }