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,921 @@
|
|
|
1
|
+
use super::eval::{number_to_string, string_to_number};
|
|
2
|
+
use super::*;
|
|
3
|
+
use crate::dom::{Document, NodeId, NodeKind};
|
|
4
|
+
use crate::html5::{parse_document, Options};
|
|
5
|
+
use std::collections::HashMap;
|
|
6
|
+
|
|
7
|
+
fn parse(input: &str) -> Document {
|
|
8
|
+
parse_document(input.as_bytes(), &Options::default())
|
|
9
|
+
.unwrap()
|
|
10
|
+
.0
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
fn element(document: &Document, id: &str) -> NodeId {
|
|
14
|
+
document
|
|
15
|
+
.descendants(NodeId::DOCUMENT)
|
|
16
|
+
.find(|&node| document.attribute_value(node, b"id") == Some(id.as_bytes()))
|
|
17
|
+
.unwrap()
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/// The ids, or contents, of what `expr` finds from `context`.
|
|
21
|
+
fn run(document: &Document, context: NodeId, expr: Expr) -> Vec<String> {
|
|
22
|
+
let query = Query::new(expr, Vec::new());
|
|
23
|
+
let Ok(Outcome::Value(Value::NodeSet(nodes))) = evaluate(
|
|
24
|
+
document,
|
|
25
|
+
&query,
|
|
26
|
+
context,
|
|
27
|
+
&HashMap::new(),
|
|
28
|
+
&HashMap::new(),
|
|
29
|
+
&HashMap::new(),
|
|
30
|
+
) else {
|
|
31
|
+
panic!("expected nodes");
|
|
32
|
+
};
|
|
33
|
+
describe(document, nodes)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
fn describe(document: &Document, nodes: Vec<NodeId>) -> Vec<String> {
|
|
37
|
+
nodes
|
|
38
|
+
.into_iter()
|
|
39
|
+
.map(|node| {
|
|
40
|
+
let bytes = match document.node_kind(node) {
|
|
41
|
+
NodeKind::Element(_) => document
|
|
42
|
+
.attribute_value(node, b"id")
|
|
43
|
+
.unwrap_or(b"?")
|
|
44
|
+
.to_vec(),
|
|
45
|
+
_ => document.content(node).unwrap_or_default(),
|
|
46
|
+
};
|
|
47
|
+
String::from_utf8(bytes).unwrap()
|
|
48
|
+
})
|
|
49
|
+
.collect()
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
fn step(axis: Axis, test: NodeTest, predicates: Vec<Expr>) -> Step {
|
|
53
|
+
Step {
|
|
54
|
+
axis,
|
|
55
|
+
test,
|
|
56
|
+
predicates,
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
fn path(steps: Vec<Step>) -> Expr {
|
|
61
|
+
Expr::Path(Path::relative(steps))
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
fn number(n: f64) -> Expr {
|
|
65
|
+
Expr::Number(n)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/// Whether `predicate` holds at `context`, as `self::node()[predicate]`.
|
|
69
|
+
fn holds(document: &Document, context: NodeId, predicate: Expr) -> bool {
|
|
70
|
+
let expr = path(vec![step(Axis::Self_, NodeTest::Node, vec![predicate])]);
|
|
71
|
+
!run(document, context, expr).is_empty()
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const SIBLINGS: &str =
|
|
75
|
+
"<div id=d><p id=a><b id=ab></b></p><p id=b></p><p id=c><i id=ci></i></p></div>";
|
|
76
|
+
|
|
77
|
+
#[test]
|
|
78
|
+
fn reverse_axes_count_from_the_context_node() {
|
|
79
|
+
let document = parse(SIBLINGS);
|
|
80
|
+
let c = element(&document, "c");
|
|
81
|
+
let first = |axis| path(vec![step(axis, NodeTest::Any, vec![number(1.0)])]);
|
|
82
|
+
assert_eq!(run(&document, c, first(Axis::PrecedingSibling)), ["b"]);
|
|
83
|
+
assert_eq!(run(&document, c, first(Axis::Ancestor)), ["d"]);
|
|
84
|
+
assert_eq!(run(&document, c, first(Axis::Preceding)), ["b"]);
|
|
85
|
+
// but the result is in document order
|
|
86
|
+
let all = path(vec![step(Axis::Preceding, NodeTest::Any, Vec::new())]);
|
|
87
|
+
// `?`: <head>, before <body>
|
|
88
|
+
assert_eq!(run(&document, c, all), ["?", "a", "ab", "b"]);
|
|
89
|
+
let following = path(vec![step(Axis::Following, NodeTest::Any, Vec::new())]);
|
|
90
|
+
assert_eq!(
|
|
91
|
+
run(&document, element(&document, "a"), following),
|
|
92
|
+
["b", "c", "ci"]
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
#[test]
|
|
97
|
+
fn constant_positions_stop_the_axis_early() {
|
|
98
|
+
let document = parse(SIBLINGS);
|
|
99
|
+
let d = element(&document, "d");
|
|
100
|
+
let children = |predicates| path(vec![step(Axis::Child, NodeTest::Any, predicates)]);
|
|
101
|
+
assert_eq!(run(&document, d, children(vec![number(2.0)])), ["b"]);
|
|
102
|
+
assert_eq!(run(&document, d, children(vec![number(4.0)])), [""; 0]);
|
|
103
|
+
assert_eq!(run(&document, d, children(vec![number(0.0)])), [""; 0]);
|
|
104
|
+
assert_eq!(run(&document, d, children(vec![number(1.5)])), [""; 0]);
|
|
105
|
+
// the next predicate counts what the first one kept
|
|
106
|
+
let last = Expr::compare(
|
|
107
|
+
Comparison::Equal,
|
|
108
|
+
Expr::Call(Function::Position, Vec::new()),
|
|
109
|
+
Expr::Call(Function::Last, Vec::new()),
|
|
110
|
+
);
|
|
111
|
+
assert_eq!(run(&document, d, children(vec![number(2.0), last])), ["b"]);
|
|
112
|
+
let from_c = |predicates| {
|
|
113
|
+
path(vec![step(
|
|
114
|
+
Axis::PrecedingSibling,
|
|
115
|
+
NodeTest::Any,
|
|
116
|
+
predicates,
|
|
117
|
+
)])
|
|
118
|
+
};
|
|
119
|
+
assert_eq!(
|
|
120
|
+
run(
|
|
121
|
+
&document,
|
|
122
|
+
element(&document, "c"),
|
|
123
|
+
from_c(vec![number(2.0)])
|
|
124
|
+
),
|
|
125
|
+
["a"]
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
#[test]
|
|
130
|
+
fn steps_from_several_nodes_merge_in_document_order() {
|
|
131
|
+
let document = parse(SIBLINGS);
|
|
132
|
+
let expr = path(vec![
|
|
133
|
+
step(Axis::Descendant, NodeTest::Any, Vec::new()),
|
|
134
|
+
step(Axis::Parent, NodeTest::Any, Vec::new()),
|
|
135
|
+
]);
|
|
136
|
+
assert_eq!(
|
|
137
|
+
run(&document, element(&document, "d"), expr),
|
|
138
|
+
["d", "a", "c"]
|
|
139
|
+
);
|
|
140
|
+
let union = Expr::Union(vec![
|
|
141
|
+
path(vec![step(Axis::Child, NodeTest::Any, vec![number(3.0)])]),
|
|
142
|
+
path(vec![step(Axis::Child, NodeTest::Any, vec![number(1.0)])]),
|
|
143
|
+
path(vec![step(Axis::Child, NodeTest::Any, vec![number(3.0)])]),
|
|
144
|
+
]);
|
|
145
|
+
assert_eq!(run(&document, element(&document, "d"), union), ["a", "c"]);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
#[test]
|
|
149
|
+
fn comparisons_follow_xpath_1() {
|
|
150
|
+
let document = parse("<p id=p class=' 2 '>x</p>");
|
|
151
|
+
let p = element(&document, "p");
|
|
152
|
+
let class = || {
|
|
153
|
+
path(vec![step(
|
|
154
|
+
Axis::Attribute,
|
|
155
|
+
NodeTest::Name(QName {
|
|
156
|
+
prefix: None,
|
|
157
|
+
local: "class".into(),
|
|
158
|
+
}),
|
|
159
|
+
Vec::new(),
|
|
160
|
+
)])
|
|
161
|
+
};
|
|
162
|
+
let missing = || {
|
|
163
|
+
path(vec![step(
|
|
164
|
+
Axis::Attribute,
|
|
165
|
+
NodeTest::Name(QName {
|
|
166
|
+
prefix: None,
|
|
167
|
+
local: "x".into(),
|
|
168
|
+
}),
|
|
169
|
+
Vec::new(),
|
|
170
|
+
)])
|
|
171
|
+
};
|
|
172
|
+
let literal = |s: &str| Expr::Literal(s.as_bytes().to_vec());
|
|
173
|
+
// a node set compares as its nodes' string values, or as numbers
|
|
174
|
+
assert!(holds(
|
|
175
|
+
&document,
|
|
176
|
+
p,
|
|
177
|
+
Expr::compare(Comparison::Equal, class(), literal(" 2 "))
|
|
178
|
+
));
|
|
179
|
+
assert!(holds(
|
|
180
|
+
&document,
|
|
181
|
+
p,
|
|
182
|
+
Expr::compare(Comparison::Equal, class(), number(2.0))
|
|
183
|
+
));
|
|
184
|
+
assert!(holds(
|
|
185
|
+
&document,
|
|
186
|
+
p,
|
|
187
|
+
Expr::compare(Comparison::Less, class(), number(3.0))
|
|
188
|
+
));
|
|
189
|
+
// an empty node set equals nothing and differs from nothing
|
|
190
|
+
assert!(!holds(
|
|
191
|
+
&document,
|
|
192
|
+
p,
|
|
193
|
+
Expr::compare(Comparison::Equal, missing(), literal(""))
|
|
194
|
+
));
|
|
195
|
+
assert!(!holds(
|
|
196
|
+
&document,
|
|
197
|
+
p,
|
|
198
|
+
Expr::compare(Comparison::NotEqual, missing(), literal(""))
|
|
199
|
+
));
|
|
200
|
+
// but its string value is empty
|
|
201
|
+
assert!(holds(
|
|
202
|
+
&document,
|
|
203
|
+
p,
|
|
204
|
+
Expr::Call(Function::StartsWith, vec![missing(), literal("")])
|
|
205
|
+
));
|
|
206
|
+
// against a boolean, a node set is its own boolean
|
|
207
|
+
let falsehood = Expr::Call(Function::Not, vec![number(1.0)]);
|
|
208
|
+
assert!(holds(
|
|
209
|
+
&document,
|
|
210
|
+
p,
|
|
211
|
+
Expr::compare(Comparison::Equal, missing(), falsehood)
|
|
212
|
+
));
|
|
213
|
+
assert!(holds(
|
|
214
|
+
&document,
|
|
215
|
+
p,
|
|
216
|
+
Expr::compare(Comparison::Equal, literal("1"), number(1.0))
|
|
217
|
+
));
|
|
218
|
+
let nan = Expr::arithmetic(Arithmetic::Modulo, number(1.0), number(0.0));
|
|
219
|
+
assert!(!holds(
|
|
220
|
+
&document,
|
|
221
|
+
p,
|
|
222
|
+
Expr::compare(Comparison::Equal, nan.clone(), nan)
|
|
223
|
+
));
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
#[test]
|
|
227
|
+
fn string_functions() {
|
|
228
|
+
let document = parse("<p id=p class='a\tb c'>x</p>");
|
|
229
|
+
let p = element(&document, "p");
|
|
230
|
+
let class = || {
|
|
231
|
+
path(vec![step(
|
|
232
|
+
Axis::Attribute,
|
|
233
|
+
NodeTest::Name(QName {
|
|
234
|
+
prefix: None,
|
|
235
|
+
local: "class".into(),
|
|
236
|
+
}),
|
|
237
|
+
Vec::new(),
|
|
238
|
+
)])
|
|
239
|
+
};
|
|
240
|
+
let literal = |s: &str| Expr::Literal(s.as_bytes().to_vec());
|
|
241
|
+
let css_class = |needle| Expr::Call(Function::CssClass, vec![class(), literal(needle)]);
|
|
242
|
+
assert!(holds(&document, p, css_class("b")));
|
|
243
|
+
assert!(holds(&document, p, css_class("c")));
|
|
244
|
+
assert!(holds(&document, p, css_class("")));
|
|
245
|
+
assert!(!holds(&document, p, css_class("a b")));
|
|
246
|
+
let normalized = Expr::Call(Function::NormalizeSpace, vec![class()]);
|
|
247
|
+
assert!(holds(
|
|
248
|
+
&document,
|
|
249
|
+
p,
|
|
250
|
+
Expr::compare(Comparison::Equal, normalized, literal("a b c"))
|
|
251
|
+
));
|
|
252
|
+
let concat = Expr::Call(
|
|
253
|
+
Function::Concat,
|
|
254
|
+
vec![literal("x"), number(1.0), literal("y")],
|
|
255
|
+
);
|
|
256
|
+
assert!(holds(
|
|
257
|
+
&document,
|
|
258
|
+
p,
|
|
259
|
+
Expr::compare(Comparison::Equal, concat, literal("x1y"))
|
|
260
|
+
));
|
|
261
|
+
assert!(holds(
|
|
262
|
+
&document,
|
|
263
|
+
p,
|
|
264
|
+
Expr::Call(Function::EndsWith, vec![class(), literal("c")])
|
|
265
|
+
));
|
|
266
|
+
let context = Expr::Path(Path::context_node());
|
|
267
|
+
assert!(holds(
|
|
268
|
+
&document,
|
|
269
|
+
p,
|
|
270
|
+
Expr::Call(Function::Contains, vec![context, literal("x")])
|
|
271
|
+
));
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
#[test]
|
|
275
|
+
fn numbers_convert_as_libxml2_converts_them() {
|
|
276
|
+
assert_eq!(string_to_number(b" 12 "), 12.0);
|
|
277
|
+
assert_eq!(string_to_number(b"-1.5"), -1.5);
|
|
278
|
+
assert_eq!(string_to_number(b".5"), 0.5);
|
|
279
|
+
assert_eq!(string_to_number(b"1e2"), 100.0);
|
|
280
|
+
// each as Nokogiri 1.19.4 reads it: digits accumulate as a double
|
|
281
|
+
assert_eq!(string_to_number(b"1e"), 1.0);
|
|
282
|
+
assert_eq!(string_to_number(b"1e+"), 1.0);
|
|
283
|
+
assert_eq!(string_to_number(b" -.5 "), -0.5);
|
|
284
|
+
assert_eq!(string_to_number(b"1."), 1.0);
|
|
285
|
+
assert_eq!(string_to_number(b"1e-400"), 0.0);
|
|
286
|
+
assert_eq!(
|
|
287
|
+
string_to_number(b"12345678901234567890"),
|
|
288
|
+
1.234567890123457e19
|
|
289
|
+
);
|
|
290
|
+
assert_eq!(
|
|
291
|
+
string_to_number(b"0.1234567890123456789012345"),
|
|
292
|
+
0.12345678901234569
|
|
293
|
+
);
|
|
294
|
+
for not_a_number in [
|
|
295
|
+
&b""[..],
|
|
296
|
+
b"1 2",
|
|
297
|
+
b"+1",
|
|
298
|
+
b"x",
|
|
299
|
+
b"1.2.3",
|
|
300
|
+
b"-",
|
|
301
|
+
b".",
|
|
302
|
+
b"0e999999",
|
|
303
|
+
] {
|
|
304
|
+
assert!(string_to_number(not_a_number).is_nan(), "{not_a_number:?}");
|
|
305
|
+
}
|
|
306
|
+
// what Nokogiri 1.19.4's libxml2 returns for `string(…)` of each
|
|
307
|
+
for (number, string) in [
|
|
308
|
+
(3.0, "3"),
|
|
309
|
+
(-0.5, "-0.5"),
|
|
310
|
+
(-0.0, "0"),
|
|
311
|
+
(f64::NAN, "NaN"),
|
|
312
|
+
(f64::NEG_INFINITY, "-Infinity"),
|
|
313
|
+
(1e9, "1000000000"),
|
|
314
|
+
(2147483646.0, "2147483646"),
|
|
315
|
+
(2147483647.0, "2.147483647e+09"),
|
|
316
|
+
(-2147483648.0, "-2.147483648e+09"),
|
|
317
|
+
(1e10, "1e+10"),
|
|
318
|
+
(1000000000.5, "1.0000000005e+09"),
|
|
319
|
+
(999999999.5, "999999999.5"),
|
|
320
|
+
(123456789012345678.0, "1.23456789012346e+17"),
|
|
321
|
+
(0.30000000000000004, "0.3"),
|
|
322
|
+
(1.0 / 3.0, "0.333333333333333"),
|
|
323
|
+
(100.0 / 3.0, "33.3333333333333"),
|
|
324
|
+
(123456789.12345679, "123456789.123457"),
|
|
325
|
+
(0.00001, "0.00001"),
|
|
326
|
+
(0.0000123, "0.0000123"),
|
|
327
|
+
(0.000009999, "9.999e-06"),
|
|
328
|
+
(0.000001, "1e-06"),
|
|
329
|
+
(5e-7, "5e-07"),
|
|
330
|
+
] {
|
|
331
|
+
assert_eq!(number_to_string(number), string, "{number}");
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
#[test]
|
|
336
|
+
fn descendant_steps_merge_unless_positions_matter() {
|
|
337
|
+
let mut expr = path(vec![
|
|
338
|
+
step(Axis::DescendantOrSelf, NodeTest::Node, Vec::new()),
|
|
339
|
+
step(Axis::Child, NodeTest::Any, Vec::new()),
|
|
340
|
+
step(Axis::DescendantOrSelf, NodeTest::Node, Vec::new()),
|
|
341
|
+
step(Axis::Child, NodeTest::Any, vec![number(1.0)]),
|
|
342
|
+
]);
|
|
343
|
+
expr.merge_descendant_steps(ast::Merge::UnlessPositional);
|
|
344
|
+
let Expr::Path(path) = expr else {
|
|
345
|
+
unreachable!()
|
|
346
|
+
};
|
|
347
|
+
let axes: Vec<Axis> = path.steps.iter().map(|step| step.axis).collect();
|
|
348
|
+
assert_eq!(
|
|
349
|
+
axes,
|
|
350
|
+
[Axis::Descendant, Axis::DescendantOrSelf, Axis::Child]
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/// The ids, or contents, of what the XPath string `xpath` finds.
|
|
355
|
+
fn find(document: &Document, context: NodeId, xpath: &str) -> Vec<String> {
|
|
356
|
+
let query = parse_xpath(xpath.as_bytes()).unwrap_or_else(|e| panic!("{xpath}: {e:?}"));
|
|
357
|
+
run(document, context, query.expr)
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
fn parse_xpath(xpath: &[u8]) -> Result<Query, ParseError> {
|
|
361
|
+
super::parse(xpath)
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
#[test]
|
|
365
|
+
fn xpath_strings_find_what_libxml2_finds() {
|
|
366
|
+
let document = parse(SIBLINGS);
|
|
367
|
+
let d = element(&document, "d");
|
|
368
|
+
let c = element(&document, "c");
|
|
369
|
+
for (xpath, found) in [
|
|
370
|
+
("//p", &["a", "b", "c"][..]),
|
|
371
|
+
("/html/body/div/p[2]", &["b"]),
|
|
372
|
+
("p", &["a", "b", "c"]),
|
|
373
|
+
("./p[b]", &["a"]),
|
|
374
|
+
("p[.//i]/following-sibling::*", &[]),
|
|
375
|
+
("p[@id='b']/preceding-sibling::p", &["a"]),
|
|
376
|
+
("//p[@id = \"c\"]/i", &["ci"]),
|
|
377
|
+
("..", &["?"]),
|
|
378
|
+
("// p [ 3 ] / i", &["ci"]),
|
|
379
|
+
("child :: p[2.]", &["b"]),
|
|
380
|
+
("p[--1]", &["a"]),
|
|
381
|
+
("p[20e-1]", &["b"]),
|
|
382
|
+
("p[1e]", &["a"]),
|
|
383
|
+
("p[1.5]", &[]),
|
|
384
|
+
("descendant::*[@id][1]", &["a"]),
|
|
385
|
+
("*:p[last]", &[]),
|
|
386
|
+
("p[3]/descendant-or-self::node()", &["c", "ci"]),
|
|
387
|
+
("/ /html/body/div/p[1]", &["a"]),
|
|
388
|
+
("/ //i", &["ci"]),
|
|
389
|
+
] {
|
|
390
|
+
assert_eq!(find(&document, d, xpath), found, "{xpath}");
|
|
391
|
+
}
|
|
392
|
+
assert_eq!(find(&document, c, "preceding::*[1]"), ["b"]);
|
|
393
|
+
// libxml2 reads an overlong form in a name as what it encodes
|
|
394
|
+
let overlong_p = parse_xpath(b"\xC1\xB0[1]").unwrap();
|
|
395
|
+
assert_eq!(run(&document, d, overlong_p.expr), ["a"]);
|
|
396
|
+
assert_eq!(find(&document, c, "ancestor::*[1]"), ["d"]);
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
#[test]
|
|
400
|
+
fn doctypes_pass_no_node_test() {
|
|
401
|
+
let document = parse("<!DOCTYPE html><p id=p>");
|
|
402
|
+
// <html>
|
|
403
|
+
assert_eq!(find(&document, NodeId::DOCUMENT, "/node()"), ["?"]);
|
|
404
|
+
// <head>
|
|
405
|
+
let p = element(&document, "p");
|
|
406
|
+
assert_eq!(find(&document, p, "preceding::node()"), ["?"]);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
#[test]
|
|
410
|
+
fn following_an_attribute_starts_after_its_element() {
|
|
411
|
+
let document = parse("<p id=a class=x><b id=b></b></p><p id=c></p>");
|
|
412
|
+
let a = element(&document, "a");
|
|
413
|
+
assert_eq!(find(&document, a, "@class/following::*"), ["c"]);
|
|
414
|
+
// <head>
|
|
415
|
+
assert_eq!(find(&document, a, "@class/preceding::*"), ["?"]);
|
|
416
|
+
// Nokogiri's `*:name` matches elements only
|
|
417
|
+
assert_eq!(find(&document, a, "@*:id"), [""; 0]);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
#[test]
|
|
421
|
+
fn names_are_xml_fourth_edition_names() {
|
|
422
|
+
// Fifth-edition names allow U+FFFD and U+2070; libxml2's XPath doesn't
|
|
423
|
+
for (xpath, error) in [
|
|
424
|
+
("//a\u{FFFD}", Error::InvalidExpression),
|
|
425
|
+
("//p[@a\u{FFFD}]", Error::InvalidPredicate),
|
|
426
|
+
("//\u{2070}", Error::InvalidExpression),
|
|
427
|
+
] {
|
|
428
|
+
let result = parse_xpath(xpath.as_bytes()).map(|_| ());
|
|
429
|
+
assert_eq!(result, Err(ParseError::Syntax(error)), "{xpath:?}");
|
|
430
|
+
}
|
|
431
|
+
// a Thai letter, an extender, an ideograph with an Arabic-Indic digit,
|
|
432
|
+
// a combining character
|
|
433
|
+
for xpath in ["//\u{E01}", "//a\u{B7}", "//\u{4E00}\u{660}", "//a\u{300}"] {
|
|
434
|
+
assert!(parse_xpath(xpath.as_bytes()).is_ok(), "{xpath:?}");
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
#[test]
|
|
439
|
+
fn syntax_errors_carry_libxml2_codes() {
|
|
440
|
+
// each as Nokogiri 1.19.4 reports it
|
|
441
|
+
for (xpath, error) in [
|
|
442
|
+
(&b""[..], Error::InvalidExpression),
|
|
443
|
+
(b" ", Error::InvalidExpression),
|
|
444
|
+
(b"..faulty_xpath", Error::InvalidExpression),
|
|
445
|
+
(b"//", Error::InvalidExpression),
|
|
446
|
+
(b"//p/", Error::InvalidExpression),
|
|
447
|
+
(b"//p[", Error::InvalidExpression),
|
|
448
|
+
(b"//p[]", Error::InvalidExpression),
|
|
449
|
+
(b"//p]", Error::InvalidExpression),
|
|
450
|
+
(b"//p@id", Error::InvalidExpression),
|
|
451
|
+
(b"//p/.[1]", Error::InvalidExpression),
|
|
452
|
+
(b"child::", Error::InvalidExpression),
|
|
453
|
+
(b"nosuch-axis::p", Error::InvalidExpression),
|
|
454
|
+
(b"//svg: svg", Error::InvalidExpression),
|
|
455
|
+
(b"//* :p", Error::InvalidExpression),
|
|
456
|
+
(b"//p[string(]", Error::InvalidExpression),
|
|
457
|
+
(b"(//p", Error::InvalidExpression),
|
|
458
|
+
(b"//p[@id='a'", Error::InvalidPredicate),
|
|
459
|
+
(b"//p[1 e1]", Error::InvalidPredicate),
|
|
460
|
+
(b"//p[@id ! = 'a']", Error::InvalidPredicate),
|
|
461
|
+
(b"//p[@id='a", Error::UnfinishedLiteral),
|
|
462
|
+
(b"text(", Error::Unclosed),
|
|
463
|
+
(b"//p[processing-instruction(]", Error::StartLiteral),
|
|
464
|
+
(b"//p[$]", Error::VariableReference),
|
|
465
|
+
(b"//p[$ v]", Error::VariableReference),
|
|
466
|
+
(b"//p[$a:]", Error::VariableReference),
|
|
467
|
+
(b"//\xFF", Error::Encoding),
|
|
468
|
+
(b"//\xC3", Error::Encoding),
|
|
469
|
+
(b"//p[@id='\xFF']", Error::InvalidChar),
|
|
470
|
+
(b"//p[@id='\x01']", Error::InvalidChar),
|
|
471
|
+
// checked before the missing quote
|
|
472
|
+
(b"//p['\x01", Error::InvalidChar),
|
|
473
|
+
(b"//p[\"\xFF", Error::InvalidChar),
|
|
474
|
+
(b"//p[\"a\xC3", Error::InvalidChar),
|
|
475
|
+
(b"//p['\x82\x80']", Error::InvalidChar),
|
|
476
|
+
// libxml2 decodes overlong forms, surrogates and code points past
|
|
477
|
+
// U+10FFFF in names, then finds them out of range
|
|
478
|
+
(b"//\xC0\x80", Error::InvalidChar),
|
|
479
|
+
(b"//\xED\xA0\x80", Error::InvalidChar),
|
|
480
|
+
(b"//p\xF4\x90\x80\x80", Error::InvalidChar),
|
|
481
|
+
(b"/\xF4\x90\x80\x80", Error::InvalidChar),
|
|
482
|
+
(b"//\xEF\xBF\xBE", Error::InvalidChar),
|
|
483
|
+
] {
|
|
484
|
+
let result = parse_xpath(xpath).map(|_| ());
|
|
485
|
+
assert_eq!(result, Err(ParseError::Syntax(error)), "{xpath:?}");
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
#[test]
|
|
490
|
+
fn only_the_namespace_axis_is_left_out() {
|
|
491
|
+
assert_eq!(
|
|
492
|
+
parse_xpath(b"//p/namespace::*").map(|_| ()),
|
|
493
|
+
Err(ParseError::Unsupported("the namespace axis".into()))
|
|
494
|
+
);
|
|
495
|
+
// libxml2 rejects it anyway
|
|
496
|
+
assert_eq!(
|
|
497
|
+
parse_xpath(b"string(//p").map(|_| ()),
|
|
498
|
+
Err(ParseError::Syntax(Error::InvalidExpression))
|
|
499
|
+
);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/// What an XPath string evaluates to, as Nokogiri would return it.
|
|
503
|
+
#[derive(Debug, PartialEq)]
|
|
504
|
+
enum Found {
|
|
505
|
+
Nodes(Vec<String>),
|
|
506
|
+
Boolean(bool),
|
|
507
|
+
Number(f64),
|
|
508
|
+
String(String),
|
|
509
|
+
Calls(Vec<String>),
|
|
510
|
+
Error(Error),
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
fn value(document: &Document, context: NodeId, xpath: &str) -> Found {
|
|
514
|
+
evaluate_with(document, context, xpath, &HashMap::new())
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
fn evaluate_with(
|
|
518
|
+
document: &Document,
|
|
519
|
+
context: NodeId,
|
|
520
|
+
xpath: &str,
|
|
521
|
+
variables: &HashMap<String, Vec<u8>>,
|
|
522
|
+
) -> Found {
|
|
523
|
+
let query = parse_xpath(xpath.as_bytes()).unwrap_or_else(|e| panic!("{xpath}: {e:?}"));
|
|
524
|
+
match evaluate(
|
|
525
|
+
document,
|
|
526
|
+
&query,
|
|
527
|
+
context,
|
|
528
|
+
&HashMap::new(),
|
|
529
|
+
variables,
|
|
530
|
+
&HashMap::new(),
|
|
531
|
+
) {
|
|
532
|
+
Ok(Outcome::Value(Value::NodeSet(nodes))) => Found::Nodes(describe(document, nodes)),
|
|
533
|
+
Ok(Outcome::Value(Value::Boolean(b))) => Found::Boolean(b),
|
|
534
|
+
Ok(Outcome::Value(Value::Number(n))) => Found::Number(n),
|
|
535
|
+
Ok(Outcome::Value(Value::String(s))) => {
|
|
536
|
+
Found::String(String::from_utf8(s.into_owned()).unwrap())
|
|
537
|
+
}
|
|
538
|
+
Ok(Outcome::Calls(calls)) => Found::Calls(
|
|
539
|
+
calls
|
|
540
|
+
.iter()
|
|
541
|
+
.map(|call| query.function(call.site).local.clone())
|
|
542
|
+
.collect(),
|
|
543
|
+
),
|
|
544
|
+
Err(error) => Found::Error(error),
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
fn nodes(ids: &[&str]) -> Found {
|
|
549
|
+
Found::Nodes(ids.iter().map(|id| id.to_string()).collect())
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
fn string(s: &str) -> Found {
|
|
553
|
+
Found::String(s.into())
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/// Each as Nokogiri 1.19.4 evaluates it.
|
|
557
|
+
#[test]
|
|
558
|
+
fn values_are_libxml2s() {
|
|
559
|
+
use Found::{Boolean, Error as E, Number};
|
|
560
|
+
let document = parse(
|
|
561
|
+
"<html lang=en><body><p id=a class='x y'>One <b>two</b></p><p id=b>3</p>\
|
|
562
|
+
<svg xml:lang=en-US><g id=g><a name=m></a></g></svg><math><mi xlink:href=u>x</mi></math>",
|
|
563
|
+
);
|
|
564
|
+
let a = element(&document, "a");
|
|
565
|
+
for (xpath, found) in [
|
|
566
|
+
("count(//p)", Number(2.0)),
|
|
567
|
+
("sum(//p)", Number(f64::NAN)),
|
|
568
|
+
("sum(//p[2])", Number(3.0)),
|
|
569
|
+
("sum(//nosuch)", Number(0.0)),
|
|
570
|
+
("string()", string("One two")),
|
|
571
|
+
("string(//p)", string("One two")),
|
|
572
|
+
("string(1e30)", string("1e+30")),
|
|
573
|
+
("string(-0)", string("0")),
|
|
574
|
+
("string(0.1 + 0.2)", string("0.3")),
|
|
575
|
+
("string(1 div 0)", string("Infinity")),
|
|
576
|
+
("number('12')", Number(12.0)),
|
|
577
|
+
("number()", Number(f64::NAN)),
|
|
578
|
+
("boolean('')", Boolean(false)),
|
|
579
|
+
("boolean(//p)", Boolean(true)),
|
|
580
|
+
("local-name()", string("p")),
|
|
581
|
+
("name()", string("p")),
|
|
582
|
+
("name(//*[local-name() = 'svg'])", string("svg:svg")),
|
|
583
|
+
(
|
|
584
|
+
"namespace-uri(//*[local-name() = 'svg'])",
|
|
585
|
+
string("http://www.w3.org/2000/svg"),
|
|
586
|
+
),
|
|
587
|
+
("name(//*[local-name() = 'mi']/@*)", string("xlink:href")),
|
|
588
|
+
("local-name(//*[local-name() = 'mi']/@*)", string("href")),
|
|
589
|
+
("name(/)", string("")),
|
|
590
|
+
("name(//text())", string("")),
|
|
591
|
+
("substring('12345', 2, 3)", string("234")),
|
|
592
|
+
("substring('12345', 1.5, 2.6)", string("234")),
|
|
593
|
+
("substring('12345', 0, 3)", string("12")),
|
|
594
|
+
("substring('12345', 0 div 0, 3)", string("")),
|
|
595
|
+
("substring('12345', 1, 0 div 0)", string("")),
|
|
596
|
+
("substring('12345', -42, 1 div 0)", string("12345")),
|
|
597
|
+
("substring('12345', -1 div 0, 1 div 0)", string("")),
|
|
598
|
+
("substring('ébc', 2)", string("bc")),
|
|
599
|
+
("substring-before('a/b/c', '/')", string("a")),
|
|
600
|
+
("substring-after('a/b/c', '/')", string("b/c")),
|
|
601
|
+
("substring-after('abc', '')", string("abc")),
|
|
602
|
+
("translate('bar', 'abc', 'ABC')", string("BAr")),
|
|
603
|
+
("translate('--aaa--', 'abc-', 'ABC')", string("AAA")),
|
|
604
|
+
("translate('éa', 'é', 'E')", string("Ea")),
|
|
605
|
+
("string-length('héllo')", Number(5.0)),
|
|
606
|
+
("string-length()", Number(7.0)),
|
|
607
|
+
("normalize-space(' a b ')", string("a b")),
|
|
608
|
+
("concat('a', 1, true())", string("a1true")),
|
|
609
|
+
("round(2.5)", Number(3.0)),
|
|
610
|
+
("round(-2.5)", Number(-2.0)),
|
|
611
|
+
("floor(-1.5)", Number(-2.0)),
|
|
612
|
+
("1 + 2 * 3 - 4 div 8", Number(6.5)),
|
|
613
|
+
("-5 mod 2", Number(-1.0)),
|
|
614
|
+
("5.5 mod 2", Number(1.5)),
|
|
615
|
+
("1 div -0", Number(f64::NEG_INFINITY)),
|
|
616
|
+
("-(1)", Number(-1.0)),
|
|
617
|
+
("--'3'", Number(3.0)),
|
|
618
|
+
("- - 'x'", Number(f64::NAN)),
|
|
619
|
+
("-//p", Number(-f64::NAN)),
|
|
620
|
+
("2 div2", Number(1.0)),
|
|
621
|
+
("1 < 2 < 3", Boolean(true)),
|
|
622
|
+
("3 > 2 > 1", Boolean(false)),
|
|
623
|
+
("1 = 1 != 0", Boolean(true)),
|
|
624
|
+
("'a' < 'b'", Boolean(false)),
|
|
625
|
+
("0 div 0 = 0 div 0", Boolean(false)),
|
|
626
|
+
("true() > false()", Boolean(true)),
|
|
627
|
+
("//p = 3", Boolean(true)),
|
|
628
|
+
("//nosuch = false()", Boolean(true)),
|
|
629
|
+
("//nosuch != //p", Boolean(false)),
|
|
630
|
+
("false() and foo()", Boolean(false)),
|
|
631
|
+
("true() or foo()", Boolean(true)),
|
|
632
|
+
("'x'/.", string("x")),
|
|
633
|
+
("1/.", Number(1.0)),
|
|
634
|
+
("(//p)[2]", nodes(&["b"])),
|
|
635
|
+
("(//p)[last()]/@id", nodes(&["b"])),
|
|
636
|
+
("(//b/ancestor::*)[1]", nodes(&["?"])),
|
|
637
|
+
("//b/ancestor::*[1]", nodes(&["a"])),
|
|
638
|
+
("//p | //b", nodes(&["a", "?", "b"])),
|
|
639
|
+
("//p[position() > 1]", nodes(&["b"])),
|
|
640
|
+
("//p[last() - 1]", nodes(&["a"])),
|
|
641
|
+
("//p[-(-2)]", nodes(&["b"])),
|
|
642
|
+
("//p['x']", nodes(&["a", "b"])),
|
|
643
|
+
("//p['']", nodes(&[])),
|
|
644
|
+
("//nosuch[foo()]", nodes(&[])),
|
|
645
|
+
("id('a b')", nodes(&["a", "b"])),
|
|
646
|
+
("id(//p/@id)", nodes(&["a", "b"])),
|
|
647
|
+
("id('m')", nodes(&["?"])),
|
|
648
|
+
("//*[lang('en')]", nodes(&["?", "g", "?"])),
|
|
649
|
+
("//*[lang('EN-us')]", nodes(&["?", "g", "?"])),
|
|
650
|
+
("//*[lang('en-')]", nodes(&[])),
|
|
651
|
+
("//p[lang('en')]", nodes(&[])),
|
|
652
|
+
(
|
|
653
|
+
"//p[nokogiri-builtin:local-name-is('p')]",
|
|
654
|
+
nodes(&["a", "b"]),
|
|
655
|
+
),
|
|
656
|
+
("nokogiri-builtin:css-class('a b', 'b')", Boolean(true)),
|
|
657
|
+
("count(//p/self::processing-instruction())", Number(0.0)),
|
|
658
|
+
("count('x')", E(Error::InvalidType)),
|
|
659
|
+
("sum('1')", E(Error::InvalidType)),
|
|
660
|
+
("name(1)", E(Error::InvalidType)),
|
|
661
|
+
("'x'[1]", E(Error::InvalidType)),
|
|
662
|
+
("'x'//.", E(Error::InvalidType)),
|
|
663
|
+
("1 | //p", E(Error::InvalidType)),
|
|
664
|
+
("count()", E(Error::InvalidArity)),
|
|
665
|
+
("true(1)", E(Error::InvalidArity)),
|
|
666
|
+
("concat('a')", E(Error::InvalidArity)),
|
|
667
|
+
("substring('a')", E(Error::InvalidArity)),
|
|
668
|
+
("nokogiri-builtin:css-class('a')", E(Error::InvalidArity)),
|
|
669
|
+
("$x", E(Error::UndefinedVariable)),
|
|
670
|
+
("$nokogiri:x", E(Error::UndefinedVariable)),
|
|
671
|
+
("$bad:x", E(Error::UndefinedNamespacePrefix)),
|
|
672
|
+
("bar:foo()", E(Error::UndefinedNamespacePrefix)),
|
|
673
|
+
("foo()", Found::Calls(vec!["foo".into()])),
|
|
674
|
+
// the argument's error comes first
|
|
675
|
+
("count(foo(), 'x')", Found::Calls(vec!["foo".into()])),
|
|
676
|
+
] {
|
|
677
|
+
let actual = value(&document, a, xpath);
|
|
678
|
+
let same = match (&actual, &found) {
|
|
679
|
+
(Number(x), Number(y)) => x.to_bits() == y.to_bits() || (x.is_nan() && y.is_nan()),
|
|
680
|
+
_ => actual == found,
|
|
681
|
+
};
|
|
682
|
+
assert!(same, "{xpath}: {actual:?}, expected {found:?}");
|
|
683
|
+
}
|
|
684
|
+
// negative zero survives
|
|
685
|
+
assert_eq!(value(&document, a, "round(-0.4)"), Number(-0.0));
|
|
686
|
+
assert!(
|
|
687
|
+
matches!(value(&document, a, "ceiling(-0.5)"), Number(n) if n == 0.0 && n.is_sign_negative())
|
|
688
|
+
);
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
#[test]
|
|
692
|
+
fn processing_instructions() {
|
|
693
|
+
let mut document = parse("<p id=p>");
|
|
694
|
+
let p = element(&document, "p");
|
|
695
|
+
let pi = document.create_processing_instruction(b"tgt".to_vec(), b"data".to_vec());
|
|
696
|
+
document.append_child(p, pi).unwrap();
|
|
697
|
+
let found = |xpath| value(&document, NodeId::DOCUMENT, xpath);
|
|
698
|
+
assert_eq!(found("//processing-instruction()"), nodes(&["data"]));
|
|
699
|
+
assert_eq!(found("//processing-instruction('tgt')"), nodes(&["data"]));
|
|
700
|
+
assert_eq!(found("//processing-instruction('x')"), nodes(&[]));
|
|
701
|
+
assert_eq!(found("name(//processing-instruction())"), string("tgt"));
|
|
702
|
+
assert_eq!(
|
|
703
|
+
found("local-name(//processing-instruction())"),
|
|
704
|
+
string("tgt")
|
|
705
|
+
);
|
|
706
|
+
assert_eq!(found("count(//p/node())"), Found::Number(1.0));
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
#[test]
|
|
710
|
+
fn variables_are_strings() {
|
|
711
|
+
let document = parse("<p id=a>1</p><p id=b>2</p>");
|
|
712
|
+
let variables = HashMap::from([("x".to_string(), b"2".to_vec())]);
|
|
713
|
+
let found = |xpath| evaluate_with(&document, NodeId::DOCUMENT, xpath, &variables);
|
|
714
|
+
assert_eq!(found("$x"), string("2"));
|
|
715
|
+
assert_eq!(found("$x + 1"), Found::Number(3.0));
|
|
716
|
+
assert_eq!(found("//p[. = $x]"), nodes(&["b"]));
|
|
717
|
+
// a string, so not a position
|
|
718
|
+
assert_eq!(found("//p[$x]"), nodes(&["a", "b"]));
|
|
719
|
+
assert_eq!(found("$x[1]"), Found::Error(Error::InvalidType));
|
|
720
|
+
assert_eq!(found("$y"), Found::Error(Error::UndefinedVariable));
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
#[test]
|
|
724
|
+
fn ids_are_the_first_of_each() {
|
|
725
|
+
let document = parse("<a name=n id=z></a><p id=a>1</p><p id=a>2</p><i id='x y'></i>");
|
|
726
|
+
let found = |xpath| value(&document, NodeId::DOCUMENT, xpath);
|
|
727
|
+
assert_eq!(found("id('n')"), nodes(&["z"]));
|
|
728
|
+
assert_eq!(found("count(id('a'))"), Found::Number(1.0));
|
|
729
|
+
assert_eq!(found("string(id('a'))"), string("1"));
|
|
730
|
+
// tokens split at blanks
|
|
731
|
+
assert_eq!(found("id('x y')"), nodes(&[]));
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
#[test]
|
|
735
|
+
fn custom_calls_from_xpath_strings() {
|
|
736
|
+
let document = parse("<p id=a>1</p><p id=b>2</p>");
|
|
737
|
+
let query = parse_xpath(b"//p[nokogiri:keep(., 'x')]/@id | //p[mine()]").unwrap();
|
|
738
|
+
assert_eq!(
|
|
739
|
+
query.function(0),
|
|
740
|
+
&FunctionName {
|
|
741
|
+
prefix: Some("nokogiri".into()),
|
|
742
|
+
local: "keep".into()
|
|
743
|
+
}
|
|
744
|
+
);
|
|
745
|
+
assert_eq!(query.function(1).prefix, None);
|
|
746
|
+
let none = HashMap::new();
|
|
747
|
+
let Ok(Outcome::Calls(calls)) = evaluate(
|
|
748
|
+
&document,
|
|
749
|
+
&query,
|
|
750
|
+
NodeId::DOCUMENT,
|
|
751
|
+
&none,
|
|
752
|
+
&none_variables(),
|
|
753
|
+
&HashMap::new(),
|
|
754
|
+
) else {
|
|
755
|
+
panic!("calls expected");
|
|
756
|
+
};
|
|
757
|
+
assert_eq!(calls.len(), 4);
|
|
758
|
+
assert_eq!(calls[0].arguments[1], Value::String(b"x"[..].into()));
|
|
759
|
+
let answers = calls
|
|
760
|
+
.into_iter()
|
|
761
|
+
.map(|call| {
|
|
762
|
+
let answer = Ok(Value::Boolean(call.site == 0));
|
|
763
|
+
(call, answer)
|
|
764
|
+
})
|
|
765
|
+
.collect();
|
|
766
|
+
let Ok(Outcome::Value(Value::NodeSet(found))) = evaluate(
|
|
767
|
+
&document,
|
|
768
|
+
&query,
|
|
769
|
+
NodeId::DOCUMENT,
|
|
770
|
+
&none,
|
|
771
|
+
&none_variables(),
|
|
772
|
+
&answers,
|
|
773
|
+
) else {
|
|
774
|
+
panic!("nodes expected");
|
|
775
|
+
};
|
|
776
|
+
assert_eq!(describe(&document, found), ["a", "b"]);
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
/// The empty node set standing in for an answer can reach calls libxml2
|
|
780
|
+
/// never makes; their errors count only once every call is answered.
|
|
781
|
+
#[test]
|
|
782
|
+
fn errors_answer_calls_only_when_reached() {
|
|
783
|
+
let document = parse("<p id=a>");
|
|
784
|
+
let query = parse_xpath(b"nokogiri:yes() or nokogiri:missing()").unwrap();
|
|
785
|
+
let none = HashMap::new();
|
|
786
|
+
let mut answers = HashMap::new();
|
|
787
|
+
let run = |answers: &HashMap<_, _>| {
|
|
788
|
+
evaluate(
|
|
789
|
+
&document,
|
|
790
|
+
&query,
|
|
791
|
+
NodeId::DOCUMENT,
|
|
792
|
+
&none,
|
|
793
|
+
&none_variables(),
|
|
794
|
+
answers,
|
|
795
|
+
)
|
|
796
|
+
};
|
|
797
|
+
let Ok(Outcome::Calls(calls)) = run(&answers) else {
|
|
798
|
+
panic!("calls expected");
|
|
799
|
+
};
|
|
800
|
+
assert_eq!(calls.len(), 2);
|
|
801
|
+
answers.insert(calls[0].clone(), Ok(Value::Boolean(true)));
|
|
802
|
+
answers.insert(calls[1].clone(), Err(Error::UnregisteredFunction));
|
|
803
|
+
assert_eq!(run(&answers), Ok(Outcome::Value(Value::Boolean(true))));
|
|
804
|
+
answers.insert(calls[0].clone(), Ok(Value::Boolean(false)));
|
|
805
|
+
assert_eq!(run(&answers), Err(Error::UnregisteredFunction));
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
/// A node can reach a call site with different arguments when it is a
|
|
809
|
+
/// candidate from more than one starting node.
|
|
810
|
+
#[test]
|
|
811
|
+
fn answers_are_per_arguments() {
|
|
812
|
+
let document = parse("<div><p><a id=a>1</a><span><a id=b>2</a></span></p></div>");
|
|
813
|
+
let query = parse_xpath(b"//*/descendant::a[nokogiri:f(position())]").unwrap();
|
|
814
|
+
let none = HashMap::new();
|
|
815
|
+
let mut answers = HashMap::new();
|
|
816
|
+
let found = loop {
|
|
817
|
+
match evaluate(
|
|
818
|
+
&document,
|
|
819
|
+
&query,
|
|
820
|
+
NodeId::DOCUMENT,
|
|
821
|
+
&none,
|
|
822
|
+
&none_variables(),
|
|
823
|
+
&answers,
|
|
824
|
+
) {
|
|
825
|
+
Ok(Outcome::Calls(calls)) => {
|
|
826
|
+
for call in calls {
|
|
827
|
+
let answer = Ok(Value::Boolean(call.arguments == [Value::Number(1.0)]));
|
|
828
|
+
answers.insert(call, answer);
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
Ok(Outcome::Value(Value::NodeSet(found))) => break found,
|
|
832
|
+
other => panic!("nodes expected, not {other:?}"),
|
|
833
|
+
}
|
|
834
|
+
};
|
|
835
|
+
assert_eq!(describe(&document, found), ["a", "b"]);
|
|
836
|
+
assert_eq!(answers.len(), 3);
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
#[test]
|
|
840
|
+
fn numbers_find_their_answers_by_bits() {
|
|
841
|
+
let document = parse("<p id=a>");
|
|
842
|
+
let query = parse_xpath(b"nokogiri:f(0 div 0)").unwrap();
|
|
843
|
+
let none = HashMap::new();
|
|
844
|
+
let run = |answers: &HashMap<_, _>| {
|
|
845
|
+
evaluate(
|
|
846
|
+
&document,
|
|
847
|
+
&query,
|
|
848
|
+
NodeId::DOCUMENT,
|
|
849
|
+
&none,
|
|
850
|
+
&none_variables(),
|
|
851
|
+
answers,
|
|
852
|
+
)
|
|
853
|
+
};
|
|
854
|
+
let Ok(Outcome::Calls(calls)) = run(&HashMap::new()) else {
|
|
855
|
+
panic!("calls expected");
|
|
856
|
+
};
|
|
857
|
+
let answers = HashMap::from([(calls[0].clone(), Ok(Value::Boolean(true)))]);
|
|
858
|
+
assert_eq!(run(&answers), Ok(Outcome::Value(Value::Boolean(true))));
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
fn none_variables() -> HashMap<String, Vec<u8>> {
|
|
862
|
+
HashMap::new()
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/// Operators of one precedence make a list, so a long chain of them costs
|
|
866
|
+
/// no stack to evaluate or drop.
|
|
867
|
+
#[test]
|
|
868
|
+
fn long_operator_chains_stay_flat() {
|
|
869
|
+
let length = if cfg!(miri) { 1_000 } else { 100_000 };
|
|
870
|
+
let document = parse("<p>");
|
|
871
|
+
let sum = format!("1{}", " + 1".repeat(length));
|
|
872
|
+
assert_eq!(
|
|
873
|
+
value(&document, NodeId::DOCUMENT, &sum),
|
|
874
|
+
Found::Number((length + 1) as f64)
|
|
875
|
+
);
|
|
876
|
+
let signs = format!("{}1", "-".repeat(length + 1));
|
|
877
|
+
assert_eq!(
|
|
878
|
+
value(&document, NodeId::DOCUMENT, &signs),
|
|
879
|
+
Found::Number(-1.0)
|
|
880
|
+
);
|
|
881
|
+
let comparisons = format!("1{}", " = 1".repeat(length));
|
|
882
|
+
assert_eq!(
|
|
883
|
+
value(&document, NodeId::DOCUMENT, &comparisons),
|
|
884
|
+
Found::Boolean(true)
|
|
885
|
+
);
|
|
886
|
+
let union = format!("//p{}", " | //p".repeat(length / 10));
|
|
887
|
+
assert_eq!(value(&document, NodeId::DOCUMENT, &union), nodes(&["?"]));
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
#[test]
|
|
891
|
+
fn predicates_nest_32_deep() {
|
|
892
|
+
let nested = |depth| format!("{}p{}", "p[".repeat(depth), "]".repeat(depth));
|
|
893
|
+
assert!(parse_xpath(nested(MAX_NESTING).as_bytes()).is_ok());
|
|
894
|
+
assert_eq!(
|
|
895
|
+
parse_xpath(nested(MAX_NESTING + 1).as_bytes()).map(|_| ()),
|
|
896
|
+
Err(ParseError::Unsupported("nesting deeper than 32".into()))
|
|
897
|
+
);
|
|
898
|
+
// a syntax error past the limit still wins, as in libxml2
|
|
899
|
+
let deep = "p[".repeat(MAX_NESTING + 1);
|
|
900
|
+
for (xpath, error) in [
|
|
901
|
+
(format!("{deep}x"), Error::InvalidPredicate),
|
|
902
|
+
(format!("{deep}x)"), Error::InvalidPredicate),
|
|
903
|
+
(format!("{deep}x(]"), Error::InvalidExpression),
|
|
904
|
+
(format!("{deep}'x"), Error::UnfinishedLiteral),
|
|
905
|
+
(
|
|
906
|
+
format!("{}]", nested(MAX_NESTING + 1)),
|
|
907
|
+
Error::InvalidExpression,
|
|
908
|
+
),
|
|
909
|
+
] {
|
|
910
|
+
assert_eq!(
|
|
911
|
+
parse_xpath(xpath.as_bytes()).map(|_| ()),
|
|
912
|
+
Err(ParseError::Syntax(error)),
|
|
913
|
+
"{xpath}"
|
|
914
|
+
);
|
|
915
|
+
}
|
|
916
|
+
let quoted = format!("{deep}'])'{}", "]".repeat(MAX_NESTING + 1));
|
|
917
|
+
assert_eq!(
|
|
918
|
+
parse_xpath(quoted.as_bytes()).map(|_| ()),
|
|
919
|
+
Err(ParseError::Unsupported("nesting deeper than 32".into()))
|
|
920
|
+
);
|
|
921
|
+
}
|