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,476 @@
|
|
|
1
|
+
use super::*;
|
|
2
|
+
use crate::dom::{Document, NodeId, NodeKind};
|
|
3
|
+
use crate::html5::{parse_document, Options as ParseOptions};
|
|
4
|
+
use crate::xpath::{evaluate, Outcome, Value};
|
|
5
|
+
use std::collections::HashMap;
|
|
6
|
+
|
|
7
|
+
fn parse(input: &str) -> Document {
|
|
8
|
+
parse_document(input.as_bytes(), &ParseOptions::default())
|
|
9
|
+
.unwrap()
|
|
10
|
+
.0
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
fn options(prefixes: &[Prefix]) -> Options {
|
|
14
|
+
Options {
|
|
15
|
+
html: true,
|
|
16
|
+
builtins: true,
|
|
17
|
+
default_namespace: false,
|
|
18
|
+
prefixes: prefixes.to_vec(),
|
|
19
|
+
first_only: false,
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/// Each match as its `id`, or its name if it has none, as `Document#css`
|
|
24
|
+
/// would find it.
|
|
25
|
+
fn select(document: &Document, rule: &str) -> Vec<String> {
|
|
26
|
+
select_from(
|
|
27
|
+
document,
|
|
28
|
+
NodeId::DOCUMENT,
|
|
29
|
+
rule,
|
|
30
|
+
&options(&[Prefix::Global]),
|
|
31
|
+
)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
fn select_from(document: &Document, context: NodeId, rule: &str, options: &Options) -> Vec<String> {
|
|
35
|
+
let selector = compile(rule, options).unwrap();
|
|
36
|
+
let query = selector.query.unwrap();
|
|
37
|
+
let namespaces = HashMap::new();
|
|
38
|
+
let Outcome::Value(Value::NodeSet(nodes)) = evaluate(
|
|
39
|
+
document,
|
|
40
|
+
&query,
|
|
41
|
+
context,
|
|
42
|
+
&namespaces,
|
|
43
|
+
&HashMap::new(),
|
|
44
|
+
&HashMap::new(),
|
|
45
|
+
)
|
|
46
|
+
.unwrap() else {
|
|
47
|
+
panic!("no custom calls expected");
|
|
48
|
+
};
|
|
49
|
+
nodes.into_iter().map(|id| describe(document, id)).collect()
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
fn describe(document: &Document, id: NodeId) -> String {
|
|
53
|
+
match document.node_kind(id) {
|
|
54
|
+
NodeKind::Element(_) => document
|
|
55
|
+
.attribute_value(id, b"id")
|
|
56
|
+
.map(|id| String::from_utf8(id.to_vec()).unwrap())
|
|
57
|
+
.unwrap_or_else(|| {
|
|
58
|
+
String::from_utf8(document.node_name(id).unwrap().to_vec()).unwrap()
|
|
59
|
+
}),
|
|
60
|
+
_ => String::from_utf8(document.content(id).unwrap_or_default()).unwrap(),
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
fn error(rule: &str) -> String {
|
|
65
|
+
compile(rule, &options(&[Prefix::Global])).unwrap_err().0
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
fn invalid(rule: &str) -> bool {
|
|
69
|
+
compile(rule, &options(&[Prefix::Global]))
|
|
70
|
+
.unwrap()
|
|
71
|
+
.query
|
|
72
|
+
.is_err()
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const LIST: &str = "<div id=d><p id=a class='x y'>1</p><p id=b>2<b id=bold>b</b></p>\
|
|
76
|
+
<span id=s>s</span><p id=c class=x>3</p></div>";
|
|
77
|
+
|
|
78
|
+
#[test]
|
|
79
|
+
fn simple_selectors() {
|
|
80
|
+
let document = parse(LIST);
|
|
81
|
+
assert_eq!(select(&document, "p"), ["a", "b", "c"]);
|
|
82
|
+
assert_eq!(select(&document, ".x"), ["a", "c"]);
|
|
83
|
+
assert_eq!(select(&document, "#b"), ["b"]);
|
|
84
|
+
assert_eq!(select(&document, "p.x.y"), ["a"]);
|
|
85
|
+
assert_eq!(select(&document, "div > span"), ["s"]);
|
|
86
|
+
assert_eq!(select(&document, "div b"), ["bold"]);
|
|
87
|
+
assert_eq!(select(&document, "p + span"), ["s"]);
|
|
88
|
+
assert_eq!(select(&document, "#a ~ p"), ["b", "c"]);
|
|
89
|
+
assert_eq!(select(&document, "span, #a"), ["a", "s"]);
|
|
90
|
+
assert_eq!(select(&document, "P"), Vec::<String>::new());
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
#[test]
|
|
94
|
+
fn positions_count_along_each_step() {
|
|
95
|
+
let document = parse(LIST);
|
|
96
|
+
// position() among the step's nodes: `p` children, or `p.x` ones for *-of-type
|
|
97
|
+
assert_eq!(select(&document, "p:first"), ["a"]);
|
|
98
|
+
assert_eq!(select(&document, "p.x:first"), ["a"]);
|
|
99
|
+
assert_eq!(select(&document, "p:last"), ["c"]);
|
|
100
|
+
assert_eq!(select(&document, ".x:last-of-type"), ["c"]);
|
|
101
|
+
assert_eq!(select(&document, ".x:nth-of-type(2)"), ["c"]);
|
|
102
|
+
assert_eq!(select(&document, "p:nth-child(2)"), ["b"]);
|
|
103
|
+
assert_eq!(select(&document, "p:nth-child(odd)"), ["a"]);
|
|
104
|
+
assert_eq!(select(&document, "p:nth-last-child(1)"), ["c"]);
|
|
105
|
+
// integers as Ruby reads them: bignums, and underscores between digits
|
|
106
|
+
assert_eq!(
|
|
107
|
+
select(&document, "p:nth-child(99999999999999999999n+1)"),
|
|
108
|
+
["a"]
|
|
109
|
+
);
|
|
110
|
+
assert_eq!(select(&document, "p:nth-child(2n-1_0)"), ["b", "c"]);
|
|
111
|
+
assert_eq!(select(&document, "p:nth-child(2n-1__0)"), ["a"]);
|
|
112
|
+
// `self::` after `+` always counts 1
|
|
113
|
+
assert_eq!(select(&document, "p + p:first"), ["b"]);
|
|
114
|
+
assert_eq!(select(&document, "p[2]"), ["b"]);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
#[test]
|
|
118
|
+
fn nokogiri_quirks() {
|
|
119
|
+
let document = parse(LIST);
|
|
120
|
+
// `:not(p.x)` drops the class
|
|
121
|
+
assert_eq!(select(&document, "p:not(p.x)"), Vec::<String>::new());
|
|
122
|
+
// an empty prefix matches a missing attribute
|
|
123
|
+
assert_eq!(select(&document, "p[class^='']"), ["a", "b", "c"]);
|
|
124
|
+
assert_eq!(select(&document, "p[class='']"), Vec::<String>::new());
|
|
125
|
+
assert_eq!(select(&document, "p[@class]"), ["a", "c"]);
|
|
126
|
+
assert_eq!(select(&document, "div > @class"), Vec::<String>::new());
|
|
127
|
+
assert_eq!(select(&document, "p > @class"), ["x y", "x"]);
|
|
128
|
+
assert_eq!(select(&document, "p > text()"), ["1", "2", "3"]);
|
|
129
|
+
assert_eq!(select(&document, "p:contains('2')"), ["b"]);
|
|
130
|
+
assert_eq!(select(&document, "div:has(b)"), ["d"]);
|
|
131
|
+
assert_eq!(select(&document, "p:has(> b)"), ["b"]);
|
|
132
|
+
assert_eq!(select(&document, "p:has(+ span)"), ["b"]);
|
|
133
|
+
assert_eq!(select(&document, "[class|=x]"), ["c"]);
|
|
134
|
+
assert_eq!(select(&document, "p:empty"), Vec::<String>::new());
|
|
135
|
+
assert_eq!(select(&document, "b:root"), Vec::<String>::new());
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
#[test]
|
|
139
|
+
fn dash_match_binds_looser_than_the_conditions_after_it() {
|
|
140
|
+
let document =
|
|
141
|
+
parse("<p id=a lang=en></p><p id=b lang=en-us class=c></p><p id=c lang=en-us></p>");
|
|
142
|
+
// `@lang='en' or starts-with(…) and contains(…class…)`
|
|
143
|
+
assert_eq!(select(&document, "p[lang|=en].c"), ["a", "b"]);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
#[test]
|
|
147
|
+
fn searches_stay_inside_the_context_node() {
|
|
148
|
+
let document = parse("<div id=outer><p id=p1><b id=b1></b></p></div>");
|
|
149
|
+
let p = document
|
|
150
|
+
.descendants(NodeId::DOCUMENT)
|
|
151
|
+
.find(|&id| document.attribute_value(id, b"id") == Some(b"p1"))
|
|
152
|
+
.unwrap();
|
|
153
|
+
let subtree = options(&[Prefix::Subtree]);
|
|
154
|
+
// `.//div//b`: the div would have to be inside the p
|
|
155
|
+
assert!(select_from(&document, p, "div b", &subtree).is_empty());
|
|
156
|
+
assert_eq!(select_from(&document, p, "b", &subtree), ["b1"]);
|
|
157
|
+
let set = options(&[Prefix::Subtree, Prefix::Self_]);
|
|
158
|
+
assert_eq!(select_from(&document, p, "p", &set), ["p1"]);
|
|
159
|
+
assert_eq!(select_from(&document, p, "> b", &set), ["b1"]);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
#[test]
|
|
163
|
+
fn names_without_a_prefix_ignore_namespaces_in_html() {
|
|
164
|
+
let document = parse("<svg><rect id=r /></svg>");
|
|
165
|
+
assert_eq!(select(&document, "rect"), ["r"]);
|
|
166
|
+
let xml = Options {
|
|
167
|
+
html: false,
|
|
168
|
+
..options(&[Prefix::Global])
|
|
169
|
+
};
|
|
170
|
+
assert!(select_from(&document, NodeId::DOCUMENT, "rect", &xml).is_empty());
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
#[test]
|
|
174
|
+
fn syntax_errors() {
|
|
175
|
+
assert_eq!(error(""), "empty CSS selector");
|
|
176
|
+
assert_eq!(error("p:"), "unexpected '$' after ':'");
|
|
177
|
+
assert_eq!(error("p::x"), "unexpected ':' after ':'");
|
|
178
|
+
assert_eq!(error("p:nth-child(2x)"), "parse error on IDENT 'x'");
|
|
179
|
+
assert_eq!(error("p:-x"), "Invalid XPath function name '-x'");
|
|
180
|
+
// a decoded `*` would be the universal selector
|
|
181
|
+
assert_eq!(error(r"\2a"), r"Invalid element name '\2a'");
|
|
182
|
+
assert_eq!(error(r"x|\*"), r"Invalid element name '\*'");
|
|
183
|
+
assert_eq!(error(r"[x|a\!b]"), "Invalid attribute name 'x|a!b'");
|
|
184
|
+
let xml = Options {
|
|
185
|
+
html: false,
|
|
186
|
+
..options(&[Prefix::Global])
|
|
187
|
+
};
|
|
188
|
+
let message = compile(r"a\!b", &xml).unwrap_err().0;
|
|
189
|
+
assert_eq!(message, "Invalid element name 'a!b'");
|
|
190
|
+
assert!(error("div,").starts_with("unexpected '$'"));
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
#[test]
|
|
194
|
+
fn invalid_xpath_waits_for_evaluation() {
|
|
195
|
+
assert!(invalid("a + text()"));
|
|
196
|
+
assert!(invalid("// p"));
|
|
197
|
+
assert!(invalid("p:not(.a:first-of-type)"));
|
|
198
|
+
assert!(invalid("eq(1)"));
|
|
199
|
+
// a CSS::Node's #to_s
|
|
200
|
+
assert!(invalid("p:eq(@b)"));
|
|
201
|
+
assert!(!invalid("p:contains(@b)"));
|
|
202
|
+
// pasted as written, quotes and all
|
|
203
|
+
assert!(invalid(r"p:eq('a\'b')"));
|
|
204
|
+
// a literal holds only XML characters: \b is U+000B
|
|
205
|
+
assert!(invalid(r"p[x=a\b]"));
|
|
206
|
+
assert!(invalid(r"#\1 x"));
|
|
207
|
+
assert!(invalid(r"p:contains('\1 ')"));
|
|
208
|
+
assert!(!invalid(r#"p[x=\"]"#));
|
|
209
|
+
assert!(!invalid(r#"#a\'b\"c"#));
|
|
210
|
+
assert!(!invalid("has(a)"));
|
|
211
|
+
assert!(!invalid("p:checked"));
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
#[test]
|
|
215
|
+
fn deep_nesting_is_refused() {
|
|
216
|
+
let nested = |depth| ":not(".repeat(depth) + "p" + &")".repeat(depth);
|
|
217
|
+
assert!(compile(&nested(parser::MAX_NESTING), &options(&[Prefix::Global])).is_ok());
|
|
218
|
+
assert!(compile(
|
|
219
|
+
&nested(parser::MAX_NESTING + 1),
|
|
220
|
+
&options(&[Prefix::Global])
|
|
221
|
+
)
|
|
222
|
+
.is_err());
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
#[test]
|
|
226
|
+
fn long_selectors_cost_no_stack() {
|
|
227
|
+
let length = if cfg!(miri) { 200 } else { 20_000 };
|
|
228
|
+
let run = move || {
|
|
229
|
+
let document = parse("<p class=a>x</p>");
|
|
230
|
+
let compound = format!("p{}", ".a".repeat(length));
|
|
231
|
+
let chain = vec!["p"; length].join(" ");
|
|
232
|
+
(
|
|
233
|
+
select(&document, &compound).len(),
|
|
234
|
+
select(&document, &chain).len(),
|
|
235
|
+
)
|
|
236
|
+
};
|
|
237
|
+
let small_stack = std::thread::Builder::new().stack_size(256 * 1024);
|
|
238
|
+
assert_eq!(small_stack.spawn(run).unwrap().join().unwrap(), (1, 0));
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
#[test]
|
|
242
|
+
fn nesting_stays_within_a_ruby_thread_stack() {
|
|
243
|
+
// Ruby threads get 1 MB. A debug build uses about four times the stack
|
|
244
|
+
// per level that a release build uses.
|
|
245
|
+
let run = || {
|
|
246
|
+
let document = parse("<p class=a>x</p>");
|
|
247
|
+
let depth = parser::MAX_NESTING;
|
|
248
|
+
let nested = ":has(".repeat(depth) + "p" + &")".repeat(depth);
|
|
249
|
+
select(&document, &nested).len()
|
|
250
|
+
};
|
|
251
|
+
let stack = std::thread::Builder::new().stack_size(1024 * 1024);
|
|
252
|
+
assert_eq!(stack.spawn(run).unwrap().join().unwrap(), 0);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
#[test]
|
|
256
|
+
fn custom_calls_are_noted_until_answered() {
|
|
257
|
+
let document = parse(LIST);
|
|
258
|
+
let query = compile("p:odd('x')", &options(&[Prefix::Global]))
|
|
259
|
+
.unwrap()
|
|
260
|
+
.query
|
|
261
|
+
.unwrap();
|
|
262
|
+
assert_eq!(query.function(0).local, "odd");
|
|
263
|
+
let namespaces = HashMap::new();
|
|
264
|
+
let mut answers = HashMap::new();
|
|
265
|
+
let variables = HashMap::new();
|
|
266
|
+
let Outcome::Calls(calls) = evaluate(
|
|
267
|
+
&document,
|
|
268
|
+
&query,
|
|
269
|
+
NodeId::DOCUMENT,
|
|
270
|
+
&namespaces,
|
|
271
|
+
&variables,
|
|
272
|
+
&answers,
|
|
273
|
+
)
|
|
274
|
+
.unwrap() else {
|
|
275
|
+
panic!("calls expected");
|
|
276
|
+
};
|
|
277
|
+
assert_eq!(calls.len(), 3);
|
|
278
|
+
assert_eq!(calls[0].arguments[1], Value::String(b"x"[..].into()));
|
|
279
|
+
for (i, call) in calls.into_iter().enumerate() {
|
|
280
|
+
answers.insert(call, Ok(Value::Boolean(i % 2 == 0)));
|
|
281
|
+
}
|
|
282
|
+
let Outcome::Value(Value::NodeSet(nodes)) = evaluate(
|
|
283
|
+
&document,
|
|
284
|
+
&query,
|
|
285
|
+
NodeId::DOCUMENT,
|
|
286
|
+
&namespaces,
|
|
287
|
+
&variables,
|
|
288
|
+
&answers,
|
|
289
|
+
)
|
|
290
|
+
.unwrap() else {
|
|
291
|
+
panic!("nodes expected");
|
|
292
|
+
};
|
|
293
|
+
let ids: Vec<String> = nodes.iter().map(|&id| describe(&document, id)).collect();
|
|
294
|
+
assert_eq!(ids, ["a", "c"]);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
#[test]
|
|
298
|
+
fn prefixes_must_be_bound() {
|
|
299
|
+
let document = parse("<svg><rect id=r /></svg>");
|
|
300
|
+
let query = compile("svg|rect", &options(&[Prefix::Global]))
|
|
301
|
+
.unwrap()
|
|
302
|
+
.query
|
|
303
|
+
.unwrap();
|
|
304
|
+
let unbound = evaluate(
|
|
305
|
+
&document,
|
|
306
|
+
&query,
|
|
307
|
+
NodeId::DOCUMENT,
|
|
308
|
+
&HashMap::new(),
|
|
309
|
+
&HashMap::new(),
|
|
310
|
+
&HashMap::new(),
|
|
311
|
+
);
|
|
312
|
+
assert_eq!(unbound, Err(crate::xpath::Error::UndefinedNamespacePrefix));
|
|
313
|
+
let bound = HashMap::from([("svg".to_string(), "http://www.w3.org/2000/svg".to_string())]);
|
|
314
|
+
let found = evaluate(
|
|
315
|
+
&document,
|
|
316
|
+
&query,
|
|
317
|
+
NodeId::DOCUMENT,
|
|
318
|
+
&bound,
|
|
319
|
+
&HashMap::new(),
|
|
320
|
+
&HashMap::new(),
|
|
321
|
+
);
|
|
322
|
+
assert!(matches!(found, Ok(Outcome::Value(Value::NodeSet(nodes))) if nodes.len() == 1));
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
#[test]
|
|
326
|
+
fn unescaping() {
|
|
327
|
+
assert_eq!(parser::unescape_identifier(r"a\31 b\.c"), "a1b.c");
|
|
328
|
+
assert_eq!(parser::unescape_string("a\\\nb\\\r\nc\\\x0cd"), "abcd");
|
|
329
|
+
// one whitespace after a hex escape is part of it, CRLF counting as one
|
|
330
|
+
assert_eq!(parser::unescape_identifier("\\31\r\nx"), "1x");
|
|
331
|
+
assert_eq!(parser::unescape_identifier("\\31\x0bx"), "1\x0bx");
|
|
332
|
+
// NUL, surrogates and code points past U+10FFFF
|
|
333
|
+
for escape in [r"\0", r"\D800", r"\110000"] {
|
|
334
|
+
assert_eq!(parser::unescape_identifier(escape), "\u{FFFD}");
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
#[test]
|
|
339
|
+
fn escaped_values_match_what_they_decode_to() {
|
|
340
|
+
let document = parse(
|
|
341
|
+
r#"<p id="it's" class="a'b" title='say "it's"'></p><p id=n data-x=1 @click=c :class=k></p><a-b id=h></a-b>"#,
|
|
342
|
+
);
|
|
343
|
+
assert_eq!(select(&document, r"#it\'s"), ["it's"]);
|
|
344
|
+
assert_eq!(select(&document, r"p.a\'b"), ["it's"]);
|
|
345
|
+
assert_eq!(select(&document, r#"[title='say "it\'s"']"#), ["it's"]);
|
|
346
|
+
assert_eq!(select(&document, r#"p:contains('')"#), ["it's", "n"]);
|
|
347
|
+
assert_eq!(select(&document, r"[data\-x=1]"), ["n"]);
|
|
348
|
+
assert_eq!(select(&document, r"[\@click=c]"), ["n"]);
|
|
349
|
+
assert_eq!(select(&document, r"[\:class]"), ["n"]);
|
|
350
|
+
assert_eq!(select(&document, r"p > @\:class"), ["k"]);
|
|
351
|
+
assert_eq!(select(&document, r"a\-b"), ["h"]);
|
|
352
|
+
// a name XPath can't write still matches in HTML, by its local name
|
|
353
|
+
assert!(select(&document, r"a\!b").is_empty());
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
#[test]
|
|
357
|
+
fn nth_with_a_zero_or_negative_step() {
|
|
358
|
+
let document = parse(LIST);
|
|
359
|
+
assert_eq!(select(&document, "p:nth-child(0n+3)"), Vec::<String>::new());
|
|
360
|
+
assert_eq!(select(&document, "p:nth-child(0n+1)"), ["a"]);
|
|
361
|
+
assert_eq!(select(&document, "p:nth-of-type(0n+3)"), ["c"]);
|
|
362
|
+
assert!(select(&document, "p:nth-child(0n-1)").is_empty());
|
|
363
|
+
assert!(select(&document, "p:nth-child(-n+0)").is_empty());
|
|
364
|
+
assert!(select(&document, "p:nth-child(-2n)").is_empty());
|
|
365
|
+
assert_eq!(select(&document, "p:nth-child(-n+2)"), ["a", "b"]);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
fn written(rule: &str, visitor: &Visitor) -> Vec<String> {
|
|
369
|
+
xpath_for(rule, visitor).unwrap()
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
fn visitor(builtins: bool, html5: bool) -> Visitor {
|
|
373
|
+
Visitor {
|
|
374
|
+
builtins,
|
|
375
|
+
html5,
|
|
376
|
+
default_namespace: false,
|
|
377
|
+
prefix: "//".into(),
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
#[test]
|
|
382
|
+
fn xpath_for_writes_what_nokogiri_writes() {
|
|
383
|
+
let plain = visitor(false, false);
|
|
384
|
+
assert_eq!(
|
|
385
|
+
written("h1 + div, a ~ b > c d", &plain),
|
|
386
|
+
[
|
|
387
|
+
"//h1/following-sibling::*[1]/self::div",
|
|
388
|
+
"//a/following-sibling::b/c//d"
|
|
389
|
+
]
|
|
390
|
+
);
|
|
391
|
+
assert_eq!(
|
|
392
|
+
written("a.b#c[d|=e]:first-of-type", &plain),
|
|
393
|
+
[
|
|
394
|
+
"//a[contains(concat(' ',normalize-space(@class),' '),' b ') and @id='c' and \
|
|
395
|
+
@d='e' or starts-with(@d,concat('e','-'))][position()=1]"
|
|
396
|
+
]
|
|
397
|
+
);
|
|
398
|
+
assert_eq!(
|
|
399
|
+
written("a:nth-child(2n+1):not(b):has(> c)", &plain),
|
|
400
|
+
["//a[((count(preceding-sibling::*)+1)>=1) and \
|
|
401
|
+
((((count(preceding-sibling::*)+1)-1) mod 2)=0) and not(self::b) and ./c]"]
|
|
402
|
+
);
|
|
403
|
+
assert_eq!(
|
|
404
|
+
written(r#"[a="it's"], [b='"\'']"#, &plain),
|
|
405
|
+
[r#"//*[@a="it's"]"#, r#"//*[@b=concat('"',"'",'')]"#]
|
|
406
|
+
);
|
|
407
|
+
assert_eq!(
|
|
408
|
+
written("a:eq(@b)", &plain),
|
|
409
|
+
["//a[position()=#<Nokogiri::CSS::Node>]"]
|
|
410
|
+
);
|
|
411
|
+
assert_eq!(
|
|
412
|
+
written("a.b, svg|a, *, a\\@b", &visitor(true, true)),
|
|
413
|
+
[
|
|
414
|
+
"//*:a[nokogiri-builtin:css-class(@class,'b')]",
|
|
415
|
+
"//svg:a",
|
|
416
|
+
"//*",
|
|
417
|
+
"//*[nokogiri-builtin:local-name-is('a@b')]"
|
|
418
|
+
]
|
|
419
|
+
);
|
|
420
|
+
assert_eq!(
|
|
421
|
+
written("a", &visitor(false, true)),
|
|
422
|
+
["//*[local-name()='a']"]
|
|
423
|
+
);
|
|
424
|
+
let namespaced = Visitor {
|
|
425
|
+
default_namespace: true,
|
|
426
|
+
prefix: "x/".into(),
|
|
427
|
+
..plain
|
|
428
|
+
};
|
|
429
|
+
assert_eq!(written("a > *, |b", &namespaced), ["x/xmlns:a/*", "x/b"]);
|
|
430
|
+
assert_eq!(written("> c", &namespaced), ["./xmlns:c"]);
|
|
431
|
+
assert_eq!(written("// c", &namespaced), ["x///xmlns:c"]);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
#[test]
|
|
435
|
+
fn xpath_for_syntax_errors() {
|
|
436
|
+
let error = |rule| xpath_for(rule, &visitor(false, false)).unwrap_err().0;
|
|
437
|
+
assert_eq!(error(""), "empty CSS selector");
|
|
438
|
+
assert_eq!(error("a:-b"), "Invalid XPath function name '-b'");
|
|
439
|
+
assert_eq!(error(r"a\!b"), "Invalid element name 'a!b'");
|
|
440
|
+
assert_eq!(error(r"[a|b\!c]"), "Invalid attribute name 'a|b!c'");
|
|
441
|
+
assert!(error("a,").starts_with("unexpected '$'"));
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/// The string and the compiled tree are two readings of one visitor.
|
|
445
|
+
#[test]
|
|
446
|
+
fn xpath_for_is_invalid_where_the_compiled_selector_is() {
|
|
447
|
+
let rules = [
|
|
448
|
+
"p",
|
|
449
|
+
"p.x:first",
|
|
450
|
+
"div > p:nth-child(2n)",
|
|
451
|
+
"p:has(b)",
|
|
452
|
+
"p + span, #c",
|
|
453
|
+
"p[class~=y]",
|
|
454
|
+
"a + text()",
|
|
455
|
+
"// p",
|
|
456
|
+
"p:not(.a:first-of-type)",
|
|
457
|
+
"eq(1)",
|
|
458
|
+
r"p:eq('a\'b')",
|
|
459
|
+
"p:eq(@b)",
|
|
460
|
+
"p:eq(2n+1)",
|
|
461
|
+
"p:self(@b)",
|
|
462
|
+
"p:contains()",
|
|
463
|
+
"p:nth-last-of-type(0)",
|
|
464
|
+
];
|
|
465
|
+
for rule in rules {
|
|
466
|
+
let compiled = compile(rule, &options(&[Prefix::Global])).unwrap().query;
|
|
467
|
+
let paths = written(rule, &visitor(true, true)).join("|");
|
|
468
|
+
let parsed = crate::xpath::parse(paths.as_bytes());
|
|
469
|
+
assert_eq!(compiled.is_ok(), parsed.is_ok(), "{rule}: {paths}");
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
#[test]
|
|
474
|
+
fn reduce_handles_the_rules_the_tables_number() {
|
|
475
|
+
assert_eq!(parser::REDUCED_RULES, tables::GRAMMAR);
|
|
476
|
+
}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
//! Nokogiri's CSS tokenizer (lib/nokogiri/css/tokenizer.rex), rule for rule.
|
|
2
|
+
//! The first rule that matches at the current position wins,
|
|
3
|
+
//! as in the generated scanner. The longest match does not win.
|
|
4
|
+
|
|
5
|
+
use super::tables as t;
|
|
6
|
+
|
|
7
|
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
8
|
+
pub struct Token<'a> {
|
|
9
|
+
/// The racc token number. [`t::ERROR`] for a character that no rule names.
|
|
10
|
+
pub kind: i16,
|
|
11
|
+
pub text: &'a str,
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
pub struct Tokenizer<'a> {
|
|
15
|
+
input: &'a str,
|
|
16
|
+
position: usize,
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
impl<'a> Tokenizer<'a> {
|
|
20
|
+
pub fn new(input: &'a str) -> Tokenizer<'a> {
|
|
21
|
+
Tokenizer { input, position: 0 }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
fn rest(&self) -> &'a str {
|
|
25
|
+
&self.input[self.position..]
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
impl<'a> Iterator for Tokenizer<'a> {
|
|
30
|
+
type Item = Token<'a>;
|
|
31
|
+
|
|
32
|
+
fn next(&mut self) -> Option<Token<'a>> {
|
|
33
|
+
let rest = self.rest();
|
|
34
|
+
let first = rest.chars().next()?;
|
|
35
|
+
let (kind, length) = RULES
|
|
36
|
+
.iter()
|
|
37
|
+
.find_map(|(kind, rule)| rule(rest).map(|length| (*kind, length)))
|
|
38
|
+
.unwrap_or_else(|| {
|
|
39
|
+
let kind = match first {
|
|
40
|
+
'@' => t::AT,
|
|
41
|
+
'.' => t::DOT,
|
|
42
|
+
'*' => t::STAR,
|
|
43
|
+
'|' => t::PIPE,
|
|
44
|
+
':' => t::COLON,
|
|
45
|
+
_ => t::ERROR,
|
|
46
|
+
};
|
|
47
|
+
(kind, first.len_utf8())
|
|
48
|
+
});
|
|
49
|
+
let text = &rest[..length];
|
|
50
|
+
self.position += length;
|
|
51
|
+
Some(Token { kind, text })
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
type Rule = fn(&str) -> Option<usize>;
|
|
56
|
+
|
|
57
|
+
// `U\+[0-9a-f?]{1,6}…` (UNICODE_RANGE) is left out: IDENT, which comes earlier,
|
|
58
|
+
// always takes the `U`.
|
|
59
|
+
const RULES: [(i16, Rule); 24] = [
|
|
60
|
+
(t::HAS, |s| after(s, "has(").map(|n| n + spaces(&s[n..]))),
|
|
61
|
+
(t::FUNCTION, |s| {
|
|
62
|
+
let n = ident(s)?;
|
|
63
|
+
after(&s[n..], "(").map(|m| n + m + spaces(&s[n + m..]))
|
|
64
|
+
}),
|
|
65
|
+
(t::IDENT, ident),
|
|
66
|
+
(t::HASH, |s| {
|
|
67
|
+
let n = after(s, "#")?;
|
|
68
|
+
let m = repeat(&s[n..], nmchar);
|
|
69
|
+
(m > 0).then_some(n + m)
|
|
70
|
+
}),
|
|
71
|
+
(t::INCLUDES, |s| spaced(s, "~=")),
|
|
72
|
+
(t::DASHMATCH, |s| spaced(s, "|=")),
|
|
73
|
+
(t::PREFIXMATCH, |s| spaced(s, "^=")),
|
|
74
|
+
(t::SUFFIXMATCH, |s| spaced(s, "$=")),
|
|
75
|
+
(t::SUBSTRINGMATCH, |s| spaced(s, "*=")),
|
|
76
|
+
(t::NOT_EQUAL, |s| spaced(s, "!=")),
|
|
77
|
+
(t::EQUAL, |s| spaced(s, "=")),
|
|
78
|
+
(t::RPAREN, |s| {
|
|
79
|
+
let n = spaces(s);
|
|
80
|
+
after(&s[n..], ")").map(|m| n + m)
|
|
81
|
+
}),
|
|
82
|
+
(t::LSQUARE, |s| after(s, "[").map(|n| n + spaces(&s[n..]))),
|
|
83
|
+
(t::RSQUARE, |s| {
|
|
84
|
+
let n = spaces(s);
|
|
85
|
+
after(&s[n..], "]").map(|m| n + m)
|
|
86
|
+
}),
|
|
87
|
+
(t::PLUS, |s| spaced(s, "+")),
|
|
88
|
+
(t::GREATER, |s| spaced(s, ">")),
|
|
89
|
+
(t::COMMA, |s| spaced(s, ",")),
|
|
90
|
+
(t::TILDE, |s| spaced(s, "~")),
|
|
91
|
+
(t::NOT, |s| after(s, ":not(").map(|n| n + spaces(&s[n..]))),
|
|
92
|
+
(t::NUMBER, number),
|
|
93
|
+
(t::DOUBLESLASH, |s| spaced(s, "//")),
|
|
94
|
+
(t::SLASH, |s| spaced(s, "/")),
|
|
95
|
+
(t::S, |s| Some(spaces(s)).filter(|&n| n > 0)),
|
|
96
|
+
(t::STRING, string),
|
|
97
|
+
];
|
|
98
|
+
|
|
99
|
+
fn is_space(c: char) -> bool {
|
|
100
|
+
matches!(c, ' ' | '\t' | '\n' | '\x0b' | '\x0c' | '\r')
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
fn spaces(s: &str) -> usize {
|
|
104
|
+
s.len() - s.trim_start_matches(is_space).len()
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
fn after(s: &str, literal: &str) -> Option<usize> {
|
|
108
|
+
s.starts_with(literal).then_some(literal.len())
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/// `[\s]*literal[\s]*`
|
|
112
|
+
fn spaced(s: &str, literal: &str) -> Option<usize> {
|
|
113
|
+
let n = spaces(s);
|
|
114
|
+
let m = after(&s[n..], literal)?;
|
|
115
|
+
Some(n + m + spaces(&s[n + m..]))
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
fn repeat(s: &str, unit: impl Fn(&str) -> Option<usize>) -> usize {
|
|
119
|
+
let mut n = 0;
|
|
120
|
+
while let Some(m) = unit(&s[n..]) {
|
|
121
|
+
n += m;
|
|
122
|
+
}
|
|
123
|
+
n
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
fn first(s: &str) -> Option<char> {
|
|
127
|
+
s.chars().next()
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/// `{unicode}|\\[^\n\r\f0-9A-Fa-f]`
|
|
131
|
+
fn escape(s: &str) -> Option<usize> {
|
|
132
|
+
let rest = s.strip_prefix('\\')?;
|
|
133
|
+
let c = first(rest)?;
|
|
134
|
+
if c.is_ascii_hexdigit() {
|
|
135
|
+
let digits = rest
|
|
136
|
+
.bytes()
|
|
137
|
+
.take(6)
|
|
138
|
+
.take_while(u8::is_ascii_hexdigit)
|
|
139
|
+
.count();
|
|
140
|
+
let tail = &rest[digits..];
|
|
141
|
+
let space = if tail.starts_with("\r\n") {
|
|
142
|
+
2
|
|
143
|
+
} else {
|
|
144
|
+
first(tail)
|
|
145
|
+
.filter(|&c| is_space(c))
|
|
146
|
+
.map_or(0, char::len_utf8)
|
|
147
|
+
};
|
|
148
|
+
Some(1 + digits + space)
|
|
149
|
+
} else if matches!(c, '\n' | '\r' | '\x0c') {
|
|
150
|
+
None
|
|
151
|
+
} else {
|
|
152
|
+
Some(1 + c.len_utf8())
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/// `[_A-Za-z]|{nonascii}|{escape}`
|
|
157
|
+
fn nmstart(s: &str) -> Option<usize> {
|
|
158
|
+
match first(s)? {
|
|
159
|
+
c if c == '_' || c.is_ascii_alphabetic() || !c.is_ascii() => Some(c.len_utf8()),
|
|
160
|
+
_ => escape(s),
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/// `[_A-Za-z0-9-]|{nonascii}|{escape}`
|
|
165
|
+
fn nmchar(s: &str) -> Option<usize> {
|
|
166
|
+
match first(s)? {
|
|
167
|
+
c if c == '-' || c.is_ascii_digit() => Some(1),
|
|
168
|
+
_ => nmstart(s),
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/// `-?{nmstart}{nmchar}*`
|
|
173
|
+
fn ident(s: &str) -> Option<usize> {
|
|
174
|
+
let dash = usize::from(s.starts_with('-'));
|
|
175
|
+
let n = dash + nmstart(&s[dash..])?;
|
|
176
|
+
Some(n + repeat(&s[n..], nmchar))
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/// `-?([0-9]+|[0-9]*\.[0-9]+)`. The first alternative wins when it matches
|
|
180
|
+
/// at all: `1.5` is the number `1`.
|
|
181
|
+
fn number(s: &str) -> Option<usize> {
|
|
182
|
+
let sign = usize::from(s.starts_with('-'));
|
|
183
|
+
let rest = &s[sign..];
|
|
184
|
+
let digits = |s: &str| s.bytes().take_while(u8::is_ascii_digit).count();
|
|
185
|
+
let whole = digits(rest);
|
|
186
|
+
if whole > 0 {
|
|
187
|
+
return Some(sign + whole);
|
|
188
|
+
}
|
|
189
|
+
let fraction = digits(rest.strip_prefix('.')?);
|
|
190
|
+
(fraction > 0).then_some(sign + 1 + fraction)
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/// `"(?>[^\n\r\f"\\]|\\?{nl}|{nonascii}|{escape})*"` and its twin with single
|
|
194
|
+
/// quotes.
|
|
195
|
+
fn string(s: &str) -> Option<usize> {
|
|
196
|
+
let quote = first(s).filter(|&c| c == '"' || c == '\'')?;
|
|
197
|
+
let unit = |s: &str| -> Option<usize> {
|
|
198
|
+
let c = first(s)?;
|
|
199
|
+
if !matches!(c, '\n' | '\r' | '\x0c' | '\\') && c != quote {
|
|
200
|
+
return Some(c.len_utf8());
|
|
201
|
+
}
|
|
202
|
+
let backslash = usize::from(c == '\\');
|
|
203
|
+
let rest = &s[backslash..];
|
|
204
|
+
let newline = if rest.starts_with("\r\n") {
|
|
205
|
+
Some(2)
|
|
206
|
+
} else {
|
|
207
|
+
first(rest)
|
|
208
|
+
.filter(|c| matches!(c, '\n' | '\r' | '\x0c'))
|
|
209
|
+
.map(|_| 1)
|
|
210
|
+
};
|
|
211
|
+
newline.map(|n| backslash + n).or_else(|| escape(s))
|
|
212
|
+
};
|
|
213
|
+
let body = 1 + repeat(&s[1..], unit);
|
|
214
|
+
first(&s[body..]).filter(|&c| c == quote).map(|_| body + 1)
|
|
215
|
+
}
|