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,806 @@
|
|
|
1
|
+
//! Port of Nokogiri's `CSS::XPathVisitor` (lib/nokogiri/css/xpath_visitor.rb).
|
|
2
|
+
//! It builds the XPath tree that the visitor writes as a string. The visitor
|
|
3
|
+
//! pastes tokens into XPath as written. This code follows how libxml2 reads
|
|
4
|
+
//! the result, including strings that are not valid XPath. Those become
|
|
5
|
+
//! [`crate::xpath::Error::InvalidExpression`], which evaluation raises,
|
|
6
|
+
//! as libxml2 does when Nokogiri evaluates them.
|
|
7
|
+
|
|
8
|
+
use super::parser::{
|
|
9
|
+
unescape_string, Argument, AttributeName, AttributeOperator, AttributeSubject, Combinator,
|
|
10
|
+
Condition, ElementName, Function, Negation, Nth, Pseudo, Selector, Simple,
|
|
11
|
+
};
|
|
12
|
+
use super::{Options, Prefix, SyntaxError};
|
|
13
|
+
use crate::xpath::chars::{is_name_char, is_name_start, is_xml_char};
|
|
14
|
+
use crate::xpath::{
|
|
15
|
+
Arithmetic, Axis, Comparison, Expr, Function as F, NodeTest, Path, QName, Step,
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
pub enum Failure {
|
|
19
|
+
/// Raised while translating, as Nokogiri raises it from `xpath_for`.
|
|
20
|
+
Syntax(SyntaxError),
|
|
21
|
+
/// Translates to a string that libxml2 cannot parse.
|
|
22
|
+
Invalid,
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
impl From<SyntaxError> for Failure {
|
|
26
|
+
fn from(error: SyntaxError) -> Failure {
|
|
27
|
+
Failure::Syntax(error)
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
type Result<T> = std::result::Result<T, Failure>;
|
|
32
|
+
|
|
33
|
+
/// The translation of a function or simple selector. It decides
|
|
34
|
+
/// where the string can go.
|
|
35
|
+
enum Fragment {
|
|
36
|
+
/// A relative location path. `axis_free` is true for a bare node test.
|
|
37
|
+
/// It can follow an axis (`self::comment()`), but `child::text()` cannot.
|
|
38
|
+
Steps {
|
|
39
|
+
steps: Vec<Step>,
|
|
40
|
+
axis_free: bool,
|
|
41
|
+
},
|
|
42
|
+
Expr(Expr),
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
impl Fragment {
|
|
46
|
+
fn into_expr(self) -> Expr {
|
|
47
|
+
match self {
|
|
48
|
+
Fragment::Steps { steps, .. } => Expr::Path(Path::relative(steps)),
|
|
49
|
+
Fragment::Expr(expr) => expr,
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/// The translation of a condition. `a or b` stays separate, because the visitor
|
|
55
|
+
/// joins conditions with a bare ` and `, which binds tighter.
|
|
56
|
+
enum Term {
|
|
57
|
+
One(Expr),
|
|
58
|
+
Or(Expr, Expr),
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/// Where the string of the next simple selector goes. After `/` it starts
|
|
62
|
+
/// a step of its own. After `::` it is the node test of a given axis.
|
|
63
|
+
#[derive(Clone, Copy)]
|
|
64
|
+
enum Join {
|
|
65
|
+
Slash,
|
|
66
|
+
Axis(Axis),
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
pub struct Translator<'a> {
|
|
70
|
+
options: &'a Options,
|
|
71
|
+
pub functions: Vec<String>,
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
impl<'a> Translator<'a> {
|
|
75
|
+
pub fn new(options: &'a Options) -> Translator<'a> {
|
|
76
|
+
Translator {
|
|
77
|
+
options,
|
|
78
|
+
functions: Vec::new(),
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/// `Node#to_xpath`: the prefix, or `.` for a leading `>`, `+` or `~`,
|
|
83
|
+
/// then the selector.
|
|
84
|
+
pub fn selector(&mut self, selector: &Selector, prefix: Prefix) -> Result<Path> {
|
|
85
|
+
let (mut path, join) = match selector.leading {
|
|
86
|
+
Some(Combinator::Child | Combinator::DirectAdjacent | Combinator::Following) => {
|
|
87
|
+
(Path::relative(Vec::new()), None)
|
|
88
|
+
}
|
|
89
|
+
// Gives `.////p` and similar.
|
|
90
|
+
Some(Combinator::Descendant) => return Err(Failure::Invalid),
|
|
91
|
+
None => match prefix {
|
|
92
|
+
Prefix::Global => (descendants(true), Some(Join::Slash)),
|
|
93
|
+
Prefix::Subtree => (descendants(false), Some(Join::Slash)),
|
|
94
|
+
Prefix::Current => (Path::relative(Vec::new()), Some(Join::Slash)),
|
|
95
|
+
Prefix::Root => (
|
|
96
|
+
Path {
|
|
97
|
+
absolute: true,
|
|
98
|
+
steps: Vec::new(),
|
|
99
|
+
},
|
|
100
|
+
Some(Join::Slash),
|
|
101
|
+
),
|
|
102
|
+
Prefix::Self_ => (Path::relative(Vec::new()), Some(Join::Axis(Axis::Self_))),
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
let join = match (join, selector.leading) {
|
|
106
|
+
(Some(join), _) => join,
|
|
107
|
+
(None, Some(combinator)) => combine(&mut path, combinator),
|
|
108
|
+
(None, None) => unreachable!("either a prefix or a leading combinator"),
|
|
109
|
+
};
|
|
110
|
+
self.chain(&mut path, join, selector)?;
|
|
111
|
+
Ok(path)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
fn chain(&mut self, path: &mut Path, mut join: Join, selector: &Selector) -> Result<()> {
|
|
115
|
+
self.simple(path, join, &selector.first)?;
|
|
116
|
+
for (combinator, simple) in &selector.rest {
|
|
117
|
+
join = combine(path, *combinator);
|
|
118
|
+
self.simple(path, join, simple)?;
|
|
119
|
+
}
|
|
120
|
+
Ok(())
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
fn simple(&mut self, path: &mut Path, join: Join, simple: &Simple) -> Result<()> {
|
|
124
|
+
let (steps, axis_free, predicates) = match simple {
|
|
125
|
+
Simple::Element { name, conditions } => {
|
|
126
|
+
let step = Step::new(Axis::Child, self.element_test(name)?);
|
|
127
|
+
let predicates = if conditions.is_empty() {
|
|
128
|
+
Vec::new()
|
|
129
|
+
} else {
|
|
130
|
+
self.conditions(conditions)?
|
|
131
|
+
};
|
|
132
|
+
(vec![step], true, predicates)
|
|
133
|
+
}
|
|
134
|
+
Simple::Function {
|
|
135
|
+
function,
|
|
136
|
+
condition,
|
|
137
|
+
} => {
|
|
138
|
+
let Fragment::Steps { steps, axis_free } = self.function(function)? else {
|
|
139
|
+
// `position()=1` and similar are not steps.
|
|
140
|
+
return Err(Failure::Invalid);
|
|
141
|
+
};
|
|
142
|
+
let predicates = match condition {
|
|
143
|
+
Some(condition) => vec![self.terms(std::slice::from_ref(condition))?],
|
|
144
|
+
None => Vec::new(),
|
|
145
|
+
};
|
|
146
|
+
(steps, axis_free, predicates)
|
|
147
|
+
}
|
|
148
|
+
Simple::Attribute(name) => (vec![attribute_step(name)?], false, Vec::new()),
|
|
149
|
+
};
|
|
150
|
+
let mut steps = steps;
|
|
151
|
+
if let Join::Axis(axis) = join {
|
|
152
|
+
if !axis_free {
|
|
153
|
+
return Err(Failure::Invalid);
|
|
154
|
+
}
|
|
155
|
+
steps[0].axis = axis;
|
|
156
|
+
}
|
|
157
|
+
steps
|
|
158
|
+
.last_mut()
|
|
159
|
+
.expect("a fragment has steps")
|
|
160
|
+
.predicates
|
|
161
|
+
.extend(predicates);
|
|
162
|
+
path.steps.extend(steps);
|
|
163
|
+
Ok(())
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/// `visit_element_name`
|
|
167
|
+
fn element_test(&self, name: &ElementName) -> Result<NodeTest> {
|
|
168
|
+
if let (None, local) = (&name.prefix, name.local.as_str()) {
|
|
169
|
+
// HTML5 has namespaces that CSS queries ignore. The visitor writes
|
|
170
|
+
// `*:name`, or a `local-name()` test for a name
|
|
171
|
+
// that is not an XPath name.
|
|
172
|
+
if self.options.html && local != "*" {
|
|
173
|
+
if self.options.builtins && xpath_name(local) {
|
|
174
|
+
ncname(local)?;
|
|
175
|
+
} else {
|
|
176
|
+
check_literal(local)?;
|
|
177
|
+
}
|
|
178
|
+
return Ok(NodeTest::LocalName(local.into()));
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
let mut names = name.prefix.iter().flatten().chain([&name.local]);
|
|
182
|
+
if let Some(invalid) = names.find(|n| *n != "*" && !xpath_name(n)) {
|
|
183
|
+
return Err(SyntaxError(format!("Invalid element name '{invalid}'")).into());
|
|
184
|
+
}
|
|
185
|
+
let test = match (&name.prefix, name.local.as_str()) {
|
|
186
|
+
(None, "*") => NodeTest::Any,
|
|
187
|
+
(Some(prefix), local) => NodeTest::Name(QName {
|
|
188
|
+
prefix: prefix.as_deref().map(ncname).transpose()?.map(Into::into),
|
|
189
|
+
local: ncname(local)?.into(),
|
|
190
|
+
}),
|
|
191
|
+
(None, local) if self.options.default_namespace => NodeTest::Name(QName {
|
|
192
|
+
prefix: Some("xmlns".into()),
|
|
193
|
+
local: ncname(local)?.into(),
|
|
194
|
+
}),
|
|
195
|
+
(None, local) => NodeTest::Name(QName {
|
|
196
|
+
prefix: None,
|
|
197
|
+
local: ncname(local)?.into(),
|
|
198
|
+
}),
|
|
199
|
+
};
|
|
200
|
+
Ok(test)
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/// The predicates of the conditions of a compound. `visit_combinator` joins
|
|
204
|
+
/// them with ` and `. A final `*-of-type` gets its own predicates
|
|
205
|
+
/// (`][`), so it counts only the nodes that pass the conditions before it.
|
|
206
|
+
fn conditions(&mut self, conditions: &[Condition]) -> Result<Vec<Expr>> {
|
|
207
|
+
match conditions.split_last() {
|
|
208
|
+
Some((last, init)) if !init.is_empty() && is_of_type(last) => Ok(vec![
|
|
209
|
+
self.terms(init)?,
|
|
210
|
+
self.terms(std::slice::from_ref(last))?,
|
|
211
|
+
]),
|
|
212
|
+
_ => Ok(vec![self.terms(conditions)?]),
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
fn terms(&mut self, conditions: &[Condition]) -> Result<Expr> {
|
|
217
|
+
let mut disjuncts: Vec<Vec<Expr>> = vec![Vec::new()];
|
|
218
|
+
for condition in conditions {
|
|
219
|
+
match self.condition(condition)? {
|
|
220
|
+
Term::One(expr) => disjuncts.last_mut().expect("never empty").push(expr),
|
|
221
|
+
Term::Or(left, right) => {
|
|
222
|
+
disjuncts.last_mut().expect("never empty").push(left);
|
|
223
|
+
disjuncts.push(vec![right]);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
let mut conjunctions = disjuncts.into_iter().map(|mut list| {
|
|
228
|
+
if list.len() == 1 {
|
|
229
|
+
list.pop().expect("one")
|
|
230
|
+
} else {
|
|
231
|
+
Expr::And(list)
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
Ok(if conjunctions.len() == 1 {
|
|
235
|
+
conjunctions.next().expect("one")
|
|
236
|
+
} else {
|
|
237
|
+
Expr::Or(conjunctions.collect())
|
|
238
|
+
})
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
fn condition(&mut self, condition: &Condition) -> Result<Term> {
|
|
242
|
+
Ok(Term::One(match condition {
|
|
243
|
+
Condition::Id(id) => {
|
|
244
|
+
let id = id.strip_prefix('#').unwrap_or(id);
|
|
245
|
+
Expr::compare(Comparison::Equal, attribute("id"), literal(id)?)
|
|
246
|
+
}
|
|
247
|
+
Condition::Class(name) => self.css_class(attribute("class"), name)?,
|
|
248
|
+
Condition::Attribute { subject, test } => {
|
|
249
|
+
return self.attribute_condition(subject, test)
|
|
250
|
+
}
|
|
251
|
+
Condition::Pseudo(Pseudo::Ident(name)) => self.pseudo_class(name)?,
|
|
252
|
+
Condition::Pseudo(Pseudo::Function(function)) => self.function(function)?.into_expr(),
|
|
253
|
+
Condition::Not(Negation::Element(name)) => {
|
|
254
|
+
let test = self.element_test(name)?;
|
|
255
|
+
Expr::Call(
|
|
256
|
+
F::Not,
|
|
257
|
+
vec![Expr::Path(Path::relative(vec![Step::new(
|
|
258
|
+
Axis::Self_,
|
|
259
|
+
test,
|
|
260
|
+
)]))],
|
|
261
|
+
)
|
|
262
|
+
}
|
|
263
|
+
Condition::Not(Negation::Conditions(conditions)) => {
|
|
264
|
+
let predicates = self.conditions(conditions)?;
|
|
265
|
+
if predicates.len() > 1 {
|
|
266
|
+
// Gives `not(a][b)`.
|
|
267
|
+
return Err(Failure::Invalid);
|
|
268
|
+
}
|
|
269
|
+
Expr::Call(F::Not, predicates)
|
|
270
|
+
}
|
|
271
|
+
}))
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/// `visit_attribute_condition`
|
|
275
|
+
fn attribute_condition(
|
|
276
|
+
&mut self,
|
|
277
|
+
subject: &AttributeSubject,
|
|
278
|
+
test: &Option<(AttributeOperator, String)>,
|
|
279
|
+
) -> Result<Term> {
|
|
280
|
+
let subject = match subject {
|
|
281
|
+
AttributeSubject::Name(name) => attribute_path(name)?,
|
|
282
|
+
AttributeSubject::Function(function) => self.function(function)?.into_expr(),
|
|
283
|
+
};
|
|
284
|
+
let Some((operator, value)) = test else {
|
|
285
|
+
return Ok(Term::One(subject));
|
|
286
|
+
};
|
|
287
|
+
let value_literal = literal(value)?;
|
|
288
|
+
let literal = || value_literal.clone();
|
|
289
|
+
let call = |function, argument: Expr| Expr::Call(function, vec![subject.clone(), argument]);
|
|
290
|
+
Ok(Term::One(match operator {
|
|
291
|
+
AttributeOperator::Equal => Expr::compare(Comparison::Equal, subject, literal()),
|
|
292
|
+
AttributeOperator::NotEqual => Expr::compare(Comparison::NotEqual, subject, literal()),
|
|
293
|
+
AttributeOperator::SubstringMatch => call(F::Contains, literal()),
|
|
294
|
+
AttributeOperator::PrefixMatch => call(F::StartsWith, literal()),
|
|
295
|
+
AttributeOperator::SuffixMatch => call(F::EndsWith, literal()),
|
|
296
|
+
AttributeOperator::DashMatch => {
|
|
297
|
+
let dashed = Expr::Call(F::Concat, vec![literal(), Expr::Literal(b"-".to_vec())]);
|
|
298
|
+
return Ok(Term::Or(
|
|
299
|
+
Expr::compare(Comparison::Equal, subject.clone(), literal()),
|
|
300
|
+
call(F::StartsWith, dashed),
|
|
301
|
+
));
|
|
302
|
+
}
|
|
303
|
+
AttributeOperator::Includes => self.css_class(subject, value)?,
|
|
304
|
+
}))
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/// `visit_pseudo_class` for a name without parentheses.
|
|
308
|
+
fn pseudo_class(&mut self, name: &str) -> Result<Expr> {
|
|
309
|
+
Ok(match name {
|
|
310
|
+
"first" | "first-of-type" => position_is(Expr::Number(1.0)),
|
|
311
|
+
"last" | "last-of-type" => position_is(call(F::Last)),
|
|
312
|
+
"first-child" => count_is(Axis::PrecedingSibling, 0.0),
|
|
313
|
+
"last-child" => count_is(Axis::FollowingSibling, 0.0),
|
|
314
|
+
"only-child" => Expr::And(vec![
|
|
315
|
+
count_is(Axis::PrecedingSibling, 0.0),
|
|
316
|
+
count_is(Axis::FollowingSibling, 0.0),
|
|
317
|
+
]),
|
|
318
|
+
"only-of-type" => Expr::compare(Comparison::Equal, call(F::Last), Expr::Number(1.0)),
|
|
319
|
+
"empty" => Expr::Call(F::Not, vec![children()]),
|
|
320
|
+
"parent" => children(),
|
|
321
|
+
"root" => Expr::Call(
|
|
322
|
+
F::Not,
|
|
323
|
+
vec![Expr::Path(Path::relative(vec![Step::new(
|
|
324
|
+
Axis::Parent,
|
|
325
|
+
NodeTest::Any,
|
|
326
|
+
)]))],
|
|
327
|
+
),
|
|
328
|
+
_ => self.custom(name, &[])?,
|
|
329
|
+
})
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/// `visit_function`, by the name with its `(`.
|
|
333
|
+
fn function(&mut self, function: &Function) -> Result<Fragment> {
|
|
334
|
+
let argument = function.arguments.first();
|
|
335
|
+
let nth = match argument {
|
|
336
|
+
Some(Argument::Nth(nth)) => Some(nth),
|
|
337
|
+
_ => None,
|
|
338
|
+
};
|
|
339
|
+
let expr = match function.name.as_str() {
|
|
340
|
+
"text(" => {
|
|
341
|
+
return Ok(Fragment::Steps {
|
|
342
|
+
steps: vec![Step::new(Axis::Child, NodeTest::Text)],
|
|
343
|
+
axis_free: false,
|
|
344
|
+
})
|
|
345
|
+
}
|
|
346
|
+
"self(" => {
|
|
347
|
+
let Some(Argument::Ident(name)) = argument else {
|
|
348
|
+
return Err(Failure::Invalid);
|
|
349
|
+
};
|
|
350
|
+
return Ok(Fragment::Steps {
|
|
351
|
+
steps: vec![Step::new(Axis::Self_, NodeTest::Name(qname(name)?))],
|
|
352
|
+
axis_free: false,
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
"comment(" => {
|
|
356
|
+
return Ok(Fragment::Steps {
|
|
357
|
+
steps: vec![Step::new(Axis::Child, NodeTest::Comment)],
|
|
358
|
+
axis_free: true,
|
|
359
|
+
})
|
|
360
|
+
}
|
|
361
|
+
"has(" => return self.has(argument),
|
|
362
|
+
"eq(" => position_is(token(argument)?),
|
|
363
|
+
"nth(" | "nth-of-type(" => match nth {
|
|
364
|
+
Some(nth) => self::nth(nth, false, false)?,
|
|
365
|
+
None => position_is(token(argument)?),
|
|
366
|
+
},
|
|
367
|
+
"nth-child(" => match nth {
|
|
368
|
+
Some(nth) => self::nth(nth, true, false)?,
|
|
369
|
+
None => count_is(Axis::PrecedingSibling, (to_i(argument)? - 1) as f64),
|
|
370
|
+
},
|
|
371
|
+
"nth-last-of-type(" => match nth {
|
|
372
|
+
Some(nth) => self::nth(nth, false, true)?,
|
|
373
|
+
None => match to_i(argument)? - 1 {
|
|
374
|
+
0 => position_is(call(F::Last)),
|
|
375
|
+
index => position_is(Expr::arithmetic(
|
|
376
|
+
Arithmetic::Subtract,
|
|
377
|
+
call(F::Last),
|
|
378
|
+
Expr::Number(index as f64),
|
|
379
|
+
)),
|
|
380
|
+
},
|
|
381
|
+
},
|
|
382
|
+
"nth-last-child(" => match nth {
|
|
383
|
+
Some(nth) => self::nth(nth, true, true)?,
|
|
384
|
+
None => count_is(Axis::FollowingSibling, (to_i(argument)? - 1) as f64),
|
|
385
|
+
},
|
|
386
|
+
"first(" | "first-of-type(" => position_is(Expr::Number(1.0)),
|
|
387
|
+
"last(" | "last-of-type(" => position_is(call(F::Last)),
|
|
388
|
+
"contains(" => Expr::Call(
|
|
389
|
+
F::Contains,
|
|
390
|
+
vec![
|
|
391
|
+
Expr::Path(Path::context_node()),
|
|
392
|
+
function_argument(argument)?,
|
|
393
|
+
],
|
|
394
|
+
),
|
|
395
|
+
"gt(" => Expr::compare(Comparison::Greater, call(F::Position), token(argument)?),
|
|
396
|
+
"only-child(" => Expr::compare(Comparison::Equal, call(F::Last), Expr::Number(1.0)),
|
|
397
|
+
name => {
|
|
398
|
+
let name = name.strip_suffix('(').unwrap_or(name);
|
|
399
|
+
self.custom(name, &function.arguments)?
|
|
400
|
+
}
|
|
401
|
+
};
|
|
402
|
+
Ok(Fragment::Expr(expr))
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/// `has(…)`: `.//` and the first selector. Or `.` and the selector,
|
|
406
|
+
/// when it has nothing before its combinator. The rest are ignored.
|
|
407
|
+
fn has(&mut self, argument: Option<&Argument>) -> Result<Fragment> {
|
|
408
|
+
let Some(Argument::Selector(selector)) = argument else {
|
|
409
|
+
return Err(Failure::Invalid);
|
|
410
|
+
};
|
|
411
|
+
// The visitor checks `value[0].nil?`, which `|name` also passes.
|
|
412
|
+
let bare_no_namespace = selector.rest.is_empty()
|
|
413
|
+
&& matches!(
|
|
414
|
+
&selector.first,
|
|
415
|
+
Simple::Element { name: ElementName { prefix: Some(None), .. }, conditions }
|
|
416
|
+
if conditions.is_empty()
|
|
417
|
+
);
|
|
418
|
+
let mut path = Path::relative(vec![Step::new(Axis::Self_, NodeTest::Node)]);
|
|
419
|
+
let join = match selector.leading {
|
|
420
|
+
None if bare_no_namespace => return Err(Failure::Invalid),
|
|
421
|
+
None => {
|
|
422
|
+
path.steps
|
|
423
|
+
.push(Step::new(Axis::DescendantOrSelf, NodeTest::Node));
|
|
424
|
+
Join::Slash
|
|
425
|
+
}
|
|
426
|
+
Some(Combinator::Descendant) => {
|
|
427
|
+
path.steps
|
|
428
|
+
.push(Step::new(Axis::DescendantOrSelf, NodeTest::Node));
|
|
429
|
+
Join::Slash
|
|
430
|
+
}
|
|
431
|
+
Some(combinator) => combine(&mut path, combinator),
|
|
432
|
+
};
|
|
433
|
+
self.chain(&mut path, join, selector)?;
|
|
434
|
+
Ok(Fragment::Steps {
|
|
435
|
+
steps: path.steps,
|
|
436
|
+
axis_free: false,
|
|
437
|
+
})
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
fn custom(&mut self, name: &str, arguments: &[Argument]) -> Result<Expr> {
|
|
441
|
+
if name.starts_with('-') {
|
|
442
|
+
return Err(SyntaxError(format!("Invalid XPath function name '{name}'")).into());
|
|
443
|
+
}
|
|
444
|
+
let mut expressions = vec![Expr::Path(Path::context_node())];
|
|
445
|
+
for argument in arguments {
|
|
446
|
+
expressions.push(function_argument(Some(argument))?);
|
|
447
|
+
}
|
|
448
|
+
ncname(name)?;
|
|
449
|
+
let site = self.functions.len();
|
|
450
|
+
self.functions.push(name.into());
|
|
451
|
+
Ok(Expr::Custom {
|
|
452
|
+
site,
|
|
453
|
+
arguments: expressions,
|
|
454
|
+
})
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/// `css_class`: the builtin, or the plain XPath 1.0 that the visitor writes
|
|
458
|
+
/// without builtins.
|
|
459
|
+
fn css_class(&self, haystack: Expr, needle: &str) -> Result<Expr> {
|
|
460
|
+
if self.options.builtins {
|
|
461
|
+
return Ok(Expr::Call(F::CssClass, vec![haystack, literal(needle)?]));
|
|
462
|
+
}
|
|
463
|
+
let space = || Expr::Literal(b" ".to_vec());
|
|
464
|
+
let padded = literal(&format!(" {needle} "))?;
|
|
465
|
+
Ok(Expr::Call(
|
|
466
|
+
F::Contains,
|
|
467
|
+
vec![
|
|
468
|
+
Expr::Call(
|
|
469
|
+
F::Concat,
|
|
470
|
+
vec![
|
|
471
|
+
space(),
|
|
472
|
+
Expr::Call(F::NormalizeSpace, vec![haystack]),
|
|
473
|
+
space(),
|
|
474
|
+
],
|
|
475
|
+
),
|
|
476
|
+
padded,
|
|
477
|
+
],
|
|
478
|
+
))
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
fn combine(path: &mut Path, combinator: Combinator) -> Join {
|
|
483
|
+
match combinator {
|
|
484
|
+
Combinator::Child => Join::Slash,
|
|
485
|
+
Combinator::Descendant => {
|
|
486
|
+
path.steps
|
|
487
|
+
.push(Step::new(Axis::DescendantOrSelf, NodeTest::Node));
|
|
488
|
+
Join::Slash
|
|
489
|
+
}
|
|
490
|
+
Combinator::DirectAdjacent => {
|
|
491
|
+
let mut sibling = Step::new(Axis::FollowingSibling, NodeTest::Any);
|
|
492
|
+
sibling.predicates.push(Expr::Number(1.0));
|
|
493
|
+
path.steps.push(sibling);
|
|
494
|
+
Join::Axis(Axis::Self_)
|
|
495
|
+
}
|
|
496
|
+
Combinator::Following => Join::Axis(Axis::FollowingSibling),
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
fn descendants(absolute: bool) -> Path {
|
|
501
|
+
Path {
|
|
502
|
+
absolute,
|
|
503
|
+
steps: vec![Step::new(Axis::DescendantOrSelf, NodeTest::Node)],
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
pub(super) fn is_of_type(condition: &Condition) -> bool {
|
|
508
|
+
let name = match condition {
|
|
509
|
+
Condition::Pseudo(Pseudo::Ident(name)) => name,
|
|
510
|
+
Condition::Pseudo(Pseudo::Function(function)) => &function.name,
|
|
511
|
+
_ => return false,
|
|
512
|
+
};
|
|
513
|
+
[
|
|
514
|
+
"nth-of-type",
|
|
515
|
+
"first-of-type",
|
|
516
|
+
"last-of-type",
|
|
517
|
+
"only-of-type",
|
|
518
|
+
]
|
|
519
|
+
.iter()
|
|
520
|
+
.any(|of_type| name.contains(of_type))
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/// `nth`: compares `an+b` with the position along the axis, or among
|
|
524
|
+
/// the element siblings for the `*-child` forms.
|
|
525
|
+
fn nth(nth: &Nth, child: bool, last: bool) -> Result<Expr> {
|
|
526
|
+
let (a, b) = read_a_and_positive_b(nth)?;
|
|
527
|
+
let position = || match (child, last) {
|
|
528
|
+
(true, false) => Expr::arithmetic(
|
|
529
|
+
Arithmetic::Add,
|
|
530
|
+
count(Axis::PrecedingSibling),
|
|
531
|
+
Expr::Number(1.0),
|
|
532
|
+
),
|
|
533
|
+
(true, true) => Expr::arithmetic(
|
|
534
|
+
Arithmetic::Add,
|
|
535
|
+
count(Axis::FollowingSibling),
|
|
536
|
+
Expr::Number(1.0),
|
|
537
|
+
),
|
|
538
|
+
(false, false) => call(F::Position),
|
|
539
|
+
(false, true) => Expr::arithmetic(
|
|
540
|
+
Arithmetic::Add,
|
|
541
|
+
Expr::arithmetic(Arithmetic::Subtract, call(F::Last), call(F::Position)),
|
|
542
|
+
Expr::Number(1.0),
|
|
543
|
+
),
|
|
544
|
+
};
|
|
545
|
+
let modulo_is_zero = |expr, modulus: i128| {
|
|
546
|
+
Expr::compare(
|
|
547
|
+
Comparison::Equal,
|
|
548
|
+
Expr::arithmetic(Arithmetic::Modulo, expr, Expr::Number(modulus as f64)),
|
|
549
|
+
Expr::Number(0.0),
|
|
550
|
+
)
|
|
551
|
+
};
|
|
552
|
+
if a == 0 {
|
|
553
|
+
return Ok(Expr::compare(
|
|
554
|
+
Comparison::Equal,
|
|
555
|
+
position(),
|
|
556
|
+
Expr::Number(b as f64),
|
|
557
|
+
));
|
|
558
|
+
}
|
|
559
|
+
if b == 0 && a > 0 {
|
|
560
|
+
return Ok(modulo_is_zero(position(), a));
|
|
561
|
+
}
|
|
562
|
+
let comparison = if a < 0 {
|
|
563
|
+
Comparison::LessOrEqual
|
|
564
|
+
} else {
|
|
565
|
+
Comparison::GreaterOrEqual
|
|
566
|
+
};
|
|
567
|
+
let bound = Expr::compare(comparison, position(), Expr::Number(b as f64));
|
|
568
|
+
if a.abs() == 1 {
|
|
569
|
+
return Ok(bound);
|
|
570
|
+
}
|
|
571
|
+
let offset = Expr::arithmetic(Arithmetic::Subtract, position(), Expr::Number(b as f64));
|
|
572
|
+
Ok(Expr::And(vec![bound, modulo_is_zero(offset, a.abs())]))
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
pub(super) fn read_a_and_positive_b(nth: &Nth) -> std::result::Result<(i128, i128), SyntaxError> {
|
|
576
|
+
let a = ruby_to_i(&nth.a);
|
|
577
|
+
match nth.operator.trim() {
|
|
578
|
+
"+" => Ok((a, ruby_to_i(&nth.b))),
|
|
579
|
+
"-" if a == 0 => Ok((a, ruby_to_i(&nth.b).saturating_neg())),
|
|
580
|
+
"-" => Ok((a, a - ruby_modulo(ruby_to_i(&nth.b), a))),
|
|
581
|
+
operator => Err(SyntaxError(format!(
|
|
582
|
+
"expected an+b node to have either + or - as the operator, but is {operator:?}"
|
|
583
|
+
))),
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/// Ruby's `%` on integers. The result takes the sign of the divisor.
|
|
588
|
+
fn ruby_modulo(x: i128, divisor: i128) -> i128 {
|
|
589
|
+
let remainder = x.wrapping_rem(divisor);
|
|
590
|
+
if remainder != 0 && (remainder < 0) != (divisor < 0) {
|
|
591
|
+
remainder + divisor
|
|
592
|
+
} else {
|
|
593
|
+
remainder
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/// Ruby's `String#to_i`: leading whitespace, a sign, then digits. Single
|
|
598
|
+
/// underscores can separate the digits. Anything else gives 0. Above i128,
|
|
599
|
+
/// where Ruby has bignums, it saturates.
|
|
600
|
+
fn ruby_to_i(text: &str) -> i128 {
|
|
601
|
+
let text = text.trim_start_matches([' ', '\t', '\n', '\x0b', '\x0c', '\r']);
|
|
602
|
+
let (sign, digits) = match text.as_bytes().first() {
|
|
603
|
+
Some(b'-') => (-1, &text[1..]),
|
|
604
|
+
Some(b'+') => (1, &text[1..]),
|
|
605
|
+
_ => (1, text),
|
|
606
|
+
};
|
|
607
|
+
let mut value: i128 = 0;
|
|
608
|
+
let mut bytes = digits.bytes().peekable();
|
|
609
|
+
let mut started = false;
|
|
610
|
+
while let Some(byte) = bytes.next() {
|
|
611
|
+
match byte {
|
|
612
|
+
b'0'..=b'9' => {
|
|
613
|
+
started = true;
|
|
614
|
+
value = value
|
|
615
|
+
.saturating_mul(10)
|
|
616
|
+
.saturating_add(i128::from(byte - b'0'));
|
|
617
|
+
}
|
|
618
|
+
b'_' if started && bytes.peek().is_some_and(u8::is_ascii_digit) => {}
|
|
619
|
+
_ => break,
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
sign * value
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
pub(super) fn to_i(argument: Option<&Argument>) -> std::result::Result<i128, SyntaxError> {
|
|
626
|
+
match argument {
|
|
627
|
+
None => Ok(0),
|
|
628
|
+
Some(Argument::Number(text) | Argument::String(text) | Argument::Ident(text)) => {
|
|
629
|
+
Ok(ruby_to_i(text))
|
|
630
|
+
}
|
|
631
|
+
Some(_) => Err(SyntaxError("undefined method 'to_i'".into())),
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/// `xpath_function_argument`, for `contains(…)` and custom pseudo-classes.
|
|
636
|
+
/// The unescaped text of a string becomes a literal. Other tokens are pasted
|
|
637
|
+
/// as `token` gives them.
|
|
638
|
+
fn function_argument(argument: Option<&Argument>) -> Result<Expr> {
|
|
639
|
+
match argument {
|
|
640
|
+
Some(Argument::String(string)) => literal(&unescape_string(&string[1..string.len() - 1])),
|
|
641
|
+
Some(Argument::Attribute(name)) => attribute_path(name),
|
|
642
|
+
Some(Argument::Nth(_)) => Err(SyntaxError("undefined method 'visit_nth'".into()).into()),
|
|
643
|
+
argument => token(argument),
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
fn token(argument: Option<&Argument>) -> Result<Expr> {
|
|
648
|
+
match argument {
|
|
649
|
+
Some(Argument::Number(number)) => number
|
|
650
|
+
.parse()
|
|
651
|
+
.map(Expr::Number)
|
|
652
|
+
.map_err(|_| Failure::Invalid),
|
|
653
|
+
Some(Argument::String(string)) => {
|
|
654
|
+
let quote = string.chars().next().expect("a quoted string");
|
|
655
|
+
let text = &string[1..string.len() - 1];
|
|
656
|
+
if text.contains(quote) {
|
|
657
|
+
return Err(Failure::Invalid);
|
|
658
|
+
}
|
|
659
|
+
literal(text)
|
|
660
|
+
}
|
|
661
|
+
// A name is a child path. A leading `-` negates it.
|
|
662
|
+
Some(Argument::Ident(ident)) => match ident.strip_prefix('-') {
|
|
663
|
+
Some(name) => Ok(Expr::arithmetic(
|
|
664
|
+
Arithmetic::Subtract,
|
|
665
|
+
Expr::Number(0.0),
|
|
666
|
+
child_path(name)?,
|
|
667
|
+
)),
|
|
668
|
+
None => child_path(ident),
|
|
669
|
+
},
|
|
670
|
+
// The visitor writes the `#to_s` of a node, or nothing.
|
|
671
|
+
Some(Argument::Nth(_) | Argument::Attribute(_) | Argument::Selector(_)) | None => {
|
|
672
|
+
Err(Failure::Invalid)
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
fn child_path(name: &str) -> Result<Expr> {
|
|
678
|
+
Ok(Expr::Path(Path::relative(vec![Step::new(
|
|
679
|
+
Axis::Child,
|
|
680
|
+
NodeTest::Name(qname(name)?),
|
|
681
|
+
)])))
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
fn attribute_path(name: &AttributeName) -> Result<Expr> {
|
|
685
|
+
Ok(Expr::Path(Path::relative(vec![attribute_step(name)?])))
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
/// `visit_attrib_name`: `@name`, `@prefix:name`, or, for a name that XPath
|
|
689
|
+
/// cannot write, `@*[namespace-uri()='' and name()='…']`.
|
|
690
|
+
fn attribute_step(name: &AttributeName) -> Result<Step> {
|
|
691
|
+
let local = name.local.as_str();
|
|
692
|
+
if let Some(prefix) = &name.prefix {
|
|
693
|
+
if !xpath_name(prefix) || !xpath_name(local) {
|
|
694
|
+
let message = format!("Invalid attribute name '{prefix}|{local}'");
|
|
695
|
+
return Err(SyntaxError(message).into());
|
|
696
|
+
}
|
|
697
|
+
let name = QName {
|
|
698
|
+
prefix: Some(ncname(prefix)?.into()),
|
|
699
|
+
local: ncname(local)?.into(),
|
|
700
|
+
};
|
|
701
|
+
return Ok(Step::new(Axis::Attribute, NodeTest::Name(name)));
|
|
702
|
+
}
|
|
703
|
+
if xpath_name(local) {
|
|
704
|
+
let name = QName {
|
|
705
|
+
prefix: None,
|
|
706
|
+
local: ncname(local)?.into(),
|
|
707
|
+
};
|
|
708
|
+
return Ok(Step::new(Axis::Attribute, NodeTest::Name(name)));
|
|
709
|
+
}
|
|
710
|
+
let mut step = Step::new(Axis::Attribute, NodeTest::Any);
|
|
711
|
+
step.predicates.push(Expr::And(vec![
|
|
712
|
+
Expr::compare(
|
|
713
|
+
Comparison::Equal,
|
|
714
|
+
call(F::NamespaceUri),
|
|
715
|
+
Expr::Literal(Vec::new()),
|
|
716
|
+
),
|
|
717
|
+
Expr::compare(Comparison::Equal, call(F::Name), literal(local)?),
|
|
718
|
+
]));
|
|
719
|
+
Ok(step)
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
fn attribute(name: &str) -> Expr {
|
|
723
|
+
Expr::Path(Path::relative(vec![Step::new(
|
|
724
|
+
Axis::Attribute,
|
|
725
|
+
NodeTest::Name(QName {
|
|
726
|
+
prefix: None,
|
|
727
|
+
local: name.into(),
|
|
728
|
+
}),
|
|
729
|
+
)]))
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
fn call(function: F) -> Expr {
|
|
733
|
+
Expr::Call(function, Vec::new())
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
fn position_is(expr: Expr) -> Expr {
|
|
737
|
+
Expr::compare(Comparison::Equal, call(F::Position), expr)
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
fn count(axis: Axis) -> Expr {
|
|
741
|
+
Expr::Call(
|
|
742
|
+
F::Count,
|
|
743
|
+
vec![Expr::Path(Path::relative(vec![Step::new(
|
|
744
|
+
axis,
|
|
745
|
+
NodeTest::Any,
|
|
746
|
+
)]))],
|
|
747
|
+
)
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
fn count_is(axis: Axis, n: f64) -> Expr {
|
|
751
|
+
Expr::compare(Comparison::Equal, count(axis), Expr::Number(n))
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
fn children() -> Expr {
|
|
755
|
+
Expr::Path(Path::relative(vec![Step::new(Axis::Child, NodeTest::Node)]))
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/// `xpath_string_literal`: the text as an XPath string. It uses `concat()`
|
|
759
|
+
/// when the text has both quotes. libxml2 rejects a character that XML does
|
|
760
|
+
/// not allow.
|
|
761
|
+
fn literal(text: &str) -> Result<Expr> {
|
|
762
|
+
check_literal(text)?;
|
|
763
|
+
Ok(Expr::Literal(text.as_bytes().to_vec()))
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
fn check_literal(text: &str) -> Result<()> {
|
|
767
|
+
if text.chars().all(is_xml_char) {
|
|
768
|
+
Ok(())
|
|
769
|
+
} else {
|
|
770
|
+
Err(Failure::Invalid)
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/// The `XPATH_NAME` of the visitor: an NCName as far as ASCII goes. The XPath
|
|
775
|
+
/// parser handles other characters.
|
|
776
|
+
pub(super) fn xpath_name(name: &str) -> bool {
|
|
777
|
+
let mut chars = name.chars();
|
|
778
|
+
chars
|
|
779
|
+
.next()
|
|
780
|
+
.is_some_and(|c| c == '_' || c.is_ascii_alphabetic() || !c.is_ascii())
|
|
781
|
+
&& chars.all(|c| matches!(c, '_' | '.' | '-') || c.is_ascii_alphanumeric() || !c.is_ascii())
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
fn qname(name: &str) -> Result<QName> {
|
|
785
|
+
Ok(match name.split_once(':') {
|
|
786
|
+
Some((prefix, local)) => QName {
|
|
787
|
+
prefix: Some(ncname(prefix)?.into()),
|
|
788
|
+
local: ncname(local)?.into(),
|
|
789
|
+
},
|
|
790
|
+
None => QName {
|
|
791
|
+
prefix: None,
|
|
792
|
+
local: ncname(name)?.into(),
|
|
793
|
+
},
|
|
794
|
+
})
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/// XML's NCName, as the XPath parser of libxml2 reads names.
|
|
798
|
+
fn ncname(name: &str) -> Result<&str> {
|
|
799
|
+
let mut chars = name.chars();
|
|
800
|
+
let valid = chars.next().is_some_and(is_name_start) && chars.all(is_name_char);
|
|
801
|
+
if valid {
|
|
802
|
+
Ok(name)
|
|
803
|
+
} else {
|
|
804
|
+
Err(Failure::Invalid)
|
|
805
|
+
}
|
|
806
|
+
}
|