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,838 @@
|
|
|
1
|
+
//! html5ever's tree builder writes into the arena. Limits and output follow
|
|
2
|
+
//! Nokogiri's gumbo binding (`ext/nokogiri/gumbo.c`).
|
|
3
|
+
|
|
4
|
+
use super::{is_html, VOID_ELEMENTS};
|
|
5
|
+
use crate::dom::{CopyDepth, Doctype, Document, DocumentKind, NodeId, NodeKind, QualName};
|
|
6
|
+
use html5ever::tendril::StrTendril;
|
|
7
|
+
use html5ever::tokenizer::{
|
|
8
|
+
self, BufferQueue, Token, TokenSink, TokenSinkResult, Tokenizer, TokenizerOpts,
|
|
9
|
+
};
|
|
10
|
+
use html5ever::tree_builder::{
|
|
11
|
+
create_element, ElemName, ElementFlags, NodeOrText, TreeBuilder, TreeBuilderOpts, TreeSink,
|
|
12
|
+
};
|
|
13
|
+
use html5ever::{local_name, ns, Attribute, LocalName, Namespace, Prefix, TokenizerResult};
|
|
14
|
+
use std::borrow::Cow;
|
|
15
|
+
use std::cell::{Cell, RefCell};
|
|
16
|
+
use std::collections::HashSet;
|
|
17
|
+
use std::fmt;
|
|
18
|
+
|
|
19
|
+
/// Limits as Nokogiri passes them to gumbo. `None` means no limit.
|
|
20
|
+
#[derive(Clone, Debug, Default)]
|
|
21
|
+
pub struct Options {
|
|
22
|
+
pub max_attributes: Option<usize>,
|
|
23
|
+
pub max_errors: Option<usize>,
|
|
24
|
+
pub max_tree_depth: Option<usize>,
|
|
25
|
+
pub parse_noscript_content_as_text: bool,
|
|
26
|
+
/// Keeps a U+FEFF at the start of the input. Gumbo drops it. libxml2 keeps
|
|
27
|
+
/// it, because its decoder removes the byte order mark itself.
|
|
28
|
+
/// An in-context parse removes none.
|
|
29
|
+
pub keep_bom: bool,
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
33
|
+
#[repr(u8)]
|
|
34
|
+
pub enum QuirksMode {
|
|
35
|
+
NoQuirks = 0,
|
|
36
|
+
Quirks = 1,
|
|
37
|
+
LimitedQuirks = 2,
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
impl From<html5ever::tree_builder::QuirksMode> for QuirksMode {
|
|
41
|
+
fn from(mode: html5ever::tree_builder::QuirksMode) -> QuirksMode {
|
|
42
|
+
use html5ever::tree_builder::QuirksMode as Html5ever;
|
|
43
|
+
match mode {
|
|
44
|
+
Html5ever::NoQuirks => QuirksMode::NoQuirks,
|
|
45
|
+
Html5ever::Quirks => QuirksMode::Quirks,
|
|
46
|
+
Html5ever::LimitedQuirks => QuirksMode::LimitedQuirks,
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
impl From<QuirksMode> for html5ever::tree_builder::QuirksMode {
|
|
52
|
+
fn from(mode: QuirksMode) -> html5ever::tree_builder::QuirksMode {
|
|
53
|
+
use html5ever::tree_builder::QuirksMode as Html5ever;
|
|
54
|
+
match mode {
|
|
55
|
+
QuirksMode::NoQuirks => Html5ever::NoQuirks,
|
|
56
|
+
QuirksMode::Quirks => Html5ever::Quirks,
|
|
57
|
+
QuirksMode::LimitedQuirks => Html5ever::LimitedQuirks,
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/// A limit was exceeded. Gumbo then returns no tree. It displays as the status
|
|
63
|
+
/// string of gumbo, which Nokogiri raises as an `ArgumentError`.
|
|
64
|
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
65
|
+
pub enum LimitError {
|
|
66
|
+
TooManyAttributes,
|
|
67
|
+
TreeTooDeep,
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
impl fmt::Display for LimitError {
|
|
71
|
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
72
|
+
f.write_str(match self {
|
|
73
|
+
LimitError::TooManyAttributes => "Attributes per element limit exceeded",
|
|
74
|
+
LimitError::TreeTooDeep => "Document tree depth limit exceeded",
|
|
75
|
+
})
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
impl std::error::Error for LimitError {}
|
|
80
|
+
|
|
81
|
+
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
82
|
+
pub struct ParseError {
|
|
83
|
+
pub line: u64,
|
|
84
|
+
pub message: String,
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
#[derive(Clone, Debug)]
|
|
88
|
+
pub struct Parsed {
|
|
89
|
+
pub quirks_mode: QuirksMode,
|
|
90
|
+
pub errors: Vec<ParseError>,
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/// Input that is not UTF-8 is decoded lossily, as gumbo does.
|
|
94
|
+
pub fn parse_document(input: &[u8], options: &Options) -> Result<(Document, Parsed), LimitError> {
|
|
95
|
+
DocumentParser::new(input.to_vec(), options).finish()
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/// A document parse that runs one chunk of input at a time, so that the caller
|
|
99
|
+
/// can do other work between chunks.
|
|
100
|
+
pub struct DocumentParser(Run);
|
|
101
|
+
|
|
102
|
+
impl DocumentParser {
|
|
103
|
+
pub fn new(input: Vec<u8>, options: &Options) -> DocumentParser {
|
|
104
|
+
let sink = Sink::new(options, options.max_tree_depth);
|
|
105
|
+
let builder = TreeBuilder::new(sink, tree_builder_options(options, QuirksMode::NoQuirks));
|
|
106
|
+
DocumentParser(Run::new(builder, input, options, None))
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/// Parses the next chunk. Returns false when no input remains or a limit
|
|
110
|
+
/// was exceeded.
|
|
111
|
+
pub fn step(&mut self) -> bool {
|
|
112
|
+
self.0.step()
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
pub fn finish(self) -> Result<(Document, Parsed), LimitError> {
|
|
116
|
+
let (mut document, parsed) = self.0.finish()?;
|
|
117
|
+
let roots: Vec<_> = document.element_children(NodeId::DOCUMENT).collect();
|
|
118
|
+
for root in roots {
|
|
119
|
+
define_namespaces(&mut document, root);
|
|
120
|
+
}
|
|
121
|
+
Ok((document, parsed))
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/// The context of a fragment parse, as Nokogiri's `Gumbo.fragment` finds
|
|
126
|
+
/// it from its `context` argument.
|
|
127
|
+
#[derive(Clone, Debug)]
|
|
128
|
+
pub struct Context {
|
|
129
|
+
name: QualName,
|
|
130
|
+
encoding: Option<Vec<u8>>,
|
|
131
|
+
has_form_ancestor: bool,
|
|
132
|
+
quirks_mode: QuirksMode,
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
136
|
+
pub enum ContextNamespace {
|
|
137
|
+
Html,
|
|
138
|
+
Svg,
|
|
139
|
+
MathMl,
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
impl Context {
|
|
143
|
+
/// Gumbo looks up context names without case. They are matched here
|
|
144
|
+
/// in the case that html5ever expects.
|
|
145
|
+
pub fn new(namespace: ContextNamespace, name: &str) -> Context {
|
|
146
|
+
let lower = name.to_ascii_lowercase();
|
|
147
|
+
let (namespace, local) = match namespace {
|
|
148
|
+
ContextNamespace::Html => (ns!(html), LocalName::from(lower)),
|
|
149
|
+
ContextNamespace::Svg if lower == "foreignobject" => {
|
|
150
|
+
(ns!(svg), local_name!("foreignObject"))
|
|
151
|
+
}
|
|
152
|
+
ContextNamespace::Svg => (ns!(svg), LocalName::from(lower)),
|
|
153
|
+
ContextNamespace::MathMl => (ns!(mathml), LocalName::from(lower)),
|
|
154
|
+
};
|
|
155
|
+
Context {
|
|
156
|
+
name: QualName::new(None, namespace, local),
|
|
157
|
+
encoding: None,
|
|
158
|
+
has_form_ancestor: false,
|
|
159
|
+
quirks_mode: QuirksMode::NoQuirks,
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
pub fn with_encoding(mut self, encoding: Option<Vec<u8>>) -> Context {
|
|
164
|
+
self.encoding = encoding;
|
|
165
|
+
self
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
pub fn with_form_ancestor(mut self, has_form_ancestor: bool) -> Context {
|
|
169
|
+
self.has_form_ancestor = has_form_ancestor;
|
|
170
|
+
self
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
pub fn with_quirks_mode(mut self, quirks_mode: QuirksMode) -> Context {
|
|
174
|
+
self.quirks_mode = quirks_mode;
|
|
175
|
+
self
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/// The context that `Gumbo.fragment` uses for a node of any kind: its name
|
|
179
|
+
/// and namespace, the `encoding` of an `annotation-xml`,
|
|
180
|
+
/// and whether the node or an element above it is a `form`. The caller sets
|
|
181
|
+
/// the quirks mode, because `Gumbo.fragment` takes it from the document
|
|
182
|
+
/// of the fragment.
|
|
183
|
+
pub fn of_node(document: &Document, node: NodeId) -> Result<Context, ContextError> {
|
|
184
|
+
let name = document.node_name(node).ok_or(ContextError::NoName)?;
|
|
185
|
+
let namespace = context_namespace(document, node).ok_or_else(|| {
|
|
186
|
+
let href = document.namespace(node).map(|namespace| namespace.href);
|
|
187
|
+
ContextError::UnknownNamespace(href.unwrap_or_default().to_owned())
|
|
188
|
+
})?;
|
|
189
|
+
let annotation_xml =
|
|
190
|
+
namespace == ContextNamespace::MathMl && name.eq_ignore_ascii_case(b"annotation-xml");
|
|
191
|
+
let encoding = annotation_xml
|
|
192
|
+
.then(|| document.attribute_value(node, b"encoding"))
|
|
193
|
+
.flatten();
|
|
194
|
+
Ok(Context::new(namespace, &String::from_utf8_lossy(name))
|
|
195
|
+
.with_encoding(encoding.map(<[u8]>::to_vec))
|
|
196
|
+
.with_form_ancestor(has_form_ancestor(document, node)))
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/// The context that `Node#in_context` parses in: the nearest element
|
|
200
|
+
/// at or above `node`. It is `body` when there is none, or when the element
|
|
201
|
+
/// is in a namespace that the parser has no rules for. If the document was
|
|
202
|
+
/// `parsed`, the quirks mode is the one of the doctype,
|
|
203
|
+
/// as for `Gumbo.fragment` with a node.
|
|
204
|
+
pub fn for_node(document: &Document, node: NodeId, parsed: bool) -> Context {
|
|
205
|
+
let element = std::iter::once(node)
|
|
206
|
+
.chain(document.ancestors(node))
|
|
207
|
+
.find(|&id| matches!(document.node_kind(id), NodeKind::Element(_)));
|
|
208
|
+
let body = Context::new(ContextNamespace::Html, "body");
|
|
209
|
+
let context = match element {
|
|
210
|
+
Some(element) => Context::of_node(document, element)
|
|
211
|
+
.unwrap_or_else(|_| body.with_form_ancestor(has_form_ancestor(document, element))),
|
|
212
|
+
None => body,
|
|
213
|
+
};
|
|
214
|
+
let quirks_mode = if parsed {
|
|
215
|
+
doctype_quirks_mode(document)
|
|
216
|
+
} else {
|
|
217
|
+
QuirksMode::NoQuirks
|
|
218
|
+
};
|
|
219
|
+
context.with_quirks_mode(quirks_mode)
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/// Why `Context::of_node` refuses a node. `Gumbo.fragment` refuses the same.
|
|
224
|
+
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
225
|
+
pub enum ContextError {
|
|
226
|
+
/// A document, fragment or CDATA section. Its `name` is nil.
|
|
227
|
+
NoName,
|
|
228
|
+
/// A namespace that the parser has no rules for, given by its href.
|
|
229
|
+
UnknownNamespace(String),
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/// The quirks mode of a fragment parsed in the context of a node of the parsed
|
|
233
|
+
/// `document`: the mode of its doctype, or quirks without a doctype.
|
|
234
|
+
pub fn doctype_quirks_mode(document: &Document) -> QuirksMode {
|
|
235
|
+
let doctype = document
|
|
236
|
+
.doctype()
|
|
237
|
+
.and_then(|id| match document.node_kind(id) {
|
|
238
|
+
NodeKind::Doctype(doctype) => Some(doctype),
|
|
239
|
+
_ => None,
|
|
240
|
+
});
|
|
241
|
+
match doctype {
|
|
242
|
+
None => QuirksMode::Quirks,
|
|
243
|
+
Some(doctype) => quirks_mode_for_doctype(
|
|
244
|
+
Some(&doctype.name),
|
|
245
|
+
doctype.public_id.as_deref(),
|
|
246
|
+
doctype.system_id.as_deref(),
|
|
247
|
+
),
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/// Port of `lookup_namespace` of gumbo.c. `None` for a namespace
|
|
252
|
+
/// that the parser has no rules for.
|
|
253
|
+
fn context_namespace(document: &Document, element: NodeId) -> Option<ContextNamespace> {
|
|
254
|
+
let Some(namespace) = document.namespace(element) else {
|
|
255
|
+
return Some(ContextNamespace::Html);
|
|
256
|
+
};
|
|
257
|
+
match namespace.href {
|
|
258
|
+
"http://www.w3.org/1999/xhtml" => Some(ContextNamespace::Html),
|
|
259
|
+
"http://www.w3.org/1998/Math/MathML" => Some(ContextNamespace::MathMl),
|
|
260
|
+
"http://www.w3.org/2000/svg" => Some(ContextNamespace::Svg),
|
|
261
|
+
_ => None,
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
fn has_form_ancestor(document: &Document, node: NodeId) -> bool {
|
|
266
|
+
let is_form = |id| {
|
|
267
|
+
matches!(document.node_kind(id), NodeKind::Element(element)
|
|
268
|
+
if element.name.local.eq_ignore_ascii_case(&local_name!("form")))
|
|
269
|
+
};
|
|
270
|
+
std::iter::once(node)
|
|
271
|
+
.chain(document.ancestors(node))
|
|
272
|
+
.any(|id| is_form(id) && context_namespace(document, id) == Some(ContextNamespace::Html))
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
pub fn parse_fragment(
|
|
276
|
+
document: &mut Document,
|
|
277
|
+
fragment: NodeId,
|
|
278
|
+
input: &[u8],
|
|
279
|
+
context: &Context,
|
|
280
|
+
options: &Options,
|
|
281
|
+
) -> Result<Parsed, LimitError> {
|
|
282
|
+
let parsed = FragmentParser::new(input.to_vec(), context, options).finish()?;
|
|
283
|
+
Ok(parsed.append_to(document, fragment))
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/// Parses a fragment in `context`. Returns its top-level nodes, each unlinked
|
|
287
|
+
/// from its parent and siblings.
|
|
288
|
+
pub fn parse_in_context(
|
|
289
|
+
document: &mut Document,
|
|
290
|
+
input: &[u8],
|
|
291
|
+
context: &Context,
|
|
292
|
+
options: &Options,
|
|
293
|
+
) -> Result<(Vec<NodeId>, Parsed), LimitError> {
|
|
294
|
+
let parsed = FragmentParser::new(input.to_vec(), context, options).finish()?;
|
|
295
|
+
Ok(parsed.import(document))
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/// A fragment parse that runs one chunk of input at a time, like
|
|
299
|
+
/// [`DocumentParser`]. It builds in its own scratch document. The scaffolding
|
|
300
|
+
/// of the parser (an html root, the context and form elements) and the nodes
|
|
301
|
+
/// of a failed parse never reach the target document.
|
|
302
|
+
pub struct FragmentParser(Run);
|
|
303
|
+
|
|
304
|
+
impl FragmentParser {
|
|
305
|
+
pub fn new(input: Vec<u8>, context: &Context, options: &Options) -> FragmentParser {
|
|
306
|
+
// The tree has an html element above the fragment nodes, as in gumbo.
|
|
307
|
+
let max_tree_depth = options.max_tree_depth.map(|depth| depth.saturating_add(1));
|
|
308
|
+
let sink = Sink::new(options, max_tree_depth);
|
|
309
|
+
// The tree builder starts in this mode and never sets it in a fragment.
|
|
310
|
+
sink.quirks_mode.set(context.quirks_mode);
|
|
311
|
+
|
|
312
|
+
let mut attributes = Vec::new();
|
|
313
|
+
if let Some(encoding) = &context.encoding {
|
|
314
|
+
attributes.push(Attribute {
|
|
315
|
+
name: QualName::new(None, ns!(), local_name!("encoding")),
|
|
316
|
+
value: StrTendril::from_slice(&String::from_utf8_lossy(encoding)),
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
let context_element = create_element(&sink, context.name.clone(), attributes);
|
|
320
|
+
let form = context.has_form_ancestor.then(|| {
|
|
321
|
+
let name = QualName::new(None, ns!(html), local_name!("form"));
|
|
322
|
+
create_element(&sink, name, Vec::new())
|
|
323
|
+
});
|
|
324
|
+
let builder = TreeBuilder::new_for_fragment(
|
|
325
|
+
sink,
|
|
326
|
+
context_element,
|
|
327
|
+
form,
|
|
328
|
+
tree_builder_options(options, context.quirks_mode),
|
|
329
|
+
);
|
|
330
|
+
let initial_state =
|
|
331
|
+
builder.tokenizer_state_for_context_elem(options.parse_noscript_content_as_text);
|
|
332
|
+
FragmentParser(Run::new(builder, input, options, Some(initial_state)))
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/// Parses the next chunk. Returns false when no input remains or a limit
|
|
336
|
+
/// was exceeded.
|
|
337
|
+
pub fn step(&mut self) -> bool {
|
|
338
|
+
self.0.step()
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
pub fn finish(self) -> Result<ParsedFragment, LimitError> {
|
|
342
|
+
let (scratch, parsed) = self.0.finish()?;
|
|
343
|
+
Ok(ParsedFragment { scratch, parsed })
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
pub struct ParsedFragment {
|
|
348
|
+
scratch: Document,
|
|
349
|
+
parsed: Parsed,
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
impl ParsedFragment {
|
|
353
|
+
/// Copies the top-level nodes into `document`, unlinked. The copies use
|
|
354
|
+
/// the names and namespace definitions that `document` writes.
|
|
355
|
+
pub fn import(self, document: &mut Document) -> (Vec<NodeId>, Parsed) {
|
|
356
|
+
let scratch = &self.scratch;
|
|
357
|
+
let root = scratch.first_child(NodeId::DOCUMENT);
|
|
358
|
+
let nodes = root
|
|
359
|
+
.into_iter()
|
|
360
|
+
.flat_map(|root| scratch.children(root))
|
|
361
|
+
.filter_map(|child| document.import(scratch, child, CopyDepth::Deep))
|
|
362
|
+
.collect();
|
|
363
|
+
(nodes, self.parsed)
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
pub fn append_to(self, document: &mut Document, fragment: NodeId) -> Parsed {
|
|
367
|
+
let (nodes, parsed) = self.import(document);
|
|
368
|
+
for node in nodes {
|
|
369
|
+
if document.append_child(fragment, node).is_err() {
|
|
370
|
+
break;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
parsed
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/// The binding of gumbo defines the foreign namespaces of a top-level element
|
|
378
|
+
/// and its descendants on that element. This puts them in scope as libxml2
|
|
379
|
+
/// needs.
|
|
380
|
+
fn define_namespaces(document: &mut Document, root: NodeId) {
|
|
381
|
+
let mut used = Vec::new();
|
|
382
|
+
for element in std::iter::once(root).chain(document.descendants(root)) {
|
|
383
|
+
let attributes = document.attributes(element).iter().copied();
|
|
384
|
+
for node in std::iter::once(element).chain(attributes) {
|
|
385
|
+
let Some(namespace) = document.namespace(node) else {
|
|
386
|
+
continue;
|
|
387
|
+
};
|
|
388
|
+
// libxml2 binds `xml` without a definition.
|
|
389
|
+
let Some(prefix) = namespace.prefix.filter(|&prefix| prefix != "xml") else {
|
|
390
|
+
continue;
|
|
391
|
+
};
|
|
392
|
+
if used
|
|
393
|
+
.iter()
|
|
394
|
+
.all(|(defined, _): &(Prefix, _)| **defined != *prefix)
|
|
395
|
+
{
|
|
396
|
+
used.push((Prefix::from(prefix), Namespace::from(namespace.href)));
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
for (prefix, href) in used {
|
|
401
|
+
document.define_namespace(root, Some(prefix), href);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/// The quirks mode of a doctype. Nokogiri computes it for a fragment parsed
|
|
406
|
+
/// in the context of a node of a parsed document.
|
|
407
|
+
pub fn quirks_mode_for_doctype(
|
|
408
|
+
name: Option<&[u8]>,
|
|
409
|
+
public_id: Option<&[u8]>,
|
|
410
|
+
system_id: Option<&[u8]>,
|
|
411
|
+
) -> QuirksMode {
|
|
412
|
+
let tendril = |bytes: Option<&[u8]>| {
|
|
413
|
+
bytes.map(|bytes| StrTendril::from_slice(&String::from_utf8_lossy(bytes)))
|
|
414
|
+
};
|
|
415
|
+
let doctype = tokenizer::Doctype {
|
|
416
|
+
name: tendril(name),
|
|
417
|
+
public_id: tendril(public_id),
|
|
418
|
+
system_id: tendril(system_id),
|
|
419
|
+
force_quirks: false,
|
|
420
|
+
};
|
|
421
|
+
// A tree builder in its initial mode decides the quirks mode
|
|
422
|
+
// from the doctype token, with the same table as for documents.
|
|
423
|
+
let options = Options::default();
|
|
424
|
+
let sink = Sink::new(&options, None);
|
|
425
|
+
let builder = TreeBuilder::new(sink, tree_builder_options(&options, QuirksMode::NoQuirks));
|
|
426
|
+
let _ = builder.process_token(Token::DoctypeToken(doctype), 1);
|
|
427
|
+
builder.sink.quirks_mode.get()
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
fn tree_builder_options(options: &Options, quirks_mode: QuirksMode) -> TreeBuilderOpts {
|
|
431
|
+
TreeBuilderOpts {
|
|
432
|
+
// Gumbo parses noscript content as markup, unless told not to.
|
|
433
|
+
scripting_enabled: options.parse_noscript_content_as_text,
|
|
434
|
+
quirks_mode: quirks_mode.into(),
|
|
435
|
+
..TreeBuilderOpts::default()
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/// Input goes to the tokenizer in pieces. Parsing then stops soon after a limit
|
|
440
|
+
/// is exceeded, and no tendril grows past its 32-bit length. The chunk
|
|
441
|
+
/// is smaller under Miri, so that tests can cross chunks quickly.
|
|
442
|
+
pub(super) const CHUNK: usize = if cfg!(miri) { 1 << 8 } else { 1 << 16 };
|
|
443
|
+
|
|
444
|
+
struct Run {
|
|
445
|
+
tokenizer: Tokenizer<Tokens>,
|
|
446
|
+
queue: BufferQueue,
|
|
447
|
+
input: String,
|
|
448
|
+
fed: usize,
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
impl Run {
|
|
452
|
+
fn new(
|
|
453
|
+
builder: TreeBuilder<NodeId, Sink>,
|
|
454
|
+
input: Vec<u8>,
|
|
455
|
+
options: &Options,
|
|
456
|
+
initial_state: Option<tokenizer::states::State>,
|
|
457
|
+
) -> Run {
|
|
458
|
+
let input = String::from_utf8(input)
|
|
459
|
+
.unwrap_or_else(|error| String::from_utf8_lossy(error.as_bytes()).into_owned());
|
|
460
|
+
let tokenizer = Tokenizer::new(
|
|
461
|
+
Tokens {
|
|
462
|
+
builder,
|
|
463
|
+
max_attributes: options.max_attributes,
|
|
464
|
+
exceeded: Cell::new(false),
|
|
465
|
+
},
|
|
466
|
+
TokenizerOpts {
|
|
467
|
+
initial_state,
|
|
468
|
+
discard_bom: !options.keep_bom,
|
|
469
|
+
..TokenizerOpts::default()
|
|
470
|
+
},
|
|
471
|
+
);
|
|
472
|
+
Run {
|
|
473
|
+
tokenizer,
|
|
474
|
+
queue: BufferQueue::default(),
|
|
475
|
+
input,
|
|
476
|
+
fed: 0,
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
fn step(&mut self) -> bool {
|
|
481
|
+
let rest = &self.input[self.fed..];
|
|
482
|
+
if rest.is_empty() || self.tokenizer.sink.limit_error().is_some() {
|
|
483
|
+
return false;
|
|
484
|
+
}
|
|
485
|
+
let mut end = rest.len().min(CHUNK);
|
|
486
|
+
while !rest.is_char_boundary(end) {
|
|
487
|
+
end += 1;
|
|
488
|
+
}
|
|
489
|
+
self.queue.push_back(StrTendril::from_slice(&rest[..end]));
|
|
490
|
+
self.fed += end;
|
|
491
|
+
while !matches!(self.tokenizer.feed(&self.queue), TokenizerResult::Done) {}
|
|
492
|
+
true
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
fn finish(mut self) -> Result<(Document, Parsed), LimitError> {
|
|
496
|
+
while self.step() {}
|
|
497
|
+
self.tokenizer.end();
|
|
498
|
+
|
|
499
|
+
let tokens = self.tokenizer.sink;
|
|
500
|
+
if let Some(error) = tokens.limit_error() {
|
|
501
|
+
return Err(error);
|
|
502
|
+
}
|
|
503
|
+
let sink = tokens.builder.sink;
|
|
504
|
+
let parsed = Parsed {
|
|
505
|
+
quirks_mode: sink.quirks_mode.get(),
|
|
506
|
+
errors: sink.errors.into_inner(),
|
|
507
|
+
};
|
|
508
|
+
Ok((sink.document.into_inner(), parsed))
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/// Passes tokens to the tree builder and counts the attributes. Gumbo's
|
|
513
|
+
/// tokenizer refuses a tag with more distinct attributes than the limit.
|
|
514
|
+
/// The tokenizer of html5ever has already dropped the duplicates.
|
|
515
|
+
struct Tokens {
|
|
516
|
+
builder: TreeBuilder<NodeId, Sink>,
|
|
517
|
+
max_attributes: Option<usize>,
|
|
518
|
+
exceeded: Cell<bool>,
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
impl Tokens {
|
|
522
|
+
fn limit_error(&self) -> Option<LimitError> {
|
|
523
|
+
if self.exceeded.get() {
|
|
524
|
+
Some(LimitError::TooManyAttributes)
|
|
525
|
+
} else if self.builder.sink.too_deep.get() {
|
|
526
|
+
Some(LimitError::TreeTooDeep)
|
|
527
|
+
} else {
|
|
528
|
+
None
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
impl TokenSink for Tokens {
|
|
534
|
+
type Handle = NodeId;
|
|
535
|
+
|
|
536
|
+
fn process_token(&self, token: Token, line_number: u64) -> TokenSinkResult<NodeId> {
|
|
537
|
+
crate::work::add(1);
|
|
538
|
+
if let Token::TagToken(tag) = &token {
|
|
539
|
+
if self.max_attributes.is_some_and(|max| tag.attrs.len() > max) {
|
|
540
|
+
self.exceeded.set(true);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
self.builder.process_token(token, line_number)
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
fn end(&self) {
|
|
547
|
+
self.builder.end();
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/// The tokenizer asks this at `<![`. If the answer is yes and `CDATA[`
|
|
551
|
+
/// follows, it opens a CDATA section.
|
|
552
|
+
fn adjusted_current_node_present_but_not_in_html_namespace(&self) -> bool {
|
|
553
|
+
self.builder
|
|
554
|
+
.adjusted_current_node_present_but_not_in_html_namespace()
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/// Builds the tree in the arena. The contents of a template are its children,
|
|
559
|
+
/// as Nokogiri builds them.
|
|
560
|
+
struct Sink {
|
|
561
|
+
document: RefCell<Document>,
|
|
562
|
+
quirks_mode: Cell<QuirksMode>,
|
|
563
|
+
line: Cell<u64>,
|
|
564
|
+
errors: RefCell<Vec<ParseError>>,
|
|
565
|
+
max_errors: Option<usize>,
|
|
566
|
+
max_tree_depth: Option<usize>,
|
|
567
|
+
too_deep: Cell<bool>,
|
|
568
|
+
integration_points: RefCell<HashSet<NodeId>>,
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
impl Sink {
|
|
572
|
+
fn new(options: &Options, max_tree_depth: Option<usize>) -> Sink {
|
|
573
|
+
Sink {
|
|
574
|
+
document: RefCell::new(Document::new(DocumentKind::Html)),
|
|
575
|
+
quirks_mode: Cell::new(QuirksMode::NoQuirks),
|
|
576
|
+
line: Cell::new(1),
|
|
577
|
+
errors: RefCell::new(Vec::new()),
|
|
578
|
+
max_errors: options.max_errors,
|
|
579
|
+
max_tree_depth,
|
|
580
|
+
too_deep: Cell::new(false),
|
|
581
|
+
integration_points: RefCell::default(),
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/// Gumbo limits its stack of open elements, which html5ever does
|
|
586
|
+
/// not expose. The depth here is the depth of the element pushed last,
|
|
587
|
+
/// so an element is measured where it is inserted. Void elements are never
|
|
588
|
+
/// pushed. Elements that the adoption agency moves are measured again.
|
|
589
|
+
/// Gumbo does not do that.
|
|
590
|
+
fn check_depth(&self, document: &Document, parent: NodeId, child: NodeId) {
|
|
591
|
+
let Some(max) = self.max_tree_depth else {
|
|
592
|
+
return;
|
|
593
|
+
};
|
|
594
|
+
if self.too_deep.get() {
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
let NodeKind::Element(element) = document.node_kind(child) else {
|
|
598
|
+
return;
|
|
599
|
+
};
|
|
600
|
+
if is_html(&element.name) && VOID_ELEMENTS.contains(&&*element.name.local) {
|
|
601
|
+
return;
|
|
602
|
+
}
|
|
603
|
+
let depth = std::iter::once(parent)
|
|
604
|
+
.chain(document.ancestors(parent))
|
|
605
|
+
.filter(|&id| matches!(document.node_kind(id), NodeKind::Element(_)))
|
|
606
|
+
.take(max)
|
|
607
|
+
.count()
|
|
608
|
+
+ 1;
|
|
609
|
+
if depth > max {
|
|
610
|
+
self.too_deep.set(true);
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
fn insert(&self, parent: NodeId, before: Option<NodeId>, child: NodeOrText<NodeId>) {
|
|
615
|
+
let mut document = self.document.borrow_mut();
|
|
616
|
+
let node = match child {
|
|
617
|
+
NodeOrText::AppendNode(node) => {
|
|
618
|
+
self.check_depth(&document, parent, node);
|
|
619
|
+
node
|
|
620
|
+
}
|
|
621
|
+
NodeOrText::AppendText(text) => {
|
|
622
|
+
match self.insert_text(&mut document, parent, before, text.as_bytes()) {
|
|
623
|
+
Some(node) => node,
|
|
624
|
+
None => return,
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
};
|
|
628
|
+
// html5ever asks only for insertions that the DOM allows.
|
|
629
|
+
let _ = match before {
|
|
630
|
+
Some(sibling) => document.insert_before(sibling, node),
|
|
631
|
+
None => document.append_child(parent, node),
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/// Adjacent character tokens make one text node. The characters of a CDATA
|
|
636
|
+
/// section are text too, as in the HTML standard. Gumbo makes one CDATA
|
|
637
|
+
/// node of them and the text around them, and serializes it raw. Returns
|
|
638
|
+
/// a new node to insert, or `None` if the text went into the adjacent node.
|
|
639
|
+
fn insert_text(
|
|
640
|
+
&self,
|
|
641
|
+
document: &mut Document,
|
|
642
|
+
parent: NodeId,
|
|
643
|
+
before: Option<NodeId>,
|
|
644
|
+
text: &[u8],
|
|
645
|
+
) -> Option<NodeId> {
|
|
646
|
+
crate::work::add(text.len());
|
|
647
|
+
if text.is_empty() {
|
|
648
|
+
return None;
|
|
649
|
+
}
|
|
650
|
+
let neighbour = match before {
|
|
651
|
+
Some(sibling) => document.previous_sibling(sibling),
|
|
652
|
+
None => document.last_child(parent),
|
|
653
|
+
};
|
|
654
|
+
match neighbour.and_then(|id| match document.node_kind(id) {
|
|
655
|
+
NodeKind::Text(_) => document.character_data_mut(id),
|
|
656
|
+
_ => None,
|
|
657
|
+
}) {
|
|
658
|
+
Some(data) => {
|
|
659
|
+
data.extend_from_slice(text);
|
|
660
|
+
None
|
|
661
|
+
}
|
|
662
|
+
None => Some(document.create_text(text.to_vec())),
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
#[derive(Debug)]
|
|
668
|
+
struct Name(QualName);
|
|
669
|
+
|
|
670
|
+
impl ElemName for Name {
|
|
671
|
+
fn ns(&self) -> &Namespace {
|
|
672
|
+
&self.0.ns
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
fn local_name(&self) -> &LocalName {
|
|
676
|
+
&self.0.local
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
impl TreeSink for Sink {
|
|
681
|
+
type Handle = NodeId;
|
|
682
|
+
type Output = ();
|
|
683
|
+
type ElemName<'b>
|
|
684
|
+
= Name
|
|
685
|
+
where
|
|
686
|
+
Self: 'b;
|
|
687
|
+
|
|
688
|
+
fn finish(self) {}
|
|
689
|
+
|
|
690
|
+
fn parse_error(&self, message: Cow<'static, str>) {
|
|
691
|
+
crate::work::add(1);
|
|
692
|
+
let mut errors = self.errors.borrow_mut();
|
|
693
|
+
if self.max_errors.is_none_or(|max| errors.len() < max) {
|
|
694
|
+
errors.push(ParseError {
|
|
695
|
+
line: self.line.get(),
|
|
696
|
+
message: message.into_owned(),
|
|
697
|
+
});
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
fn get_document(&self) -> NodeId {
|
|
702
|
+
NodeId::DOCUMENT
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
fn elem_name(&self, target: &NodeId) -> Name {
|
|
706
|
+
match self.document.borrow().node_kind(*target) {
|
|
707
|
+
NodeKind::Element(element) => Name(element.name.clone()),
|
|
708
|
+
_ => Name(QualName::new(None, ns!(), local_name!(""))),
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
fn create_element(
|
|
713
|
+
&self,
|
|
714
|
+
name: QualName,
|
|
715
|
+
attributes: Vec<Attribute>,
|
|
716
|
+
flags: ElementFlags,
|
|
717
|
+
) -> NodeId {
|
|
718
|
+
let mut document = self.document.borrow_mut();
|
|
719
|
+
let element = document.create_element(name);
|
|
720
|
+
for attribute in attributes {
|
|
721
|
+
let node =
|
|
722
|
+
document.create_attribute(attribute.name, attribute.value.as_bytes().to_vec());
|
|
723
|
+
let _ = document.append_attribute(element, node);
|
|
724
|
+
}
|
|
725
|
+
if flags.mathml_annotation_xml_integration_point {
|
|
726
|
+
self.integration_points.borrow_mut().insert(element);
|
|
727
|
+
}
|
|
728
|
+
element
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
fn create_comment(&self, text: StrTendril) -> NodeId {
|
|
732
|
+
self.document
|
|
733
|
+
.borrow_mut()
|
|
734
|
+
.create_comment(text.as_bytes().to_vec())
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
fn create_pi(&self, target: StrTendril, data: StrTendril) -> NodeId {
|
|
738
|
+
self.document
|
|
739
|
+
.borrow_mut()
|
|
740
|
+
.create_processing_instruction(target.as_bytes().to_vec(), data.as_bytes().to_vec())
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
fn append(&self, parent: &NodeId, child: NodeOrText<NodeId>) {
|
|
744
|
+
self.insert(*parent, None, child);
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
fn append_based_on_parent_node(
|
|
748
|
+
&self,
|
|
749
|
+
element: &NodeId,
|
|
750
|
+
prev_element: &NodeId,
|
|
751
|
+
child: NodeOrText<NodeId>,
|
|
752
|
+
) {
|
|
753
|
+
let has_parent = self.document.borrow().parent(*element).is_some();
|
|
754
|
+
if has_parent {
|
|
755
|
+
self.append_before_sibling(element, child);
|
|
756
|
+
} else {
|
|
757
|
+
self.append(prev_element, child);
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/// libxml2 makes the doctype the first child of the document, wherever
|
|
762
|
+
/// it was in the input.
|
|
763
|
+
fn append_doctype_to_document(
|
|
764
|
+
&self,
|
|
765
|
+
name: StrTendril,
|
|
766
|
+
public_id: StrTendril,
|
|
767
|
+
system_id: StrTendril,
|
|
768
|
+
) {
|
|
769
|
+
let optional = |id: StrTendril| (!id.is_empty()).then(|| id.as_bytes().to_vec());
|
|
770
|
+
let mut document = self.document.borrow_mut();
|
|
771
|
+
let doctype = document.create_doctype(Doctype {
|
|
772
|
+
name: name.as_bytes().to_vec(),
|
|
773
|
+
public_id: optional(public_id),
|
|
774
|
+
system_id: optional(system_id),
|
|
775
|
+
});
|
|
776
|
+
let _ = match document.first_child(NodeId::DOCUMENT) {
|
|
777
|
+
Some(first) => document.insert_before(first, doctype),
|
|
778
|
+
None => document.append_child(NodeId::DOCUMENT, doctype),
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
fn get_template_contents(&self, target: &NodeId) -> NodeId {
|
|
783
|
+
*target
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
fn same_node(&self, x: &NodeId, y: &NodeId) -> bool {
|
|
787
|
+
crate::work::add(1);
|
|
788
|
+
x == y
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
fn set_quirks_mode(&self, mode: html5ever::tree_builder::QuirksMode) {
|
|
792
|
+
self.quirks_mode.set(mode.into());
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
fn append_before_sibling(&self, sibling: &NodeId, new_node: NodeOrText<NodeId>) {
|
|
796
|
+
let parent = self.document.borrow().parent(*sibling);
|
|
797
|
+
if let Some(parent) = parent {
|
|
798
|
+
self.insert(parent, Some(*sibling), new_node);
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
fn add_attrs_if_missing(&self, target: &NodeId, attributes: Vec<Attribute>) {
|
|
803
|
+
let mut document = self.document.borrow_mut();
|
|
804
|
+
for attribute in attributes {
|
|
805
|
+
let present = document.attributes(*target).iter().any(|&existing| {
|
|
806
|
+
matches!(document.node_kind(existing),
|
|
807
|
+
NodeKind::Attribute(a) if a.name == attribute.name)
|
|
808
|
+
});
|
|
809
|
+
if !present {
|
|
810
|
+
let node =
|
|
811
|
+
document.create_attribute(attribute.name, attribute.value.as_bytes().to_vec());
|
|
812
|
+
let _ = document.append_attribute(*target, node);
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
fn remove_from_parent(&self, target: &NodeId) {
|
|
818
|
+
self.document.borrow_mut().detach(*target);
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
fn reparent_children(&self, node: &NodeId, new_parent: &NodeId) {
|
|
822
|
+
let mut document = self.document.borrow_mut();
|
|
823
|
+
while let Some(child) = document.first_child(*node) {
|
|
824
|
+
if document.append_child(*new_parent, child).is_err() {
|
|
825
|
+
break;
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
fn is_mathml_annotation_xml_integration_point(&self, handle: &NodeId) -> bool {
|
|
831
|
+
crate::work::add(1);
|
|
832
|
+
self.integration_points.borrow().contains(handle)
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
fn set_current_line(&self, line_number: u64) {
|
|
836
|
+
self.line.set(line_number);
|
|
837
|
+
}
|
|
838
|
+
}
|