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,370 @@
|
|
|
1
|
+
//! Nokogiri's `CSS::XPathVisitor` (lib/nokogiri/css/xpath_visitor.rb) writes
|
|
2
|
+
//! XPath strings for `CSS.xpath_for`. [`super::translate`] builds what libxml2
|
|
3
|
+
//! would read from these strings. This module pastes tokens as the visitor
|
|
4
|
+
//! does, into valid XPath or not.
|
|
5
|
+
|
|
6
|
+
use super::parser::{
|
|
7
|
+
unescape_string, Argument, AttributeName, AttributeOperator, AttributeSubject, Combinator,
|
|
8
|
+
Condition, ElementName, Function, Negation, Nth, Pseudo, Selector, Simple,
|
|
9
|
+
};
|
|
10
|
+
use super::translate::{is_of_type, read_a_and_positive_b, to_i, xpath_name};
|
|
11
|
+
use super::{SyntaxError, Visitor};
|
|
12
|
+
|
|
13
|
+
type Result<T> = std::result::Result<T, SyntaxError>;
|
|
14
|
+
|
|
15
|
+
/// What `"#{node}"` pastes for a `CSS::Node`. The Nokogiri text also has
|
|
16
|
+
/// the address of the object.
|
|
17
|
+
const NODE_TO_S: &str = "#<Nokogiri::CSS::Node>";
|
|
18
|
+
|
|
19
|
+
pub struct Writer<'a> {
|
|
20
|
+
visitor: &'a Visitor,
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
impl<'a> Writer<'a> {
|
|
24
|
+
pub fn new(visitor: &'a Visitor) -> Writer<'a> {
|
|
25
|
+
Writer { visitor }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
pub fn selector(&self, selector: &Selector) -> Result<String> {
|
|
29
|
+
let mut xpath = match selector.leading {
|
|
30
|
+
Some(Combinator::Child | Combinator::DirectAdjacent | Combinator::Following) => {
|
|
31
|
+
".".to_string()
|
|
32
|
+
}
|
|
33
|
+
Some(Combinator::Descendant) | None => self.visitor.prefix.clone(),
|
|
34
|
+
};
|
|
35
|
+
self.chain(&mut xpath, selector)?;
|
|
36
|
+
Ok(xpath)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
fn chain(&self, xpath: &mut String, selector: &Selector) -> Result<()> {
|
|
40
|
+
if let Some(combinator) = selector.leading {
|
|
41
|
+
xpath.push_str(separator(combinator));
|
|
42
|
+
}
|
|
43
|
+
self.simple(xpath, &selector.first)?;
|
|
44
|
+
for (combinator, simple) in &selector.rest {
|
|
45
|
+
xpath.push_str(separator(*combinator));
|
|
46
|
+
self.simple(xpath, simple)?;
|
|
47
|
+
}
|
|
48
|
+
Ok(())
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
fn simple(&self, xpath: &mut String, simple: &Simple) -> Result<()> {
|
|
52
|
+
match simple {
|
|
53
|
+
Simple::Element { name, conditions } => {
|
|
54
|
+
xpath.push_str(&self.element_name(name)?);
|
|
55
|
+
if !conditions.is_empty() {
|
|
56
|
+
xpath.push('[');
|
|
57
|
+
self.conditions(xpath, conditions)?;
|
|
58
|
+
xpath.push(']');
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
Simple::Function {
|
|
62
|
+
function,
|
|
63
|
+
condition,
|
|
64
|
+
} => {
|
|
65
|
+
self.function(xpath, function)?;
|
|
66
|
+
if let Some(condition) = condition {
|
|
67
|
+
xpath.push('[');
|
|
68
|
+
self.condition(xpath, condition)?;
|
|
69
|
+
xpath.push(']');
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
Simple::Attribute(name) => xpath.push_str(&attribute_name(name)?),
|
|
73
|
+
}
|
|
74
|
+
Ok(())
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
fn conditions(&self, xpath: &mut String, conditions: &[Condition]) -> Result<()> {
|
|
78
|
+
for (index, condition) in conditions.iter().enumerate() {
|
|
79
|
+
if index > 0 {
|
|
80
|
+
let last = index == conditions.len() - 1;
|
|
81
|
+
xpath.push_str(if last && is_of_type(condition) {
|
|
82
|
+
"]["
|
|
83
|
+
} else {
|
|
84
|
+
" and "
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
self.condition(xpath, condition)?;
|
|
88
|
+
}
|
|
89
|
+
Ok(())
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
fn condition(&self, xpath: &mut String, condition: &Condition) -> Result<()> {
|
|
93
|
+
match condition {
|
|
94
|
+
Condition::Id(id) => {
|
|
95
|
+
xpath.push_str("@id=");
|
|
96
|
+
xpath.push_str(&literal(id.strip_prefix('#').unwrap_or(id)));
|
|
97
|
+
}
|
|
98
|
+
Condition::Class(name) => xpath.push_str(&self.css_class("@class", name)),
|
|
99
|
+
Condition::Attribute { subject, test } => {
|
|
100
|
+
self.attribute_condition(xpath, subject, test)?;
|
|
101
|
+
}
|
|
102
|
+
Condition::Pseudo(Pseudo::Ident(name)) => xpath.push_str(&pseudo_class(name)?),
|
|
103
|
+
Condition::Pseudo(Pseudo::Function(function)) => self.function(xpath, function)?,
|
|
104
|
+
Condition::Not(Negation::Element(name)) => {
|
|
105
|
+
xpath.push_str("not(self::");
|
|
106
|
+
xpath.push_str(&self.element_name(name)?);
|
|
107
|
+
xpath.push(')');
|
|
108
|
+
}
|
|
109
|
+
Condition::Not(Negation::Conditions(conditions)) => {
|
|
110
|
+
xpath.push_str("not(");
|
|
111
|
+
self.conditions(xpath, conditions)?;
|
|
112
|
+
xpath.push(')');
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
Ok(())
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
fn attribute_condition(
|
|
119
|
+
&self,
|
|
120
|
+
xpath: &mut String,
|
|
121
|
+
subject: &AttributeSubject,
|
|
122
|
+
test: &Option<(AttributeOperator, String)>,
|
|
123
|
+
) -> Result<()> {
|
|
124
|
+
let attribute = match subject {
|
|
125
|
+
AttributeSubject::Name(name) => attribute_name(name)?,
|
|
126
|
+
AttributeSubject::Function(function) => {
|
|
127
|
+
let mut call = String::new();
|
|
128
|
+
self.function(&mut call, function)?;
|
|
129
|
+
call
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
let Some((operator, text)) = test else {
|
|
133
|
+
xpath.push_str(&attribute);
|
|
134
|
+
return Ok(());
|
|
135
|
+
};
|
|
136
|
+
let value = literal(text);
|
|
137
|
+
xpath.push_str(&match operator {
|
|
138
|
+
AttributeOperator::Equal => format!("{attribute}={value}"),
|
|
139
|
+
AttributeOperator::NotEqual => format!("{attribute}!={value}"),
|
|
140
|
+
AttributeOperator::SubstringMatch => format!("contains({attribute},{value})"),
|
|
141
|
+
AttributeOperator::PrefixMatch => format!("starts-with({attribute},{value})"),
|
|
142
|
+
AttributeOperator::DashMatch => format!(
|
|
143
|
+
"{attribute}={value} or starts-with({attribute},concat({value},'-'))"
|
|
144
|
+
),
|
|
145
|
+
AttributeOperator::Includes => self.css_class(&attribute, text),
|
|
146
|
+
AttributeOperator::SuffixMatch => format!(
|
|
147
|
+
"substring({attribute},string-length({attribute})-string-length({value})+1,string-length({value}))={value}"
|
|
148
|
+
),
|
|
149
|
+
});
|
|
150
|
+
Ok(())
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/// `visit_function`, by the name with its `(`.
|
|
154
|
+
fn function(&self, xpath: &mut String, function: &Function) -> Result<()> {
|
|
155
|
+
let argument = function.arguments.first();
|
|
156
|
+
let nth = match argument {
|
|
157
|
+
Some(Argument::Nth(nth)) => Some(nth),
|
|
158
|
+
_ => None,
|
|
159
|
+
};
|
|
160
|
+
let written = match function.name.as_str() {
|
|
161
|
+
"text(" => "child::text()".into(),
|
|
162
|
+
"self(" => format!("self::{}", pasted(argument)),
|
|
163
|
+
"eq(" => format!("position()={}", pasted(argument)),
|
|
164
|
+
"nth(" | "nth-of-type(" => match nth {
|
|
165
|
+
Some(nth) => self::nth(nth, false, false)?,
|
|
166
|
+
None => format!("position()={}", pasted(argument)),
|
|
167
|
+
},
|
|
168
|
+
"nth-child(" => match nth {
|
|
169
|
+
Some(nth) => self::nth(nth, true, false)?,
|
|
170
|
+
None => format!("count(preceding-sibling::*)={}", to_i(argument)? - 1),
|
|
171
|
+
},
|
|
172
|
+
"nth-last-of-type(" => match nth {
|
|
173
|
+
Some(nth) => self::nth(nth, false, true)?,
|
|
174
|
+
None => match to_i(argument)? - 1 {
|
|
175
|
+
0 => "position()=last()".into(),
|
|
176
|
+
index => format!("position()=last()-{index}"),
|
|
177
|
+
},
|
|
178
|
+
},
|
|
179
|
+
"nth-last-child(" => match nth {
|
|
180
|
+
Some(nth) => self::nth(nth, true, true)?,
|
|
181
|
+
None => format!("count(following-sibling::*)={}", to_i(argument)? - 1),
|
|
182
|
+
},
|
|
183
|
+
"first(" | "first-of-type(" => "position()=1".into(),
|
|
184
|
+
"last(" | "last-of-type(" => "position()=last()".into(),
|
|
185
|
+
"contains(" => format!("contains(.,{})", function_argument(argument)?),
|
|
186
|
+
"gt(" => format!("position()>{}", pasted(argument)),
|
|
187
|
+
"only-child(" => "last()=1".into(),
|
|
188
|
+
"comment(" => "comment()".into(),
|
|
189
|
+
"has(" => return self.has(xpath, argument),
|
|
190
|
+
name => {
|
|
191
|
+
validate_function_name(name)?;
|
|
192
|
+
let mut call = format!("nokogiri:{name}.");
|
|
193
|
+
for argument in &function.arguments {
|
|
194
|
+
call.push(',');
|
|
195
|
+
call.push_str(&function_argument(Some(argument))?);
|
|
196
|
+
}
|
|
197
|
+
call.push(')');
|
|
198
|
+
call
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
xpath.push_str(&written);
|
|
202
|
+
Ok(())
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/// `has(…)`: `.//` and the first selector. Or `.` and the selector,
|
|
206
|
+
/// when the visitor finds nothing before its combinator. The rest
|
|
207
|
+
/// are ignored.
|
|
208
|
+
fn has(&self, xpath: &mut String, argument: Option<&Argument>) -> Result<()> {
|
|
209
|
+
let Some(Argument::Selector(selector)) = argument else {
|
|
210
|
+
return Err(SyntaxError("has() takes a selector".into()));
|
|
211
|
+
};
|
|
212
|
+
// The visitor checks `value[0].nil?`, which `|name` also passes.
|
|
213
|
+
let bare_no_namespace = selector.rest.is_empty()
|
|
214
|
+
&& matches!(
|
|
215
|
+
&selector.first,
|
|
216
|
+
Simple::Element { name: ElementName { prefix: Some(None), .. }, conditions }
|
|
217
|
+
if conditions.is_empty()
|
|
218
|
+
);
|
|
219
|
+
xpath.push('.');
|
|
220
|
+
if selector.leading.is_none() && !bare_no_namespace {
|
|
221
|
+
xpath.push_str("//");
|
|
222
|
+
}
|
|
223
|
+
self.chain(xpath, selector)
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
fn element_name(&self, name: &ElementName) -> Result<String> {
|
|
227
|
+
let local = name.local.as_str();
|
|
228
|
+
if self.visitor.html5 && name.prefix.is_none() && local != "*" {
|
|
229
|
+
// HTML5 has namespaces that CSS queries ignore.
|
|
230
|
+
return Ok(if !self.visitor.builtins {
|
|
231
|
+
format!("*[local-name()={}]", literal(local))
|
|
232
|
+
} else if xpath_name(local) {
|
|
233
|
+
format!("*:{local}")
|
|
234
|
+
} else {
|
|
235
|
+
format!("*[nokogiri-builtin:local-name-is({})]", literal(local))
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
let mut names = name.prefix.iter().flatten().chain([&name.local]);
|
|
239
|
+
if let Some(invalid) = names.find(|n| *n != "*" && !xpath_name(n)) {
|
|
240
|
+
return Err(SyntaxError(format!("Invalid element name '{invalid}'")));
|
|
241
|
+
}
|
|
242
|
+
Ok(match &name.prefix {
|
|
243
|
+
Some(Some(prefix)) => format!("{prefix}:{local}"),
|
|
244
|
+
Some(None) => local.into(),
|
|
245
|
+
None if local != "*" && self.visitor.default_namespace => format!("xmlns:{local}"),
|
|
246
|
+
None => local.into(),
|
|
247
|
+
})
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
fn css_class(&self, haystack: &str, needle: &str) -> String {
|
|
251
|
+
if self.visitor.builtins {
|
|
252
|
+
format!("nokogiri-builtin:css-class({haystack},{})", literal(needle))
|
|
253
|
+
} else {
|
|
254
|
+
let padded = literal(&format!(" {needle} "));
|
|
255
|
+
format!("contains(concat(' ',normalize-space({haystack}),' '),{padded})")
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/// What the combinator methods of the visitor put between two selectors.
|
|
261
|
+
fn separator(combinator: Combinator) -> &'static str {
|
|
262
|
+
match combinator {
|
|
263
|
+
Combinator::DirectAdjacent => "/following-sibling::*[1]/self::",
|
|
264
|
+
Combinator::Following => "/following-sibling::",
|
|
265
|
+
Combinator::Descendant => "//",
|
|
266
|
+
Combinator::Child => "/",
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
fn pseudo_class(name: &str) -> Result<String> {
|
|
271
|
+
Ok(match name {
|
|
272
|
+
"first" | "first-of-type" => "position()=1",
|
|
273
|
+
"first-child" => "count(preceding-sibling::*)=0",
|
|
274
|
+
"last" | "last-of-type" => "position()=last()",
|
|
275
|
+
"last-child" => "count(following-sibling::*)=0",
|
|
276
|
+
"only-child" => "count(preceding-sibling::*)=0 and count(following-sibling::*)=0",
|
|
277
|
+
"only-of-type" => "last()=1",
|
|
278
|
+
"empty" => "not(node())",
|
|
279
|
+
"parent" => "node()",
|
|
280
|
+
"root" => "not(parent::*)",
|
|
281
|
+
_ => {
|
|
282
|
+
validate_function_name(name)?;
|
|
283
|
+
return Ok(format!("nokogiri:{name}(.)"));
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
.into())
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/// `visit_attrib_name`: `@name`, `@prefix:name`, or, for a name that XPath
|
|
290
|
+
/// cannot write, a test of `name()`.
|
|
291
|
+
fn attribute_name(name: &AttributeName) -> Result<String> {
|
|
292
|
+
let local = name.local.as_str();
|
|
293
|
+
Ok(match &name.prefix {
|
|
294
|
+
Some(prefix) if xpath_name(prefix) && xpath_name(local) => format!("@{prefix}:{local}"),
|
|
295
|
+
Some(prefix) => {
|
|
296
|
+
let message = format!("Invalid attribute name '{prefix}|{local}'");
|
|
297
|
+
return Err(SyntaxError(message));
|
|
298
|
+
}
|
|
299
|
+
None if xpath_name(local) => format!("@{local}"),
|
|
300
|
+
None => format!("@*[namespace-uri()='' and name()={}]", literal(local)),
|
|
301
|
+
})
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
fn validate_function_name(name: &str) -> Result<()> {
|
|
305
|
+
if name.starts_with('-') {
|
|
306
|
+
return Err(SyntaxError(format!("Invalid XPath function name '{name}'")));
|
|
307
|
+
}
|
|
308
|
+
Ok(())
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/// `nth`: compares `an+b` with the position along the axis, or among
|
|
312
|
+
/// the element siblings for the `*-child` forms.
|
|
313
|
+
fn nth(nth: &Nth, child: bool, last: bool) -> Result<String> {
|
|
314
|
+
let (a, b) = read_a_and_positive_b(nth)?;
|
|
315
|
+
let position = match (child, last) {
|
|
316
|
+
(true, false) => "(count(preceding-sibling::*)+1)",
|
|
317
|
+
(true, true) => "(count(following-sibling::*)+1)",
|
|
318
|
+
(false, false) => "position()",
|
|
319
|
+
(false, true) => "(last()-position()+1)",
|
|
320
|
+
};
|
|
321
|
+
Ok(if a == 0 {
|
|
322
|
+
format!("{position}={b}")
|
|
323
|
+
} else if b == 0 && a > 0 {
|
|
324
|
+
format!("({position} mod {a})=0")
|
|
325
|
+
} else {
|
|
326
|
+
let compare = if a < 0 { "<=" } else { ">=" };
|
|
327
|
+
let modulus = a.unsigned_abs();
|
|
328
|
+
if modulus == 1 {
|
|
329
|
+
format!("{position}{compare}{b}")
|
|
330
|
+
} else {
|
|
331
|
+
format!("({position}{compare}{b}) and ((({position}-{b}) mod {modulus})=0)")
|
|
332
|
+
}
|
|
333
|
+
})
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/// The first argument of a function as `"#{node.value[1]}"` pastes
|
|
337
|
+
/// it: the token as written, or nothing.
|
|
338
|
+
fn pasted(argument: Option<&Argument>) -> &str {
|
|
339
|
+
match argument {
|
|
340
|
+
Some(Argument::Number(token) | Argument::String(token) | Argument::Ident(token)) => token,
|
|
341
|
+
Some(Argument::Nth(_) | Argument::Attribute(_) | Argument::Selector(_)) => NODE_TO_S,
|
|
342
|
+
None => "",
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/// `xpath_function_argument`: the unescaped text of a string as a literal,
|
|
347
|
+
/// an `@name`, or any other token as written.
|
|
348
|
+
fn function_argument(argument: Option<&Argument>) -> Result<String> {
|
|
349
|
+
Ok(match argument {
|
|
350
|
+
Some(Argument::String(string)) => literal(&unescape_string(&string[1..string.len() - 1])),
|
|
351
|
+
Some(Argument::Attribute(name)) => attribute_name(name)?,
|
|
352
|
+
Some(Argument::Nth(_)) => return Err(SyntaxError("undefined method 'visit_nth'".into())),
|
|
353
|
+
argument => pasted(argument).into(),
|
|
354
|
+
})
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/// `xpath_string_literal`: XPath strings have no escapes, so `concat()` joins
|
|
358
|
+
/// a string that has both quotes.
|
|
359
|
+
fn literal(text: &str) -> String {
|
|
360
|
+
if !text.contains('\'') {
|
|
361
|
+
format!("'{text}'")
|
|
362
|
+
} else if !text.contains('"') {
|
|
363
|
+
format!("\"{text}\"")
|
|
364
|
+
} else {
|
|
365
|
+
format!(
|
|
366
|
+
"concat('{}')",
|
|
367
|
+
text.split('\'').collect::<Vec<_>>().join("',\"'\",'")
|
|
368
|
+
)
|
|
369
|
+
}
|
|
370
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
//! Finds attributes by name, as the libxml2 functions behind the attribute
|
|
2
|
+
//! readers of Nokogiri do. Names are compared as bytes, because Ruby passes
|
|
3
|
+
//! them in any encoding.
|
|
4
|
+
|
|
5
|
+
use super::namespace::split_qualified_name;
|
|
6
|
+
use super::{Attribute, Document, NodeId, NodeKind, QualName};
|
|
7
|
+
use html5ever::{ns, LocalName, Namespace, Prefix};
|
|
8
|
+
use std::iter;
|
|
9
|
+
|
|
10
|
+
impl Document {
|
|
11
|
+
/// The first attribute with this local name in any namespace: libxml2's
|
|
12
|
+
/// `xmlHasProp`.
|
|
13
|
+
pub fn attribute_named(&self, element: NodeId, name: &[u8]) -> Option<NodeId> {
|
|
14
|
+
self.find_attribute(element, |attribute| attribute.name.local.as_bytes() == name)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/// The attribute with this local name in the namespace `href`, or in no
|
|
18
|
+
/// namespace if `href` is `None`: libxml2's `xmlHasNsProp`.
|
|
19
|
+
pub fn attribute_in_namespace(
|
|
20
|
+
&self,
|
|
21
|
+
element: NodeId,
|
|
22
|
+
name: &[u8],
|
|
23
|
+
href: Option<&[u8]>,
|
|
24
|
+
) -> Option<NodeId> {
|
|
25
|
+
self.find_attribute(element, |attribute| {
|
|
26
|
+
let namespace = &attribute.name.ns;
|
|
27
|
+
attribute.name.local.as_bytes() == name
|
|
28
|
+
&& match href {
|
|
29
|
+
Some(href) => *namespace != ns!() && namespace.as_bytes() == href,
|
|
30
|
+
None => *namespace == ns!(),
|
|
31
|
+
}
|
|
32
|
+
})
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/// Nokogiri's `Node#[]`. A name with a colon is `prefix:local`
|
|
36
|
+
/// when the prefix is in scope. Otherwise it matches an attribute
|
|
37
|
+
/// with that whole name in any namespace. A name without a colon matches
|
|
38
|
+
/// only attributes in no namespace.
|
|
39
|
+
pub fn attribute_value(&self, element: NodeId, name: &[u8]) -> Option<&[u8]> {
|
|
40
|
+
let attribute = match name.iter().position(|&byte| byte == b':') {
|
|
41
|
+
Some(colon) => match self.search_namespace(element, &name[..colon]) {
|
|
42
|
+
Some(namespace) => self.attribute_in_namespace(
|
|
43
|
+
element,
|
|
44
|
+
&name[colon + 1..],
|
|
45
|
+
Some(namespace.href.as_bytes()),
|
|
46
|
+
),
|
|
47
|
+
None => self.attribute_named(element, name),
|
|
48
|
+
},
|
|
49
|
+
None => self.attribute_in_namespace(element, name, None),
|
|
50
|
+
}?;
|
|
51
|
+
self.value_of(attribute)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/// The nearest `xml:lang` on the node or an ancestor: libxml2's
|
|
55
|
+
/// `xmlNodeGetLang`. A `lang` attribute does not count.
|
|
56
|
+
pub fn lang(&self, id: NodeId) -> Option<&[u8]> {
|
|
57
|
+
let href = ns!(xml);
|
|
58
|
+
iter::once(id)
|
|
59
|
+
.chain(self.ancestors(id))
|
|
60
|
+
.find_map(|node| self.attribute_in_namespace(node, b"lang", Some(href.as_bytes())))
|
|
61
|
+
.and_then(|attribute| self.value_of(attribute))
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/// Nokogiri's `Node#[]=`, libxml2's `xmlSetProp`. A name with a colon
|
|
65
|
+
/// is `prefix:local` when the prefix is in scope and neither side is empty.
|
|
66
|
+
/// Otherwise it is the whole name of an attribute in no namespace.
|
|
67
|
+
/// An existing attribute keeps its node and gets the new value. `None`
|
|
68
|
+
/// for anything but an element.
|
|
69
|
+
pub fn set_attribute(&mut self, element: NodeId, name: &str, value: Vec<u8>) -> Option<NodeId> {
|
|
70
|
+
if !matches!(self.node_kind(element), NodeKind::Element(_)) {
|
|
71
|
+
return None;
|
|
72
|
+
}
|
|
73
|
+
let namespace = split_qualified_name(name).and_then(|(prefix, local)| {
|
|
74
|
+
let namespace = self.search_namespace(element, prefix.as_bytes())?;
|
|
75
|
+
Some((prefix, local, Namespace::from(namespace.href)))
|
|
76
|
+
});
|
|
77
|
+
let name = match namespace {
|
|
78
|
+
Some((prefix, local, href)) => {
|
|
79
|
+
QualName::new(Some(Prefix::from(prefix)), href, LocalName::from(local))
|
|
80
|
+
}
|
|
81
|
+
None => QualName::new(None, ns!(), LocalName::from(name)),
|
|
82
|
+
};
|
|
83
|
+
Some(self.set_attribute_name(element, name, value))
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/// `Attr#value=`. Nokogiri escapes the value
|
|
87
|
+
/// with `xmlEncodeEntitiesReentrant` and libxml2 unescapes it again.
|
|
88
|
+
/// The value is therefore stored as given, except for the C0 controls
|
|
89
|
+
/// that the escaping drops: all but tab, LF and CR.
|
|
90
|
+
pub fn set_attribute_value(&mut self, attribute: NodeId, mut value: Vec<u8>) {
|
|
91
|
+
value.retain(|&byte| byte >= 0x20 || matches!(byte, b'\t' | b'\n' | b'\r'));
|
|
92
|
+
if let NodeKind::Attribute(attribute) = &mut self.node_mut(attribute).kind {
|
|
93
|
+
attribute.value = value;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
pub fn set_lang(&mut self, id: NodeId, lang: Vec<u8>) {
|
|
98
|
+
if matches!(self.node_kind(id), NodeKind::Element(_)) {
|
|
99
|
+
let name = QualName::new(Some(Prefix::from("xml")), ns!(xml), LocalName::from("lang"));
|
|
100
|
+
self.set_attribute_name(id, name, lang);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
fn set_attribute_name(&mut self, element: NodeId, name: QualName, value: Vec<u8>) -> NodeId {
|
|
105
|
+
let href = (name.ns != ns!()).then(|| name.ns.clone());
|
|
106
|
+
let existing = self.attribute_in_namespace(
|
|
107
|
+
element,
|
|
108
|
+
name.local.as_bytes(),
|
|
109
|
+
href.as_ref().map(|href| href.as_bytes()),
|
|
110
|
+
);
|
|
111
|
+
match existing {
|
|
112
|
+
Some(attribute) => {
|
|
113
|
+
if let NodeKind::Attribute(existing) = &mut self.node_mut(attribute).kind {
|
|
114
|
+
existing.name = name;
|
|
115
|
+
existing.value = value;
|
|
116
|
+
}
|
|
117
|
+
attribute
|
|
118
|
+
}
|
|
119
|
+
None => {
|
|
120
|
+
let attribute = self.create_attribute(name, value);
|
|
121
|
+
self.append_attribute(element, attribute)
|
|
122
|
+
.expect("checked to be an element");
|
|
123
|
+
attribute
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
fn value_of(&self, attribute: NodeId) -> Option<&[u8]> {
|
|
129
|
+
match self.node_kind(attribute) {
|
|
130
|
+
NodeKind::Attribute(attribute) => Some(&attribute.value),
|
|
131
|
+
_ => None,
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
fn find_attribute(
|
|
136
|
+
&self,
|
|
137
|
+
element: NodeId,
|
|
138
|
+
matches: impl Fn(&Attribute) -> bool,
|
|
139
|
+
) -> Option<NodeId> {
|
|
140
|
+
self.attributes(element).iter().copied().find(|&id| {
|
|
141
|
+
matches!(self.node_kind(id), NodeKind::Attribute(attribute) if matches(attribute))
|
|
142
|
+
})
|
|
143
|
+
}
|
|
144
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
use super::{Document, NodeId, NodeKind};
|
|
2
|
+
use html5ever::ns;
|
|
3
|
+
|
|
4
|
+
impl Document {
|
|
5
|
+
/// Verifies that every link in the arena agrees with its counterpart.
|
|
6
|
+
/// For tests and fuzz targets. Linear in the size of the arena.
|
|
7
|
+
pub fn check_invariants(&self) -> Result<(), String> {
|
|
8
|
+
if self.parent(NodeId::DOCUMENT).is_some() {
|
|
9
|
+
return Err("the document node has a parent".into());
|
|
10
|
+
}
|
|
11
|
+
// Set when a node is reached from the children or attributes
|
|
12
|
+
// of its parent.
|
|
13
|
+
let mut listed = vec![false; self.nodes.len()];
|
|
14
|
+
for id in self.node_ids() {
|
|
15
|
+
if id != NodeId::DOCUMENT && matches!(self.node_kind(id), NodeKind::Document) {
|
|
16
|
+
return Err(format!("{id:?} is a second document node"));
|
|
17
|
+
}
|
|
18
|
+
self.check_children(id, &mut listed)?;
|
|
19
|
+
self.check_attributes(id, &mut listed)?;
|
|
20
|
+
}
|
|
21
|
+
for id in self.node_ids() {
|
|
22
|
+
match self.parent(id) {
|
|
23
|
+
Some(parent) if !listed[id.index()] => {
|
|
24
|
+
return Err(format!("{id:?} isn't listed by its parent {parent:?}"));
|
|
25
|
+
}
|
|
26
|
+
None if self.previous_sibling(id).is_some() || self.next_sibling(id).is_some() => {
|
|
27
|
+
return Err(format!("{id:?} has siblings but no parent"));
|
|
28
|
+
}
|
|
29
|
+
_ => {}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
self.check_acyclic()?;
|
|
33
|
+
self.check_names()?;
|
|
34
|
+
self.check_order()
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/// An element in no namespace, in libxml2's terms, is in the namespace
|
|
38
|
+
/// that stands for none in this kind of document. A name with a prefix has
|
|
39
|
+
/// a local part.
|
|
40
|
+
fn check_names(&self) -> Result<(), String> {
|
|
41
|
+
let default_namespace = self.default_namespace();
|
|
42
|
+
for id in self.node_ids() {
|
|
43
|
+
let name = match self.node_kind(id) {
|
|
44
|
+
NodeKind::Element(element) => {
|
|
45
|
+
let unqualified = element.name.prefix.is_none()
|
|
46
|
+
&& (element.name.ns == ns!() || element.name.ns == ns!(html));
|
|
47
|
+
if unqualified && element.name.ns != default_namespace {
|
|
48
|
+
return Err(format!(
|
|
49
|
+
"element {id:?} is in {:?}, not this document's {default_namespace:?}",
|
|
50
|
+
element.name.ns
|
|
51
|
+
));
|
|
52
|
+
}
|
|
53
|
+
&element.name
|
|
54
|
+
}
|
|
55
|
+
NodeKind::Attribute(attribute) => &attribute.name,
|
|
56
|
+
_ => continue,
|
|
57
|
+
};
|
|
58
|
+
if name.prefix.is_some() && name.local.is_empty() {
|
|
59
|
+
return Err(format!("{id:?} has a prefix but no local name"));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
Ok(())
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/// The document order that comparisons numbered is the one that numbering
|
|
66
|
+
/// gives now.
|
|
67
|
+
fn check_order(&self) -> Result<(), String> {
|
|
68
|
+
let Some(order) = self.order.get() else {
|
|
69
|
+
return Ok(());
|
|
70
|
+
};
|
|
71
|
+
let current = self.number_nodes();
|
|
72
|
+
match order
|
|
73
|
+
.iter()
|
|
74
|
+
.zip(¤t)
|
|
75
|
+
.position(|(kept, now)| kept != now)
|
|
76
|
+
{
|
|
77
|
+
Some(index) => Err(format!(
|
|
78
|
+
"the kept document order is stale at node index {index}"
|
|
79
|
+
)),
|
|
80
|
+
None => Ok(()),
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
fn check_children(&self, id: NodeId, listed: &mut [bool]) -> Result<(), String> {
|
|
85
|
+
let mut previous = None;
|
|
86
|
+
let mut next = self.first_child(id);
|
|
87
|
+
while let Some(child) = next {
|
|
88
|
+
// Also ends a sibling list that loops back on itself.
|
|
89
|
+
if std::mem::replace(&mut listed[child.index()], true) {
|
|
90
|
+
return Err(format!("{child:?} is listed twice"));
|
|
91
|
+
}
|
|
92
|
+
if self.parent(child) != Some(id) {
|
|
93
|
+
return Err(format!(
|
|
94
|
+
"{child:?} is linked under {id:?} but has another parent"
|
|
95
|
+
));
|
|
96
|
+
}
|
|
97
|
+
if self.previous_sibling(child) != previous {
|
|
98
|
+
return Err(format!("{child:?} has the wrong previous sibling"));
|
|
99
|
+
}
|
|
100
|
+
if matches!(self.node_kind(child), NodeKind::Attribute(_)) {
|
|
101
|
+
return Err(format!("attribute {child:?} is a child of {id:?}"));
|
|
102
|
+
}
|
|
103
|
+
previous = Some(child);
|
|
104
|
+
next = self.next_sibling(child);
|
|
105
|
+
}
|
|
106
|
+
if self.last_child(id) != previous {
|
|
107
|
+
return Err(format!("{id:?} has the wrong last child"));
|
|
108
|
+
}
|
|
109
|
+
if previous.is_some() && !self.node_kind(id).can_have_children() {
|
|
110
|
+
return Err(format!("{id:?} can't have children but has some"));
|
|
111
|
+
}
|
|
112
|
+
Ok(())
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
fn check_attributes(&self, id: NodeId, listed: &mut [bool]) -> Result<(), String> {
|
|
116
|
+
for &attribute in self.attributes(id) {
|
|
117
|
+
if !matches!(self.node_kind(attribute), NodeKind::Attribute(_)) {
|
|
118
|
+
return Err(format!("{attribute:?} on {id:?} isn't an attribute"));
|
|
119
|
+
}
|
|
120
|
+
if self.parent(attribute) != Some(id) {
|
|
121
|
+
return Err(format!("attribute {attribute:?} has the wrong parent"));
|
|
122
|
+
}
|
|
123
|
+
if std::mem::replace(&mut listed[attribute.index()], true) {
|
|
124
|
+
return Err(format!("attribute {attribute:?} is listed twice"));
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
Ok(())
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/// Follows the parent links from every node. It remembers which nodes reach
|
|
131
|
+
/// a root, so each link is followed once.
|
|
132
|
+
fn check_acyclic(&self) -> Result<(), String> {
|
|
133
|
+
#[derive(Clone, Copy, PartialEq)]
|
|
134
|
+
enum Walk {
|
|
135
|
+
Unvisited,
|
|
136
|
+
OnPath,
|
|
137
|
+
ReachesRoot,
|
|
138
|
+
}
|
|
139
|
+
let mut walk = vec![Walk::Unvisited; self.nodes.len()];
|
|
140
|
+
let mut path = Vec::new();
|
|
141
|
+
for start in self.node_ids() {
|
|
142
|
+
let mut next = Some(start);
|
|
143
|
+
while let Some(id) = next {
|
|
144
|
+
match walk[id.index()] {
|
|
145
|
+
Walk::ReachesRoot => break,
|
|
146
|
+
Walk::OnPath => return Err(format!("{id:?} is its own ancestor")),
|
|
147
|
+
Walk::Unvisited => {
|
|
148
|
+
walk[id.index()] = Walk::OnPath;
|
|
149
|
+
path.push(id);
|
|
150
|
+
next = self.parent(id);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
for id in path.drain(..) {
|
|
155
|
+
walk[id.index()] = Walk::ReachesRoot;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
Ok(())
|
|
159
|
+
}
|
|
160
|
+
}
|