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,129 @@
1
+ use super::{NamespaceDefinition, NodeId, QualName};
2
+ use std::mem::size_of;
3
+
4
+ /// Node types numbered as libxml2 numbers them. Nokogiri's `Node#type`
5
+ /// and `Node::*_NODE` constants expose them.
6
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
7
+ #[repr(u8)]
8
+ pub enum NodeType {
9
+ Element = 1,
10
+ Attribute = 2,
11
+ Text = 3,
12
+ CDataSection = 4,
13
+ ProcessingInstruction = 7,
14
+ Comment = 8,
15
+ Document = 9,
16
+ DocumentFragment = 11,
17
+ HtmlDocument = 13,
18
+ Dtd = 14,
19
+ }
20
+
21
+ #[derive(Clone, Debug)]
22
+ pub enum NodeKind {
23
+ Document,
24
+ DocumentFragment,
25
+ Element(Element),
26
+ Attribute(Attribute),
27
+ Text(Vec<u8>),
28
+ CData(Vec<u8>),
29
+ Comment(Vec<u8>),
30
+ Doctype(Doctype),
31
+ ProcessingInstruction(ProcessingInstruction),
32
+ }
33
+
34
+ impl NodeKind {
35
+ /// The type of every kind except `Document`. The type of a `Document`
36
+ /// depends on its [`super::DocumentKind`].
37
+ pub(super) fn node_type(&self) -> NodeType {
38
+ match self {
39
+ NodeKind::Document => NodeType::Document,
40
+ NodeKind::DocumentFragment => NodeType::DocumentFragment,
41
+ NodeKind::Element(_) => NodeType::Element,
42
+ NodeKind::Attribute(_) => NodeType::Attribute,
43
+ NodeKind::Text(_) => NodeType::Text,
44
+ NodeKind::CData(_) => NodeType::CDataSection,
45
+ NodeKind::Comment(_) => NodeType::Comment,
46
+ NodeKind::Doctype(_) => NodeType::Dtd,
47
+ NodeKind::ProcessingInstruction(_) => NodeType::ProcessingInstruction,
48
+ }
49
+ }
50
+
51
+ /// Interned names belong to the atom table of html5ever, not to the node.
52
+ pub(super) fn heap_size(&self) -> usize {
53
+ match self {
54
+ NodeKind::Document | NodeKind::DocumentFragment => 0,
55
+ NodeKind::Element(element) => {
56
+ element.attributes.capacity() * size_of::<NodeId>()
57
+ + element.namespace_definitions.capacity() * size_of::<NamespaceDefinition>()
58
+ }
59
+ NodeKind::Attribute(attribute) => attribute.value.capacity(),
60
+ NodeKind::Text(text) | NodeKind::CData(text) | NodeKind::Comment(text) => {
61
+ text.capacity()
62
+ }
63
+ NodeKind::Doctype(doctype) => {
64
+ doctype.name.capacity()
65
+ + doctype.public_id.as_ref().map_or(0, Vec::capacity)
66
+ + doctype.system_id.as_ref().map_or(0, Vec::capacity)
67
+ }
68
+ NodeKind::ProcessingInstruction(pi) => pi.target.capacity() + pi.data.capacity(),
69
+ }
70
+ }
71
+
72
+ pub(super) fn can_have_children(&self) -> bool {
73
+ matches!(
74
+ self,
75
+ NodeKind::Document | NodeKind::DocumentFragment | NodeKind::Element(_)
76
+ )
77
+ }
78
+ }
79
+
80
+ #[derive(Clone, Debug)]
81
+ pub struct Element {
82
+ pub name: QualName,
83
+ /// Attribute nodes in source order. The parent of each is this element,
84
+ /// but it is not one of the children of the element.
85
+ pub attributes: Vec<NodeId>,
86
+ pub namespace_definitions: Vec<NamespaceDefinition>,
87
+ }
88
+
89
+ #[derive(Clone, Debug)]
90
+ pub struct Attribute {
91
+ pub name: QualName,
92
+ pub value: Vec<u8>,
93
+ }
94
+
95
+ #[derive(Clone, Debug, PartialEq, Eq)]
96
+ pub struct Doctype {
97
+ pub name: Vec<u8>,
98
+ pub public_id: Option<Vec<u8>>,
99
+ pub system_id: Option<Vec<u8>>,
100
+ }
101
+
102
+ #[derive(Clone, Debug)]
103
+ pub struct ProcessingInstruction {
104
+ pub target: Vec<u8>,
105
+ pub data: Vec<u8>,
106
+ }
107
+
108
+ #[derive(Clone, Debug)]
109
+ pub(super) struct Node {
110
+ pub(super) kind: NodeKind,
111
+ pub(super) parent: Option<NodeId>,
112
+ pub(super) previous_sibling: Option<NodeId>,
113
+ pub(super) next_sibling: Option<NodeId>,
114
+ pub(super) first_child: Option<NodeId>,
115
+ pub(super) last_child: Option<NodeId>,
116
+ }
117
+
118
+ impl Node {
119
+ pub(super) fn new(kind: NodeKind) -> Node {
120
+ Node {
121
+ kind,
122
+ parent: None,
123
+ previous_sibling: None,
124
+ next_sibling: None,
125
+ first_child: None,
126
+ last_child: None,
127
+ }
128
+ }
129
+ }
@@ -0,0 +1,116 @@
1
+ use super::{Document, NamespaceRef, NodeId, NodeKind};
2
+
3
+ impl Document {
4
+ /// libxml2's `xmlGetNodePath`, which Nokogiri's `Node#path` returns: a step
5
+ /// for each ancestor, numbered when siblings share the step name. `None`
6
+ /// where libxml2 gives up, at a doctype or a fragment. Nokogiri shows
7
+ /// it as `"?"`. Nodes in a fragment have no path either.
8
+ pub fn path(&self, id: NodeId) -> Option<Vec<u8>> {
9
+ let mut steps = Vec::new();
10
+ let mut next = Some(id);
11
+ while let Some(node) = next {
12
+ next = self.parent(node);
13
+ let (separator, name, position): (&[u8], _, _) = match self.node_kind(node) {
14
+ NodeKind::Document if steps.is_empty() => (b"/", Vec::new(), None),
15
+ NodeKind::Document => break,
16
+ NodeKind::Element(element) => {
17
+ let local = &element.name.local;
18
+ let namespace = self.namespace(node);
19
+ let name = match namespace {
20
+ Some(NamespaceRef {
21
+ prefix: Some(prefix),
22
+ ..
23
+ }) => qualified(prefix, local),
24
+ // libxml2 cannot name an element in a default
25
+ // namespace, so it counts every element as a match.
26
+ Some(_) => b"*".to_vec(),
27
+ None => local.as_bytes().to_vec(),
28
+ };
29
+ let any_element = namespace.is_some_and(|namespace| namespace.prefix.is_none());
30
+ let prefix = namespace.map(|namespace| namespace.prefix);
31
+ let position = self.position(node, |other| match self.node_kind(other) {
32
+ NodeKind::Element(other_element) => {
33
+ any_element
34
+ || other_element.name.local == *local
35
+ && self.namespace(other).map(|namespace| namespace.prefix)
36
+ == prefix
37
+ }
38
+ _ => false,
39
+ });
40
+ (b"/", name, position)
41
+ }
42
+ NodeKind::Comment(_) => {
43
+ let position = self.position(node, |other| {
44
+ matches!(self.node_kind(other), NodeKind::Comment(_))
45
+ });
46
+ (b"/", b"comment()".to_vec(), position)
47
+ }
48
+ NodeKind::Text(_) | NodeKind::CData(_) => {
49
+ let position = self.position(node, |other| {
50
+ matches!(
51
+ self.node_kind(other),
52
+ NodeKind::Text(_) | NodeKind::CData(_)
53
+ )
54
+ });
55
+ (b"/", b"text()".to_vec(), position)
56
+ }
57
+ NodeKind::ProcessingInstruction(pi) => {
58
+ let mut name = b"processing-instruction('".to_vec();
59
+ name.extend_from_slice(&pi.target);
60
+ name.extend_from_slice(b"')");
61
+ let position = self.position(node, |other| {
62
+ matches!(self.node_kind(other), NodeKind::ProcessingInstruction(other) if other.target == pi.target)
63
+ });
64
+ (b"/", truncated(name), position)
65
+ }
66
+ NodeKind::Attribute(attribute) => {
67
+ let local = &attribute.name.local;
68
+ let name = match self.namespace(node) {
69
+ Some(namespace) => match namespace.prefix {
70
+ Some(prefix) => qualified(prefix, local),
71
+ None => truncated(local.as_bytes().to_vec()),
72
+ },
73
+ None => local.as_bytes().to_vec(),
74
+ };
75
+ (b"/@", name, None)
76
+ }
77
+ NodeKind::Doctype(_) | NodeKind::DocumentFragment => return None,
78
+ };
79
+ steps.push((separator, name, position));
80
+ }
81
+
82
+ let mut path = Vec::new();
83
+ for (separator, name, position) in steps.into_iter().rev() {
84
+ path.extend_from_slice(separator);
85
+ path.extend_from_slice(&name);
86
+ if let Some(position) = position {
87
+ path.extend_from_slice(format!("[{position}]").as_bytes());
88
+ }
89
+ }
90
+ Some(path)
91
+ }
92
+
93
+ /// The position of the node among the siblings that `same_step` accepts.
94
+ /// `None` if it is the only one.
95
+ fn position(&self, id: NodeId, same_step: impl Fn(NodeId) -> bool) -> Option<usize> {
96
+ let mut before = 0;
97
+ let mut previous = self.previous_sibling(id);
98
+ while let Some(sibling) = previous {
99
+ before += usize::from(same_step(sibling));
100
+ previous = self.previous_sibling(sibling);
101
+ }
102
+ let mut following =
103
+ std::iter::successors(self.next_sibling(id), |&sibling| self.next_sibling(sibling));
104
+ (before > 0 || following.any(same_step)).then_some(before + 1)
105
+ }
106
+ }
107
+
108
+ fn qualified(prefix: &str, local: &str) -> Vec<u8> {
109
+ truncated(format!("{prefix}:{local}").into_bytes())
110
+ }
111
+
112
+ /// libxml2 formats generated step names in a buffer of 100 bytes.
113
+ fn truncated(mut name: Vec<u8>) -> Vec<u8> {
114
+ name.truncate(98);
115
+ name
116
+ }
@@ -0,0 +1,308 @@
1
+ //! Nokogiri's `reparent_node_with` over libxml2 2.13: which nodes can go
2
+ //! where, the copies of text and of nodes from other documents, text merging,
3
+ //! and the namespace fixes afterwards (`relink_namespace`).
4
+
5
+ use super::namespace::split_qualified_name;
6
+ use super::{CopyDepth, Document, NodeId, NodeKind, NodeType, QualName};
7
+ use html5ever::{LocalName, Namespace, Prefix};
8
+ use std::{fmt, mem};
9
+
10
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
11
+ pub enum Position {
12
+ /// `add_child_node`, through `xmlAddChild`.
13
+ LastChild,
14
+ /// `add_previous_sibling_node`, through `xmlAddPrevSibling`.
15
+ Before,
16
+ /// `add_next_sibling_node`, through `xmlAddNextSibling`.
17
+ After,
18
+ /// `replace_node`, through `xmlReplaceNode`.
19
+ Replace,
20
+ }
21
+
22
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
23
+ pub enum ReparentError {
24
+ /// The DOM check of Nokogiri refuses this kind of node under this parent.
25
+ NotAllowed,
26
+ /// libxml2 refuses to put a node into or next to itself, or next to a node
27
+ /// with no parent or an attribute. Nokogiri raises after it unlinks
28
+ /// the node. Here nothing has changed.
29
+ Refused,
30
+ /// The node would become its own ancestor. Nokogiri raises after libxml2
31
+ /// has linked the cycle. Here nothing has changed.
32
+ Cycle,
33
+ }
34
+
35
+ impl fmt::Display for ReparentError {
36
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37
+ f.write_str(match self {
38
+ ReparentError::NotAllowed => "node can't go there",
39
+ ReparentError::Refused => "could not reparent node",
40
+ ReparentError::Cycle => "node would become its own ancestor",
41
+ })
42
+ }
43
+ }
44
+
45
+ impl std::error::Error for ReparentError {}
46
+
47
+ impl Document {
48
+ /// Moves a node of this document relative to `pivot`. Returns what is now
49
+ /// in the tree for it: the node, its copy if it is text, or the text node
50
+ /// that the copy merged into.
51
+ pub fn reparent(
52
+ &mut self,
53
+ pivot: NodeId,
54
+ position: Position,
55
+ node: NodeId,
56
+ namespace_inheritance: bool,
57
+ ) -> Result<NodeId, ReparentError> {
58
+ self.reparent_with(pivot, position, None, node, namespace_inheritance)
59
+ }
60
+
61
+ /// [`Document::reparent`] for a node of another document. It is copied
62
+ /// into this one and unlinked from its own.
63
+ pub fn reparent_from(
64
+ &mut self,
65
+ pivot: NodeId,
66
+ position: Position,
67
+ source: &mut Document,
68
+ node: NodeId,
69
+ namespace_inheritance: bool,
70
+ ) -> Result<NodeId, ReparentError> {
71
+ self.reparent_with(pivot, position, Some(source), node, namespace_inheritance)
72
+ }
73
+
74
+ fn reparent_with(
75
+ &mut self,
76
+ pivot: NodeId,
77
+ position: Position,
78
+ source: Option<&mut Document>,
79
+ node: NodeId,
80
+ namespace_inheritance: bool,
81
+ ) -> Result<NodeId, ReparentError> {
82
+ let parent = match position {
83
+ Position::LastChild => Some(pivot),
84
+ _ => self.parent(pivot),
85
+ };
86
+ let node_type = source.as_deref().unwrap_or(self).node_type(node);
87
+ let is_self = source.is_none() && pivot == node;
88
+ if let Some(parent) = parent {
89
+ if !may_contain(self.node_type(parent), node_type) {
90
+ return Err(ReparentError::NotAllowed);
91
+ }
92
+ }
93
+
94
+ let is_text = node_type == NodeType::Text;
95
+ let beside_itself =
96
+ is_self && is_text && matches!(position, Position::Before | Position::After);
97
+ // An attribute has an element but no siblings.
98
+ let no_siblings = parent.is_none() || self.node_type(pivot) == NodeType::Attribute;
99
+ if (is_self || (position != Position::LastChild && no_siblings)) && !beside_itself {
100
+ return Err(ReparentError::Refused);
101
+ }
102
+ let inserted = if source.is_some() || is_text {
103
+ let copy = match source.as_deref() {
104
+ Some(source) => self.import(source, node, CopyDepth::Deep),
105
+ None => self.copy(node, CopyDepth::Deep),
106
+ };
107
+ copy.ok_or(ReparentError::Refused)?
108
+ } else {
109
+ if parent
110
+ .is_some_and(|parent| parent == node || self.ancestors(parent).any(|a| a == node))
111
+ {
112
+ return Err(ReparentError::Cycle);
113
+ }
114
+ node
115
+ };
116
+ match source {
117
+ Some(source) => source.detach(node),
118
+ None => self.detach(node),
119
+ }
120
+ if beside_itself {
121
+ // Text next to itself: Nokogiri links the copy beside the unlinked
122
+ // original, outside any tree. Siblings need a parent here,
123
+ // so the copy stays detached.
124
+ return Ok(inserted);
125
+ }
126
+
127
+ let reparented = match position {
128
+ Position::LastChild => self.append_merging_text(pivot, inserted),
129
+ Position::Before => self.insert_before(pivot, inserted).map(|()| inserted),
130
+ Position::After => self.insert_after(pivot, inserted).map(|()| inserted),
131
+ Position::Replace => self.replace_merging_text(pivot, inserted),
132
+ }
133
+ .expect("the checks above cover the tree's");
134
+ self.relink_namespaces(reparented, namespace_inheritance);
135
+ Ok(reparented)
136
+ }
137
+
138
+ /// `xmlAddChild`: text added after a text node goes into that node.
139
+ fn append_merging_text(
140
+ &mut self,
141
+ parent: NodeId,
142
+ node: NodeId,
143
+ ) -> Result<NodeId, super::HierarchyError> {
144
+ if let Some(last) = self.last_child(parent) {
145
+ if self.merge_text(last, node) {
146
+ return Ok(last);
147
+ }
148
+ }
149
+ self.append_child(parent, node)?;
150
+ Ok(node)
151
+ }
152
+
153
+ /// `xmlReplaceNode`, then the merge of Nokogiri for a text replacement
154
+ /// with the text on each side. The text after it is first replaced
155
+ /// by a copy. The original can have an object, so it must not be merged
156
+ /// away.
157
+ fn replace_merging_text(
158
+ &mut self,
159
+ pivot: NodeId,
160
+ node: NodeId,
161
+ ) -> Result<NodeId, super::HierarchyError> {
162
+ let is_text = |document: &Document, id| matches!(document.node_kind(id), NodeKind::Text(_));
163
+ if is_text(self, node) {
164
+ if let Some(next) = self.next_sibling(pivot).filter(|&next| is_text(self, next)) {
165
+ let copy = self
166
+ .copy(next, CopyDepth::Deep)
167
+ .expect("text can be copied");
168
+ self.insert_before(next, copy)?;
169
+ self.detach(next);
170
+ }
171
+ }
172
+ self.insert_after(pivot, node)?;
173
+ self.detach(pivot);
174
+ if !is_text(self, node) {
175
+ return Ok(node);
176
+ }
177
+ let mut merged = node;
178
+ if let Some(previous) = self.previous_sibling(node) {
179
+ if self.merge_text(previous, node) {
180
+ self.detach(node);
181
+ merged = previous;
182
+ }
183
+ }
184
+ if let Some(next) = self.next_sibling(merged) {
185
+ if self.merge_text(merged, next) {
186
+ self.detach(next);
187
+ }
188
+ }
189
+ Ok(merged)
190
+ }
191
+
192
+ /// Moves the text of `second` to the end of `first` if both are text nodes.
193
+ /// `second` is always a copy that nothing refers to. libxml2 frees it. Here
194
+ /// it stays as an empty slot.
195
+ fn merge_text(&mut self, first: NodeId, second: NodeId) -> bool {
196
+ if !matches!(self.node_kind(first), NodeKind::Text(_)) {
197
+ return false;
198
+ }
199
+ let NodeKind::Text(text) = &mut self.node_mut(second).kind else {
200
+ return false;
201
+ };
202
+ let text = mem::take(text);
203
+ if let NodeKind::Text(first) = &mut self.node_mut(first).kind {
204
+ first.extend_from_slice(&text);
205
+ }
206
+ true
207
+ }
208
+
209
+ fn relink_namespaces(&mut self, id: NodeId, namespace_inheritance: bool) {
210
+ let mut pending = vec![id];
211
+ while let Some(node) = pending.pop() {
212
+ let is_element = match self.node_kind(node) {
213
+ NodeKind::Element(_) => true,
214
+ NodeKind::Attribute(_) => false,
215
+ _ => continue,
216
+ };
217
+ self.resolve_prefix(node, is_element);
218
+ let Some(parent) = self.parent(node).filter(|_| is_element) else {
219
+ continue;
220
+ };
221
+ if namespace_inheritance
222
+ && self.namespace(node).is_none()
223
+ && self.namespace(parent).is_some()
224
+ {
225
+ if let NodeKind::Element(parent) = self.node_kind(parent) {
226
+ let (prefix, ns) = (parent.name.prefix.clone(), parent.name.ns.clone());
227
+ let local = self
228
+ .local_name(node)
229
+ .expect("an element has a name")
230
+ .clone();
231
+ self.rename(node, QualName::new(prefix, ns, local));
232
+ }
233
+ }
234
+ self.drop_definitions_in_scope(node, parent);
235
+ if self.namespace(node).is_some() {
236
+ pending.extend_from_slice(self.attributes(node));
237
+ pending.extend(self.children(node));
238
+ }
239
+ }
240
+ }
241
+
242
+ /// A name written `prefix:local`, with no namespace or the default one,
243
+ /// takes the namespace that the prefix now refers to. Attributes
244
+ /// with `xmlns` stay as they are. libxml2 also gives an element
245
+ /// without a prefix the default namespace in scope. Nothing here defines
246
+ /// one.
247
+ fn resolve_prefix(&mut self, id: NodeId, is_element: bool) {
248
+ if self
249
+ .namespace(id)
250
+ .is_some_and(|namespace| namespace.prefix.is_some())
251
+ {
252
+ return;
253
+ }
254
+ let Some(name) = self.local_name(id) else {
255
+ return;
256
+ };
257
+ let Some((prefix, local)) = split_qualified_name(name) else {
258
+ return;
259
+ };
260
+ if !is_element && prefix == "xmlns" {
261
+ return;
262
+ }
263
+ let Some(namespace) = self.search_namespace(id, prefix.as_bytes()) else {
264
+ return;
265
+ };
266
+ let name = QualName::new(
267
+ Some(Prefix::from(prefix)),
268
+ Namespace::from(namespace.href),
269
+ LocalName::from(local),
270
+ );
271
+ self.rename(id, name);
272
+ }
273
+
274
+ /// Definitions that the new parent already has in scope with the same
275
+ /// prefix are dropped.
276
+ fn drop_definitions_in_scope(&mut self, id: NodeId, parent: NodeId) {
277
+ if self.namespace_definitions(id).is_empty() {
278
+ return;
279
+ }
280
+ let in_scope: Vec<_> = self
281
+ .namespace_scopes(parent)
282
+ .into_iter()
283
+ .map(|scope| (scope.prefix.map(Prefix::from), Namespace::from(scope.href)))
284
+ .collect();
285
+ if let NodeKind::Element(element) = &mut self.node_mut(id).kind {
286
+ element.namespace_definitions.retain(|definition| {
287
+ !in_scope
288
+ .iter()
289
+ .any(|(prefix, href)| definition.prefix == *prefix && definition.href == *href)
290
+ });
291
+ }
292
+ }
293
+ }
294
+
295
+ /// Nokogiri's check of the hierarchy rules of the DOM, with its additions: text
296
+ /// can go directly into a document. Attributes take no children here,
297
+ /// because their values are bytes.
298
+ fn may_contain(parent: NodeType, child: NodeType) -> bool {
299
+ use NodeType::*;
300
+ let content = matches!(
301
+ child,
302
+ Element | ProcessingInstruction | Comment | Text | CDataSection
303
+ );
304
+ match parent {
305
+ Document | HtmlDocument | DocumentFragment | Element => content,
306
+ _ => false,
307
+ }
308
+ }