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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +5 -0
- data/Cargo.lock +520 -0
- data/Cargo.toml +11 -0
- data/LICENSE-NOKOGIRI.md +15 -0
- data/LICENSE.txt +21 -0
- data/README.md +144 -0
- data/crates/lobzique-core/Cargo.toml +14 -0
- data/crates/lobzique-core/src/css/mod.rs +127 -0
- data/crates/lobzique-core/src/css/parser.rs +805 -0
- data/crates/lobzique-core/src/css/tables.rs +282 -0
- data/crates/lobzique-core/src/css/tests.rs +476 -0
- data/crates/lobzique-core/src/css/tokenizer.rs +215 -0
- data/crates/lobzique-core/src/css/translate.rs +806 -0
- data/crates/lobzique-core/src/css/write.rs +370 -0
- data/crates/lobzique-core/src/dom/attribute.rs +144 -0
- data/crates/lobzique-core/src/dom/check.rs +160 -0
- data/crates/lobzique-core/src/dom/copy.rs +229 -0
- data/crates/lobzique-core/src/dom/mod.rs +298 -0
- data/crates/lobzique-core/src/dom/namespace.rs +134 -0
- data/crates/lobzique-core/src/dom/node.rs +129 -0
- data/crates/lobzique-core/src/dom/path.rs +116 -0
- data/crates/lobzique-core/src/dom/reparent.rs +308 -0
- data/crates/lobzique-core/src/dom/tests.rs +1057 -0
- data/crates/lobzique-core/src/dom/text.rs +159 -0
- data/crates/lobzique-core/src/dom/tree.rs +446 -0
- data/crates/lobzique-core/src/html5/mod.rs +28 -0
- data/crates/lobzique-core/src/html5/parse.rs +838 -0
- data/crates/lobzique-core/src/html5/serialize.rs +181 -0
- data/crates/lobzique-core/src/html5/tests.rs +548 -0
- data/crates/lobzique-core/src/lib.rs +12 -0
- data/crates/lobzique-core/src/work.rs +26 -0
- data/crates/lobzique-core/src/xml/mod.rs +8 -0
- data/crates/lobzique-core/src/xml/serialize.rs +681 -0
- data/crates/lobzique-core/src/xml/tests.rs +174 -0
- data/crates/lobzique-core/src/xpath/ast.rs +415 -0
- data/crates/lobzique-core/src/xpath/chars.rs +139 -0
- data/crates/lobzique-core/src/xpath/eval.rs +1305 -0
- data/crates/lobzique-core/src/xpath/mod.rs +118 -0
- data/crates/lobzique-core/src/xpath/parse.rs +729 -0
- data/crates/lobzique-core/src/xpath/tests.rs +921 -0
- data/ext/lobzique/Cargo.toml +22 -0
- data/ext/lobzique/build.rs +5 -0
- data/ext/lobzique/clippy.toml +15 -0
- data/ext/lobzique/extconf.rb +6 -0
- data/ext/lobzique/src/css/mod.rs +9 -0
- data/ext/lobzique/src/css/parser.rs +44 -0
- data/ext/lobzique/src/css/selector.rs +101 -0
- data/ext/lobzique/src/html4/document.rs +31 -0
- data/ext/lobzique/src/html4/mod.rs +7 -0
- data/ext/lobzique/src/html5/mod.rs +16 -0
- data/ext/lobzique/src/html5ever.rs +278 -0
- data/ext/lobzique/src/lib.rs +45 -0
- data/ext/lobzique/src/support.rs +156 -0
- data/ext/lobzique/src/xml/attr.rs +27 -0
- data/ext/lobzique/src/xml/cdata.rs +33 -0
- data/ext/lobzique/src/xml/comment.rs +34 -0
- data/ext/lobzique/src/xml/document.rs +199 -0
- data/ext/lobzique/src/xml/document_fragment.rs +27 -0
- data/ext/lobzique/src/xml/dtd.rs +37 -0
- data/ext/lobzique/src/xml/mod.rs +44 -0
- data/ext/lobzique/src/xml/namespace.rs +56 -0
- data/ext/lobzique/src/xml/node.rs +944 -0
- data/ext/lobzique/src/xml/node_set.rs +20 -0
- data/ext/lobzique/src/xml/syntax_error.rs +33 -0
- data/ext/lobzique/src/xml/text.rs +44 -0
- data/ext/lobzique/src/xml/xpath_context.rs +305 -0
- data/lib/lobzique/action_text.rb +29 -0
- data/lib/lobzique/class_resolver.rb +33 -0
- data/lib/lobzique/css/selector_cache.rb +36 -0
- data/lib/lobzique/css/syntax_error.rb +12 -0
- data/lib/lobzique/css/xpath_visitor.rb +60 -0
- data/lib/lobzique/css.rb +57 -0
- data/lib/lobzique/extension.rb +31 -0
- data/lib/lobzique/html.rb +14 -0
- data/lib/lobzique/html4/document.rb +235 -0
- data/lib/lobzique/html4/document_fragment.rb +75 -0
- data/lib/lobzique/html4/encoding_reader.rb +374 -0
- data/lib/lobzique/html4.rb +35 -0
- data/lib/lobzique/html5/document.rb +106 -0
- data/lib/lobzique/html5/document_fragment.rb +113 -0
- data/lib/lobzique/html5/node.rb +66 -0
- data/lib/lobzique/html5.rb +92 -0
- data/lib/lobzique/html5ever.rb +14 -0
- data/lib/lobzique/rails_dom_testing.rb +95 -0
- data/lib/lobzique/sanitizer/concerns.rb +110 -0
- data/lib/lobzique/sanitizer/document.rb +14 -0
- data/lib/lobzique/sanitizer/document_fragment.rb +12 -0
- data/lib/lobzique/sanitizer/escape_raw_text_in_select.rb +31 -0
- data/lib/lobzique/sanitizer/scrubbers.rb +46 -0
- data/lib/lobzique/sanitizer.rb +96 -0
- data/lib/lobzique/syntax_error.rb +8 -0
- data/lib/lobzique/version.rb +6 -0
- data/lib/lobzique/xml/attr.rb +23 -0
- data/lib/lobzique/xml/cdata.rb +13 -0
- data/lib/lobzique/xml/character_data.rb +11 -0
- data/lib/lobzique/xml/document.rb +149 -0
- data/lib/lobzique/xml/document_fragment.rb +109 -0
- data/lib/lobzique/xml/dtd.rb +28 -0
- data/lib/lobzique/xml/namespace.rb +19 -0
- data/lib/lobzique/xml/node/save_options.rb +52 -0
- data/lib/lobzique/xml/node.rb +629 -0
- data/lib/lobzique/xml/node_set.rb +329 -0
- data/lib/lobzique/xml/parse_options.rb +89 -0
- data/lib/lobzique/xml/pp/character_data.rb +22 -0
- data/lib/lobzique/xml/pp/node.rb +73 -0
- data/lib/lobzique/xml/pp.rb +6 -0
- data/lib/lobzique/xml/searchable.rb +123 -0
- data/lib/lobzique/xml/syntax_error.rb +77 -0
- data/lib/lobzique/xml/text.rb +14 -0
- data/lib/lobzique/xml/xpath/syntax_error.rb +20 -0
- data/lib/lobzique/xml/xpath.rb +16 -0
- data/lib/lobzique/xml/xpath_context.rb +27 -0
- data/lib/lobzique/xml.rb +22 -0
- data/lib/lobzique.rb +15 -0
- metadata +177 -0
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
use super::{Document, NodeId, NodeKind};
|
|
2
|
+
|
|
3
|
+
impl Document {
|
|
4
|
+
/// libxml2's `xmlNodeGetContent`, which Nokogiri's `Node#content` returns:
|
|
5
|
+
/// the text and CDATA in an element, fragment or document, the own text
|
|
6
|
+
/// of a character node, and nothing for a doctype.
|
|
7
|
+
pub fn content(&self, id: NodeId) -> Option<Vec<u8>> {
|
|
8
|
+
match self.node_kind(id) {
|
|
9
|
+
NodeKind::Text(text) | NodeKind::CData(text) | NodeKind::Comment(text) => {
|
|
10
|
+
Some(text.clone())
|
|
11
|
+
}
|
|
12
|
+
NodeKind::Attribute(attribute) => Some(attribute.value.clone()),
|
|
13
|
+
NodeKind::ProcessingInstruction(pi) => Some(pi.data.clone()),
|
|
14
|
+
NodeKind::Doctype(_) => None,
|
|
15
|
+
NodeKind::Document | NodeKind::DocumentFragment | NodeKind::Element(_) => {
|
|
16
|
+
let mut content = Vec::new();
|
|
17
|
+
for descendant in self.descendants(id) {
|
|
18
|
+
if let NodeKind::Text(text) | NodeKind::CData(text) = self.node_kind(descendant)
|
|
19
|
+
{
|
|
20
|
+
content.extend_from_slice(text);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
Some(content)
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/// libxml2's `xmlIsBlankNode`: a text or CDATA node of only spaces, tabs
|
|
29
|
+
/// and line breaks.
|
|
30
|
+
pub fn is_blank(&self, id: NodeId) -> bool {
|
|
31
|
+
match self.node_kind(id) {
|
|
32
|
+
NodeKind::Text(text) | NodeKind::CData(text) => text
|
|
33
|
+
.iter()
|
|
34
|
+
.all(|byte| matches!(byte, b' ' | b'\t' | b'\n' | b'\r')),
|
|
35
|
+
_ => false,
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/// Nokogiri's `native_content=`: `xmlNodeSetContent` after the children
|
|
40
|
+
/// are unlinked. Elements, fragments and attributes get the content
|
|
41
|
+
/// with its character references decoded. Character data and processing
|
|
42
|
+
/// instructions get it as is. Other nodes get nothing.
|
|
43
|
+
pub fn set_content(&mut self, id: NodeId, content: Vec<u8>) {
|
|
44
|
+
while let Some(child) = self.first_child(id) {
|
|
45
|
+
self.detach(child);
|
|
46
|
+
}
|
|
47
|
+
if matches!(
|
|
48
|
+
self.node_kind(id),
|
|
49
|
+
NodeKind::Element(_) | NodeKind::DocumentFragment
|
|
50
|
+
) {
|
|
51
|
+
let text = decode_references(&content);
|
|
52
|
+
if !text.is_empty() {
|
|
53
|
+
let text = self.create_text(text);
|
|
54
|
+
self.append_child(id, text)
|
|
55
|
+
.expect("an element takes a text child");
|
|
56
|
+
}
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
match &mut self.node_mut(id).kind {
|
|
60
|
+
NodeKind::Attribute(attribute) => attribute.value = decode_references(&content),
|
|
61
|
+
NodeKind::Text(text) | NodeKind::CData(text) | NodeKind::Comment(text) => {
|
|
62
|
+
*text = content
|
|
63
|
+
}
|
|
64
|
+
NodeKind::ProcessingInstruction(pi) => pi.data = content,
|
|
65
|
+
NodeKind::Element(_)
|
|
66
|
+
| NodeKind::DocumentFragment
|
|
67
|
+
| NodeKind::Document
|
|
68
|
+
| NodeKind::Doctype(_) => {}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
pub fn character_data_mut(&mut self, id: NodeId) -> Option<&mut Vec<u8>> {
|
|
73
|
+
match &mut self.node_mut(id).kind {
|
|
74
|
+
NodeKind::Text(text) | NodeKind::CData(text) | NodeKind::Comment(text) => Some(text),
|
|
75
|
+
_ => None,
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/// What libxml2's `xmlNodeSetContent` decodes: the predefined entities
|
|
81
|
+
/// and character references. This covers everything [`encode_special_chars`]
|
|
82
|
+
/// writes. libxml2 makes any other entity reference a node of its own. Here
|
|
83
|
+
/// it stays text.
|
|
84
|
+
fn decode_references(input: &[u8]) -> Vec<u8> {
|
|
85
|
+
let mut decoded = Vec::with_capacity(input.len());
|
|
86
|
+
let mut rest = input;
|
|
87
|
+
while let Some(start) = rest.iter().position(|&byte| byte == b'&') {
|
|
88
|
+
decoded.extend_from_slice(&rest[..start]);
|
|
89
|
+
rest = &rest[start..];
|
|
90
|
+
// A name never holds `&`, so stopping there keeps decoding linear.
|
|
91
|
+
let reference = rest
|
|
92
|
+
.iter()
|
|
93
|
+
.skip(1)
|
|
94
|
+
.position(|&byte| byte == b';' || byte == b'&')
|
|
95
|
+
.map(|offset| offset + 1)
|
|
96
|
+
.filter(|&end| rest[end] == b';')
|
|
97
|
+
.and_then(|end| Some((decode_reference(&rest[1..end])?, end)));
|
|
98
|
+
match reference {
|
|
99
|
+
Some((character, end)) => {
|
|
100
|
+
decoded.extend_from_slice(character.encode_utf8(&mut [0; 4]).as_bytes());
|
|
101
|
+
rest = &rest[end + 1..];
|
|
102
|
+
}
|
|
103
|
+
None => {
|
|
104
|
+
decoded.push(b'&');
|
|
105
|
+
rest = &rest[1..];
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
decoded.extend_from_slice(rest);
|
|
110
|
+
decoded
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
fn decode_reference(name: &[u8]) -> Option<char> {
|
|
114
|
+
let number = |digits: &[u8], radix| {
|
|
115
|
+
let digits = std::str::from_utf8(digits).ok()?;
|
|
116
|
+
let all_digits = !digits.is_empty() && digits.chars().all(|c| c.is_digit(radix));
|
|
117
|
+
all_digits
|
|
118
|
+
.then(|| u32::from_str_radix(digits, radix).ok())
|
|
119
|
+
.flatten()
|
|
120
|
+
.and_then(char::from_u32)
|
|
121
|
+
.filter(|&c| c != '\0')
|
|
122
|
+
};
|
|
123
|
+
match name {
|
|
124
|
+
b"lt" => Some('<'),
|
|
125
|
+
b"gt" => Some('>'),
|
|
126
|
+
b"amp" => Some('&'),
|
|
127
|
+
b"quot" => Some('"'),
|
|
128
|
+
b"apos" => Some('\''),
|
|
129
|
+
[b'#', b'x' | b'X', hex @ ..] => number(hex, 16),
|
|
130
|
+
[b'#', decimal @ ..] => number(decimal, 10),
|
|
131
|
+
_ => None,
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/// libxml2's `xmlEncodeSpecialChars`, behind Nokogiri's
|
|
136
|
+
/// `Node#encode_special_chars` and `Node#content=`.
|
|
137
|
+
pub fn encode_special_chars(input: &[u8]) -> Vec<u8> {
|
|
138
|
+
let mut encoded = Vec::with_capacity(input.len());
|
|
139
|
+
for &byte in input {
|
|
140
|
+
match byte {
|
|
141
|
+
b'<' => encoded.extend_from_slice(b"<"),
|
|
142
|
+
b'>' => encoded.extend_from_slice(b">"),
|
|
143
|
+
b'&' => encoded.extend_from_slice(b"&"),
|
|
144
|
+
b'"' => encoded.extend_from_slice(b"""),
|
|
145
|
+
b'\r' => encoded.extend_from_slice(b" "),
|
|
146
|
+
_ => encoded.push(byte),
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
encoded
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/// libxml2 holds text as C strings, so what it writes ends at the first zero
|
|
153
|
+
/// byte.
|
|
154
|
+
pub fn c_string(bytes: &[u8]) -> &[u8] {
|
|
155
|
+
match bytes.iter().position(|&byte| byte == 0) {
|
|
156
|
+
Some(end) => &bytes[..end],
|
|
157
|
+
None => bytes,
|
|
158
|
+
}
|
|
159
|
+
}
|
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
//! Linking and walking nodes. These operations keep the tree well formed and do
|
|
2
|
+
//! nothing else. The rules of Nokogiri for where a node can go, and the copying
|
|
3
|
+
//! and text merging that come with them, are in other modules.
|
|
4
|
+
|
|
5
|
+
use super::{Document, NodeId, NodeKind};
|
|
6
|
+
use std::cmp::Ordering;
|
|
7
|
+
use std::fmt;
|
|
8
|
+
|
|
9
|
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
10
|
+
pub enum HierarchyError {
|
|
11
|
+
/// Documents and attributes are never children.
|
|
12
|
+
NotAChild,
|
|
13
|
+
/// Only documents, fragments and elements have children.
|
|
14
|
+
NoChildren,
|
|
15
|
+
/// The new parent is the node itself or one of its descendants.
|
|
16
|
+
Cycle,
|
|
17
|
+
/// Inserting next to a node that has no parent.
|
|
18
|
+
NoParent,
|
|
19
|
+
/// Attributes go on elements only.
|
|
20
|
+
NotAnElement,
|
|
21
|
+
NotAnAttribute,
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
impl fmt::Display for HierarchyError {
|
|
25
|
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
26
|
+
f.write_str(match self {
|
|
27
|
+
HierarchyError::NotAChild => "node can't be a child",
|
|
28
|
+
HierarchyError::NoChildren => "node can't have children",
|
|
29
|
+
HierarchyError::Cycle => "node would become its own ancestor",
|
|
30
|
+
HierarchyError::NoParent => "node has no parent",
|
|
31
|
+
HierarchyError::NotAnElement => "attributes go on elements only",
|
|
32
|
+
HierarchyError::NotAnAttribute => "node isn't an attribute",
|
|
33
|
+
})
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
impl std::error::Error for HierarchyError {}
|
|
38
|
+
|
|
39
|
+
impl Document {
|
|
40
|
+
pub fn parent(&self, id: NodeId) -> Option<NodeId> {
|
|
41
|
+
self.node(id).parent
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
pub fn first_child(&self, id: NodeId) -> Option<NodeId> {
|
|
45
|
+
self.node(id).first_child
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
pub fn last_child(&self, id: NodeId) -> Option<NodeId> {
|
|
49
|
+
self.node(id).last_child
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
pub fn next_sibling(&self, id: NodeId) -> Option<NodeId> {
|
|
53
|
+
self.node(id).next_sibling
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
pub fn previous_sibling(&self, id: NodeId) -> Option<NodeId> {
|
|
57
|
+
self.node(id).previous_sibling
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
pub fn attributes(&self, id: NodeId) -> &[NodeId] {
|
|
61
|
+
match self.node_kind(id) {
|
|
62
|
+
NodeKind::Element(element) => &element.attributes,
|
|
63
|
+
_ => &[],
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
pub fn children(&self, id: NodeId) -> Children<'_> {
|
|
68
|
+
Children {
|
|
69
|
+
document: self,
|
|
70
|
+
next: self.first_child(id),
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
pub fn ancestors(&self, id: NodeId) -> Ancestors<'_> {
|
|
75
|
+
Ancestors {
|
|
76
|
+
document: self,
|
|
77
|
+
next: self.parent(id),
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/// The descendants of the node in document order, without the node.
|
|
82
|
+
/// It follows the links and does not recurse, so depth uses no stack.
|
|
83
|
+
pub fn descendants(&self, id: NodeId) -> Descendants<'_> {
|
|
84
|
+
Descendants {
|
|
85
|
+
document: self,
|
|
86
|
+
root: id,
|
|
87
|
+
next: self.first_child(id),
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/// libxml2's `node->next`: the next sibling. For an attribute, the next
|
|
92
|
+
/// attribute of its element.
|
|
93
|
+
pub fn next_in_parent(&self, id: NodeId) -> Option<NodeId> {
|
|
94
|
+
self.next_sibling(id)
|
|
95
|
+
.or_else(|| self.attribute_sibling(id, |index| index.checked_add(1)))
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/// libxml2's `node->prev`, as [`Document::next_in_parent`].
|
|
99
|
+
pub fn previous_in_parent(&self, id: NodeId) -> Option<NodeId> {
|
|
100
|
+
self.previous_sibling(id)
|
|
101
|
+
.or_else(|| self.attribute_sibling(id, |index| index.checked_sub(1)))
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/// libxml2's `xmlNextElementSibling`: none for attributes, documents
|
|
105
|
+
/// and fragments.
|
|
106
|
+
pub fn next_element_sibling(&self, id: NodeId) -> Option<NodeId> {
|
|
107
|
+
if !self.has_element_siblings(id) {
|
|
108
|
+
return None;
|
|
109
|
+
}
|
|
110
|
+
std::iter::successors(self.next_sibling(id), |&sibling| self.next_sibling(sibling))
|
|
111
|
+
.find(|&sibling| self.is_element(sibling))
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/// libxml2's `xmlPreviousElementSibling`, as
|
|
115
|
+
/// [`Document::next_element_sibling`].
|
|
116
|
+
pub fn previous_element_sibling(&self, id: NodeId) -> Option<NodeId> {
|
|
117
|
+
if !self.has_element_siblings(id) {
|
|
118
|
+
return None;
|
|
119
|
+
}
|
|
120
|
+
std::iter::successors(self.previous_sibling(id), |&sibling| {
|
|
121
|
+
self.previous_sibling(sibling)
|
|
122
|
+
})
|
|
123
|
+
.find(|&sibling| self.is_element(sibling))
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
pub fn element_children(&self, id: NodeId) -> impl Iterator<Item = NodeId> + '_ {
|
|
127
|
+
self.children(id).filter(|&child| self.is_element(child))
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
pub fn last_element_child(&self, id: NodeId) -> Option<NodeId> {
|
|
131
|
+
std::iter::successors(self.last_child(id), |&child| self.previous_sibling(child))
|
|
132
|
+
.find(|&child| self.is_element(child))
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/// Where `a` is relative to `b` in document order, as libxml2's
|
|
136
|
+
/// `xmlXPathCmpNodes` decides it. An attribute comes after its element
|
|
137
|
+
/// and before the children of the element. Attributes keep the order
|
|
138
|
+
/// of their element. `None` for nodes in different trees.
|
|
139
|
+
///
|
|
140
|
+
/// A comparison walks the tree until it has cost as much as numbering
|
|
141
|
+
/// every node once. Then it uses those numbers until the tree changes.
|
|
142
|
+
/// Sorting n nodes thus stays O(n log n) in any tree.
|
|
143
|
+
pub fn document_order(&self, a: NodeId, b: NodeId) -> Option<Ordering> {
|
|
144
|
+
if a == b {
|
|
145
|
+
return Some(Ordering::Equal);
|
|
146
|
+
}
|
|
147
|
+
if let Some(order) = self.order.get() {
|
|
148
|
+
if let (Some(a), Some(b)) = (order.get(a.index()), order.get(b.index())) {
|
|
149
|
+
return (a.0 == b.0).then(|| a.1.cmp(&b.1));
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
let (ordering, cost) = self.walk_order(a, b);
|
|
153
|
+
let walked = self.order_walked.get().saturating_add(cost);
|
|
154
|
+
self.order_walked.set(walked);
|
|
155
|
+
if walked >= self.nodes.len() {
|
|
156
|
+
self.order.get_or_init(|| self.number_nodes());
|
|
157
|
+
}
|
|
158
|
+
ordering
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/// Sorts nodes into document order and removes duplicates, as libxml2 keeps
|
|
162
|
+
/// XPath node sets. Nodes of different trees go by the ids of their roots,
|
|
163
|
+
/// so the order stays total.
|
|
164
|
+
pub fn sort_in_document_order(&self, nodes: &mut Vec<NodeId>) {
|
|
165
|
+
let root = |id: NodeId| self.ancestors(id).last().unwrap_or(id);
|
|
166
|
+
let mut keyed: Vec<(NodeId, NodeId)> = nodes.iter().map(|&id| (root(id), id)).collect();
|
|
167
|
+
keyed.sort_by(|&(a_root, a), &(b_root, b)| {
|
|
168
|
+
a_root
|
|
169
|
+
.cmp(&b_root)
|
|
170
|
+
.then_with(|| self.document_order(a, b).unwrap_or(Ordering::Equal))
|
|
171
|
+
});
|
|
172
|
+
keyed.dedup_by_key(|&mut (_, id)| id);
|
|
173
|
+
*nodes = keyed.into_iter().map(|(_, id)| id).collect();
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/// [`Document::document_order`] by following links. Also gives the number
|
|
177
|
+
/// of links followed.
|
|
178
|
+
pub(super) fn walk_order(&self, a: NodeId, b: NodeId) -> (Option<Ordering>, usize) {
|
|
179
|
+
// Each node as its tree node. For an attribute, also its index there.
|
|
180
|
+
let key = |id: NodeId| match (self.node_kind(id), self.parent(id)) {
|
|
181
|
+
(NodeKind::Attribute(_), Some(element)) => {
|
|
182
|
+
let index = self.attributes(element).iter().position(|&a| a == id);
|
|
183
|
+
(element, index)
|
|
184
|
+
}
|
|
185
|
+
_ => (id, None),
|
|
186
|
+
};
|
|
187
|
+
let ((mut a, a_attribute), (mut b, b_attribute)) = (key(a), key(b));
|
|
188
|
+
if a == b {
|
|
189
|
+
return (Some(a_attribute.cmp(&b_attribute)), 0);
|
|
190
|
+
}
|
|
191
|
+
let (a_depth, b_depth) = (self.ancestors(a).count(), self.ancestors(b).count());
|
|
192
|
+
let mut cost = a_depth + b_depth;
|
|
193
|
+
let lift = |mut id: NodeId, steps: usize| {
|
|
194
|
+
for _ in 0..steps {
|
|
195
|
+
id = self.parent(id).expect("counted as an ancestor");
|
|
196
|
+
}
|
|
197
|
+
id
|
|
198
|
+
};
|
|
199
|
+
a = lift(a, a_depth.saturating_sub(b_depth));
|
|
200
|
+
b = lift(b, b_depth.saturating_sub(a_depth));
|
|
201
|
+
if a == b {
|
|
202
|
+
// One is an ancestor of the other, and comes first.
|
|
203
|
+
return (Some(a_depth.cmp(&b_depth)), cost);
|
|
204
|
+
}
|
|
205
|
+
loop {
|
|
206
|
+
match (self.parent(a), self.parent(b)) {
|
|
207
|
+
(Some(a_parent), Some(b_parent)) if a_parent == b_parent => break,
|
|
208
|
+
(Some(a_parent), Some(b_parent)) => (a, b) = (a_parent, b_parent),
|
|
209
|
+
_ => return (None, cost),
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
let mut sibling = self.next_sibling(a);
|
|
213
|
+
while let Some(next) = sibling {
|
|
214
|
+
cost += 1;
|
|
215
|
+
if next == b {
|
|
216
|
+
return (Some(Ordering::Less), cost);
|
|
217
|
+
}
|
|
218
|
+
sibling = self.next_sibling(next);
|
|
219
|
+
}
|
|
220
|
+
(Some(Ordering::Greater), cost)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
pub(super) fn number_nodes(&self) -> Vec<(NodeId, u32)> {
|
|
224
|
+
let mut order = vec![(NodeId::DOCUMENT, 0); self.nodes.len()];
|
|
225
|
+
for root in self.node_ids().filter(|&id| self.parent(id).is_none()) {
|
|
226
|
+
// At most the node count of the arena, which fits in a u32.
|
|
227
|
+
let mut position = 0;
|
|
228
|
+
for node in std::iter::once(root).chain(self.descendants(root)) {
|
|
229
|
+
for &id in std::iter::once(&node).chain(self.attributes(node)) {
|
|
230
|
+
order[id.index()] = (root, position);
|
|
231
|
+
position += 1;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
order
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
pub fn append_child(&mut self, parent: NodeId, child: NodeId) -> Result<(), HierarchyError> {
|
|
239
|
+
self.check_insertion(parent, child)?;
|
|
240
|
+
self.detach(child);
|
|
241
|
+
let previous = self.node(parent).last_child;
|
|
242
|
+
self.link(child, parent, previous, None);
|
|
243
|
+
Ok(())
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
pub fn insert_before(&mut self, reference: NodeId, node: NodeId) -> Result<(), HierarchyError> {
|
|
247
|
+
let parent = self.parent_for_insertion(reference, node)?;
|
|
248
|
+
self.detach(node);
|
|
249
|
+
let previous = self.node(reference).previous_sibling;
|
|
250
|
+
self.link(node, parent, previous, Some(reference));
|
|
251
|
+
Ok(())
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
pub fn insert_after(&mut self, reference: NodeId, node: NodeId) -> Result<(), HierarchyError> {
|
|
255
|
+
let parent = self.parent_for_insertion(reference, node)?;
|
|
256
|
+
self.detach(node);
|
|
257
|
+
let next = self.node(reference).next_sibling;
|
|
258
|
+
self.link(node, parent, Some(reference), next);
|
|
259
|
+
Ok(())
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
pub fn append_attribute(
|
|
263
|
+
&mut self,
|
|
264
|
+
element: NodeId,
|
|
265
|
+
attribute: NodeId,
|
|
266
|
+
) -> Result<(), HierarchyError> {
|
|
267
|
+
if !matches!(self.node_kind(attribute), NodeKind::Attribute(_)) {
|
|
268
|
+
return Err(HierarchyError::NotAnAttribute);
|
|
269
|
+
}
|
|
270
|
+
if !matches!(self.node_kind(element), NodeKind::Element(_)) {
|
|
271
|
+
return Err(HierarchyError::NotAnElement);
|
|
272
|
+
}
|
|
273
|
+
self.detach(attribute);
|
|
274
|
+
self.tree_changed();
|
|
275
|
+
self.node_mut(attribute).parent = Some(element);
|
|
276
|
+
if let NodeKind::Element(e) = &mut self.node_mut(element).kind {
|
|
277
|
+
e.attributes.push(attribute);
|
|
278
|
+
}
|
|
279
|
+
Ok(())
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/// Unlinks the node from its parent and siblings, or an attribute from
|
|
283
|
+
/// its element. The node and its subtree stay in the arena.
|
|
284
|
+
pub fn detach(&mut self, id: NodeId) {
|
|
285
|
+
let Some(parent) = self.node(id).parent else {
|
|
286
|
+
return;
|
|
287
|
+
};
|
|
288
|
+
self.tree_changed();
|
|
289
|
+
if matches!(self.node_kind(id), NodeKind::Attribute(_)) {
|
|
290
|
+
if let NodeKind::Element(element) = &mut self.node_mut(parent).kind {
|
|
291
|
+
element.attributes.retain(|&a| a != id);
|
|
292
|
+
}
|
|
293
|
+
self.node_mut(id).parent = None;
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
let node = self.node_mut(id);
|
|
298
|
+
let (previous, next) = (node.previous_sibling.take(), node.next_sibling.take());
|
|
299
|
+
node.parent = None;
|
|
300
|
+
match previous {
|
|
301
|
+
Some(previous) => self.node_mut(previous).next_sibling = next,
|
|
302
|
+
None => self.node_mut(parent).first_child = next,
|
|
303
|
+
}
|
|
304
|
+
match next {
|
|
305
|
+
Some(next) => self.node_mut(next).previous_sibling = previous,
|
|
306
|
+
None => self.node_mut(parent).last_child = previous,
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
fn tree_changed(&mut self) {
|
|
311
|
+
self.order.take();
|
|
312
|
+
*self.order_walked.get_mut() = 0;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
fn attribute_sibling(
|
|
316
|
+
&self,
|
|
317
|
+
id: NodeId,
|
|
318
|
+
step: impl Fn(usize) -> Option<usize>,
|
|
319
|
+
) -> Option<NodeId> {
|
|
320
|
+
if !matches!(self.node_kind(id), NodeKind::Attribute(_)) {
|
|
321
|
+
return None;
|
|
322
|
+
}
|
|
323
|
+
let attributes = self.attributes(self.parent(id)?);
|
|
324
|
+
let index = attributes.iter().position(|&attribute| attribute == id)?;
|
|
325
|
+
attributes.get(step(index)?).copied()
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
fn has_element_siblings(&self, id: NodeId) -> bool {
|
|
329
|
+
!matches!(
|
|
330
|
+
self.node_kind(id),
|
|
331
|
+
NodeKind::Attribute(_) | NodeKind::Document | NodeKind::DocumentFragment
|
|
332
|
+
)
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
fn is_element(&self, id: NodeId) -> bool {
|
|
336
|
+
matches!(self.node_kind(id), NodeKind::Element(_))
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
fn check_insertion(&self, parent: NodeId, child: NodeId) -> Result<(), HierarchyError> {
|
|
340
|
+
if matches!(
|
|
341
|
+
self.node_kind(child),
|
|
342
|
+
NodeKind::Document | NodeKind::Attribute(_)
|
|
343
|
+
) {
|
|
344
|
+
return Err(HierarchyError::NotAChild);
|
|
345
|
+
}
|
|
346
|
+
if !self.node_kind(parent).can_have_children() {
|
|
347
|
+
return Err(HierarchyError::NoChildren);
|
|
348
|
+
}
|
|
349
|
+
// A childless node cannot be an ancestor, so appending leaves stays
|
|
350
|
+
// O(1).
|
|
351
|
+
let may_be_ancestor = self.first_child(child).is_some();
|
|
352
|
+
if parent == child || may_be_ancestor && self.ancestors(parent).any(|a| a == child) {
|
|
353
|
+
return Err(HierarchyError::Cycle);
|
|
354
|
+
}
|
|
355
|
+
Ok(())
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
fn parent_for_insertion(
|
|
359
|
+
&self,
|
|
360
|
+
reference: NodeId,
|
|
361
|
+
node: NodeId,
|
|
362
|
+
) -> Result<NodeId, HierarchyError> {
|
|
363
|
+
if matches!(self.node_kind(reference), NodeKind::Attribute(_)) {
|
|
364
|
+
return Err(HierarchyError::NotAChild);
|
|
365
|
+
}
|
|
366
|
+
let parent = self.parent(reference).ok_or(HierarchyError::NoParent)?;
|
|
367
|
+
if reference == node {
|
|
368
|
+
return Err(HierarchyError::Cycle);
|
|
369
|
+
}
|
|
370
|
+
self.check_insertion(parent, node)?;
|
|
371
|
+
Ok(parent)
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
fn link(&mut self, id: NodeId, parent: NodeId, previous: Option<NodeId>, next: Option<NodeId>) {
|
|
375
|
+
self.tree_changed();
|
|
376
|
+
let node = self.node_mut(id);
|
|
377
|
+
node.parent = Some(parent);
|
|
378
|
+
node.previous_sibling = previous;
|
|
379
|
+
node.next_sibling = next;
|
|
380
|
+
match previous {
|
|
381
|
+
Some(previous) => self.node_mut(previous).next_sibling = Some(id),
|
|
382
|
+
None => self.node_mut(parent).first_child = Some(id),
|
|
383
|
+
}
|
|
384
|
+
match next {
|
|
385
|
+
Some(next) => self.node_mut(next).previous_sibling = Some(id),
|
|
386
|
+
None => self.node_mut(parent).last_child = Some(id),
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
pub struct Children<'a> {
|
|
392
|
+
document: &'a Document,
|
|
393
|
+
next: Option<NodeId>,
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
impl Iterator for Children<'_> {
|
|
397
|
+
type Item = NodeId;
|
|
398
|
+
|
|
399
|
+
fn next(&mut self) -> Option<NodeId> {
|
|
400
|
+
let id = self.next?;
|
|
401
|
+
self.next = self.document.next_sibling(id);
|
|
402
|
+
Some(id)
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
pub struct Ancestors<'a> {
|
|
407
|
+
document: &'a Document,
|
|
408
|
+
next: Option<NodeId>,
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
impl Iterator for Ancestors<'_> {
|
|
412
|
+
type Item = NodeId;
|
|
413
|
+
|
|
414
|
+
fn next(&mut self) -> Option<NodeId> {
|
|
415
|
+
let id = self.next?;
|
|
416
|
+
self.next = self.document.parent(id);
|
|
417
|
+
Some(id)
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
pub struct Descendants<'a> {
|
|
422
|
+
document: &'a Document,
|
|
423
|
+
root: NodeId,
|
|
424
|
+
next: Option<NodeId>,
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
impl Iterator for Descendants<'_> {
|
|
428
|
+
type Item = NodeId;
|
|
429
|
+
|
|
430
|
+
fn next(&mut self) -> Option<NodeId> {
|
|
431
|
+
let id = self.next?;
|
|
432
|
+
self.next = self.document.first_child(id).or_else(|| {
|
|
433
|
+
let mut node = id;
|
|
434
|
+
loop {
|
|
435
|
+
if node == self.root {
|
|
436
|
+
return None;
|
|
437
|
+
}
|
|
438
|
+
if let Some(next) = self.document.next_sibling(node) {
|
|
439
|
+
return Some(next);
|
|
440
|
+
}
|
|
441
|
+
node = self.document.parent(node)?;
|
|
442
|
+
}
|
|
443
|
+
});
|
|
444
|
+
Some(id)
|
|
445
|
+
}
|
|
446
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
//! HTML parsing and serialization as Nokogiri::HTML5 does them, over the
|
|
2
|
+
//! arena DOM.
|
|
3
|
+
|
|
4
|
+
mod parse;
|
|
5
|
+
mod serialize;
|
|
6
|
+
#[cfg(test)]
|
|
7
|
+
mod tests;
|
|
8
|
+
|
|
9
|
+
pub use parse::{
|
|
10
|
+
doctype_quirks_mode, parse_document, parse_fragment, parse_in_context, quirks_mode_for_doctype,
|
|
11
|
+
Context, ContextError, ContextNamespace, DocumentParser, FragmentParser, LimitError, Options,
|
|
12
|
+
ParseError, Parsed, ParsedFragment, QuirksMode,
|
|
13
|
+
};
|
|
14
|
+
pub use serialize::{prepend_newline, serialize};
|
|
15
|
+
|
|
16
|
+
use crate::dom::QualName;
|
|
17
|
+
use html5ever::ns;
|
|
18
|
+
|
|
19
|
+
const VOID_ELEMENTS: &[&str] = &[
|
|
20
|
+
"area", "base", "basefont", "bgsound", "br", "col", "embed", "frame", "hr", "img", "input",
|
|
21
|
+
"keygen", "link", "meta", "param", "source", "track", "wbr",
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
/// Whether an element counts as HTML for Nokogiri. Nokogiri gives HTML elements
|
|
25
|
+
/// no namespace: they are in the HTML namespace or in none.
|
|
26
|
+
fn is_html(name: &QualName) -> bool {
|
|
27
|
+
name.ns == ns!(html) || name.ns == ns!()
|
|
28
|
+
}
|