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.
Files changed (116) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +5 -0
  3. data/Cargo.lock +520 -0
  4. data/Cargo.toml +11 -0
  5. data/LICENSE-NOKOGIRI.md +15 -0
  6. data/LICENSE.txt +21 -0
  7. data/README.md +144 -0
  8. data/crates/lobzique-core/Cargo.toml +14 -0
  9. data/crates/lobzique-core/src/css/mod.rs +127 -0
  10. data/crates/lobzique-core/src/css/parser.rs +805 -0
  11. data/crates/lobzique-core/src/css/tables.rs +282 -0
  12. data/crates/lobzique-core/src/css/tests.rs +476 -0
  13. data/crates/lobzique-core/src/css/tokenizer.rs +215 -0
  14. data/crates/lobzique-core/src/css/translate.rs +806 -0
  15. data/crates/lobzique-core/src/css/write.rs +370 -0
  16. data/crates/lobzique-core/src/dom/attribute.rs +144 -0
  17. data/crates/lobzique-core/src/dom/check.rs +160 -0
  18. data/crates/lobzique-core/src/dom/copy.rs +229 -0
  19. data/crates/lobzique-core/src/dom/mod.rs +298 -0
  20. data/crates/lobzique-core/src/dom/namespace.rs +134 -0
  21. data/crates/lobzique-core/src/dom/node.rs +129 -0
  22. data/crates/lobzique-core/src/dom/path.rs +116 -0
  23. data/crates/lobzique-core/src/dom/reparent.rs +308 -0
  24. data/crates/lobzique-core/src/dom/tests.rs +1057 -0
  25. data/crates/lobzique-core/src/dom/text.rs +159 -0
  26. data/crates/lobzique-core/src/dom/tree.rs +446 -0
  27. data/crates/lobzique-core/src/html5/mod.rs +28 -0
  28. data/crates/lobzique-core/src/html5/parse.rs +838 -0
  29. data/crates/lobzique-core/src/html5/serialize.rs +181 -0
  30. data/crates/lobzique-core/src/html5/tests.rs +548 -0
  31. data/crates/lobzique-core/src/lib.rs +12 -0
  32. data/crates/lobzique-core/src/work.rs +26 -0
  33. data/crates/lobzique-core/src/xml/mod.rs +8 -0
  34. data/crates/lobzique-core/src/xml/serialize.rs +681 -0
  35. data/crates/lobzique-core/src/xml/tests.rs +174 -0
  36. data/crates/lobzique-core/src/xpath/ast.rs +415 -0
  37. data/crates/lobzique-core/src/xpath/chars.rs +139 -0
  38. data/crates/lobzique-core/src/xpath/eval.rs +1305 -0
  39. data/crates/lobzique-core/src/xpath/mod.rs +118 -0
  40. data/crates/lobzique-core/src/xpath/parse.rs +729 -0
  41. data/crates/lobzique-core/src/xpath/tests.rs +921 -0
  42. data/ext/lobzique/Cargo.toml +22 -0
  43. data/ext/lobzique/build.rs +5 -0
  44. data/ext/lobzique/clippy.toml +15 -0
  45. data/ext/lobzique/extconf.rb +6 -0
  46. data/ext/lobzique/src/css/mod.rs +9 -0
  47. data/ext/lobzique/src/css/parser.rs +44 -0
  48. data/ext/lobzique/src/css/selector.rs +101 -0
  49. data/ext/lobzique/src/html4/document.rs +31 -0
  50. data/ext/lobzique/src/html4/mod.rs +7 -0
  51. data/ext/lobzique/src/html5/mod.rs +16 -0
  52. data/ext/lobzique/src/html5ever.rs +278 -0
  53. data/ext/lobzique/src/lib.rs +45 -0
  54. data/ext/lobzique/src/support.rs +156 -0
  55. data/ext/lobzique/src/xml/attr.rs +27 -0
  56. data/ext/lobzique/src/xml/cdata.rs +33 -0
  57. data/ext/lobzique/src/xml/comment.rs +34 -0
  58. data/ext/lobzique/src/xml/document.rs +199 -0
  59. data/ext/lobzique/src/xml/document_fragment.rs +27 -0
  60. data/ext/lobzique/src/xml/dtd.rs +37 -0
  61. data/ext/lobzique/src/xml/mod.rs +44 -0
  62. data/ext/lobzique/src/xml/namespace.rs +56 -0
  63. data/ext/lobzique/src/xml/node.rs +944 -0
  64. data/ext/lobzique/src/xml/node_set.rs +20 -0
  65. data/ext/lobzique/src/xml/syntax_error.rs +33 -0
  66. data/ext/lobzique/src/xml/text.rs +44 -0
  67. data/ext/lobzique/src/xml/xpath_context.rs +305 -0
  68. data/lib/lobzique/action_text.rb +29 -0
  69. data/lib/lobzique/class_resolver.rb +33 -0
  70. data/lib/lobzique/css/selector_cache.rb +36 -0
  71. data/lib/lobzique/css/syntax_error.rb +12 -0
  72. data/lib/lobzique/css/xpath_visitor.rb +60 -0
  73. data/lib/lobzique/css.rb +57 -0
  74. data/lib/lobzique/extension.rb +31 -0
  75. data/lib/lobzique/html.rb +14 -0
  76. data/lib/lobzique/html4/document.rb +235 -0
  77. data/lib/lobzique/html4/document_fragment.rb +75 -0
  78. data/lib/lobzique/html4/encoding_reader.rb +374 -0
  79. data/lib/lobzique/html4.rb +35 -0
  80. data/lib/lobzique/html5/document.rb +106 -0
  81. data/lib/lobzique/html5/document_fragment.rb +113 -0
  82. data/lib/lobzique/html5/node.rb +66 -0
  83. data/lib/lobzique/html5.rb +92 -0
  84. data/lib/lobzique/html5ever.rb +14 -0
  85. data/lib/lobzique/rails_dom_testing.rb +95 -0
  86. data/lib/lobzique/sanitizer/concerns.rb +110 -0
  87. data/lib/lobzique/sanitizer/document.rb +14 -0
  88. data/lib/lobzique/sanitizer/document_fragment.rb +12 -0
  89. data/lib/lobzique/sanitizer/escape_raw_text_in_select.rb +31 -0
  90. data/lib/lobzique/sanitizer/scrubbers.rb +46 -0
  91. data/lib/lobzique/sanitizer.rb +96 -0
  92. data/lib/lobzique/syntax_error.rb +8 -0
  93. data/lib/lobzique/version.rb +6 -0
  94. data/lib/lobzique/xml/attr.rb +23 -0
  95. data/lib/lobzique/xml/cdata.rb +13 -0
  96. data/lib/lobzique/xml/character_data.rb +11 -0
  97. data/lib/lobzique/xml/document.rb +149 -0
  98. data/lib/lobzique/xml/document_fragment.rb +109 -0
  99. data/lib/lobzique/xml/dtd.rb +28 -0
  100. data/lib/lobzique/xml/namespace.rb +19 -0
  101. data/lib/lobzique/xml/node/save_options.rb +52 -0
  102. data/lib/lobzique/xml/node.rb +629 -0
  103. data/lib/lobzique/xml/node_set.rb +329 -0
  104. data/lib/lobzique/xml/parse_options.rb +89 -0
  105. data/lib/lobzique/xml/pp/character_data.rb +22 -0
  106. data/lib/lobzique/xml/pp/node.rb +73 -0
  107. data/lib/lobzique/xml/pp.rb +6 -0
  108. data/lib/lobzique/xml/searchable.rb +123 -0
  109. data/lib/lobzique/xml/syntax_error.rb +77 -0
  110. data/lib/lobzique/xml/text.rb +14 -0
  111. data/lib/lobzique/xml/xpath/syntax_error.rb +20 -0
  112. data/lib/lobzique/xml/xpath.rb +16 -0
  113. data/lib/lobzique/xml/xpath_context.rb +27 -0
  114. data/lib/lobzique/xml.rb +22 -0
  115. data/lib/lobzique.rb +15 -0
  116. metadata +177 -0
@@ -0,0 +1,1305 @@
1
+ //! Evaluation as libxml2 does it: XPath 1.0 value types and comparisons, node
2
+ //! sets in document order, positions along the axis of each step, and errors
3
+ //! where libxml2 raises them.
4
+ //!
5
+ //! Custom functions are Ruby methods. They cannot run while the arena
6
+ //! is borrowed. [`evaluate`] takes the result of each call from `answers`.
7
+ //! If a result is missing, it records the call, uses an empty node set
8
+ //! and continues. The caller then runs the recorded calls with the borrow
9
+ //! released and evaluates again, until no result is missing. A result can
10
+ //! be the error that the call raises, for example when the handler has no such
11
+ //! function. That error is raised only when an evaluation with all results
12
+ //! reaches it. The empty node sets can cause calls that libxml2 never makes.
13
+
14
+ use super::ast::{
15
+ Arithmetic, Axis, Comparison, Expr, Filter, Function, NodeTest, Operator, Path, QName, Step,
16
+ };
17
+ use super::chars::is_blank;
18
+ use super::{Error, Query, NOKOGIRI_BUILTIN_URI, NOKOGIRI_URI};
19
+ use crate::dom::{Document, DocumentKind, NodeId, NodeKind};
20
+ use std::borrow::Cow;
21
+ use std::cell::RefCell;
22
+ use std::collections::{HashMap, HashSet};
23
+ use std::hash::{Hash, Hasher};
24
+
25
+ #[derive(Clone, Debug, PartialEq)]
26
+ pub enum Value<'a> {
27
+ /// In document order, without duplicates.
28
+ NodeSet(Vec<NodeId>),
29
+ Boolean(bool),
30
+ Number(f64),
31
+ String(Cow<'a, [u8]>),
32
+ }
33
+
34
+ impl Value<'_> {
35
+ pub fn into_owned(self) -> Value<'static> {
36
+ match self {
37
+ Value::NodeSet(nodes) => Value::NodeSet(nodes),
38
+ Value::Boolean(b) => Value::Boolean(b),
39
+ Value::Number(n) => Value::Number(n),
40
+ Value::String(s) => Value::String(Cow::Owned(s.into_owned())),
41
+ }
42
+ }
43
+ }
44
+
45
+ pub type Answer = Result<Value<'static>, Error>;
46
+
47
+ /// A custom function call that the caller must make. It has a key
48
+ /// for its result: the same node can reach a call site with different
49
+ /// arguments, for example `position()` from different start nodes.
50
+ #[derive(Clone, Debug)]
51
+ pub struct Call {
52
+ pub site: usize,
53
+ pub node: NodeId,
54
+ pub arguments: Vec<Value<'static>>,
55
+ }
56
+
57
+ impl Call {
58
+ /// Numbers compare by bit pattern, so `NaN` finds its result and 0 and -0
59
+ /// stay apart. All `NaN`s are one key: arithmetic does not specify the sign
60
+ /// and payload of a `NaN`, so `0 div 0` can differ between runs.
61
+ fn key(&self) -> (usize, NodeId, impl Iterator<Item = ArgumentKey<'_>>) {
62
+ let arguments = self.arguments.iter().map(|value| match value {
63
+ Value::NodeSet(nodes) => ArgumentKey::NodeSet(nodes),
64
+ Value::Boolean(b) => ArgumentKey::Boolean(*b),
65
+ Value::Number(n) if n.is_nan() => ArgumentKey::Number(f64::NAN.to_bits()),
66
+ Value::Number(n) => ArgumentKey::Number(n.to_bits()),
67
+ Value::String(s) => ArgumentKey::String(s),
68
+ });
69
+ (self.site, self.node, arguments)
70
+ }
71
+ }
72
+
73
+ #[derive(PartialEq, Eq, Hash)]
74
+ enum ArgumentKey<'a> {
75
+ NodeSet(&'a [NodeId]),
76
+ Boolean(bool),
77
+ Number(u64),
78
+ String(&'a [u8]),
79
+ }
80
+
81
+ impl PartialEq for Call {
82
+ fn eq(&self, other: &Self) -> bool {
83
+ let (site, node, arguments) = self.key();
84
+ let (other_site, other_node, other_arguments) = other.key();
85
+ site == other_site && node == other_node && arguments.eq(other_arguments)
86
+ }
87
+ }
88
+
89
+ impl Eq for Call {}
90
+
91
+ impl Hash for Call {
92
+ fn hash<H: Hasher>(&self, state: &mut H) {
93
+ let (site, node, arguments) = self.key();
94
+ site.hash(state);
95
+ node.hash(state);
96
+ self.arguments.len().hash(state);
97
+ arguments.for_each(|argument| argument.hash(state));
98
+ }
99
+ }
100
+
101
+ #[derive(Debug, PartialEq)]
102
+ pub enum Outcome {
103
+ Value(Value<'static>),
104
+ Calls(Vec<Call>),
105
+ }
106
+
107
+ /// Evaluates `query` at `context`. `namespaces` binds prefixes in addition
108
+ /// to the ones Nokogiri always binds. `variables` has the variable values
109
+ /// as strings. `answers` has the results of the custom calls made so far.
110
+ pub fn evaluate(
111
+ document: &Document,
112
+ query: &Query,
113
+ context: NodeId,
114
+ namespaces: &HashMap<String, String>,
115
+ variables: &HashMap<String, Vec<u8>>,
116
+ answers: &HashMap<Call, Answer>,
117
+ ) -> Result<Outcome, Error> {
118
+ // libxml2 resolves a prefix when it evaluates the step. Resolving
119
+ // all prefixes first differs only when libxml2 never reaches that step.
120
+ check_prefixes(&query.expr, namespaces)?;
121
+ let evaluator = Evaluator {
122
+ document,
123
+ query,
124
+ namespaces,
125
+ variables,
126
+ answers,
127
+ calls: RefCell::new(Vec::new()),
128
+ noted: RefCell::new(HashSet::new()),
129
+ root: document.ancestors(context).last().unwrap_or(context),
130
+ ids: RefCell::new(None),
131
+ };
132
+ let value = evaluator.expr(
133
+ &query.expr,
134
+ Context {
135
+ node: context,
136
+ position: 1,
137
+ size: 1,
138
+ },
139
+ );
140
+ // libxml2 makes the calls it reaches before an error.
141
+ let calls = evaluator.calls.into_inner();
142
+ if !calls.is_empty() {
143
+ return Ok(Outcome::Calls(calls));
144
+ }
145
+ Ok(Outcome::Value(value?.into_owned()))
146
+ }
147
+
148
+ const XML_NAMESPACE: &str = "http://www.w3.org/XML/1998/namespace";
149
+
150
+ fn lookup<'n>(namespaces: &'n HashMap<String, String>, prefix: &str) -> Option<&'n str> {
151
+ if let Some(href) = namespaces.get(prefix) {
152
+ return Some(href);
153
+ }
154
+ match prefix {
155
+ "xml" => Some(XML_NAMESPACE),
156
+ "nokogiri" => Some(NOKOGIRI_URI),
157
+ "nokogiri-builtin" => Some(NOKOGIRI_BUILTIN_URI),
158
+ _ => None,
159
+ }
160
+ }
161
+
162
+ fn check_prefixes(expr: &Expr, namespaces: &HashMap<String, String>) -> Result<(), Error> {
163
+ let mut result = Ok(());
164
+ expr.for_each_step(&mut |step| {
165
+ let prefix = match &step.test {
166
+ NodeTest::Name(QName {
167
+ prefix: Some(prefix),
168
+ ..
169
+ })
170
+ | NodeTest::AnyIn(prefix) => prefix,
171
+ _ => return,
172
+ };
173
+ if lookup(namespaces, prefix).is_none() {
174
+ result = Err(Error::UndefinedNamespacePrefix);
175
+ }
176
+ });
177
+ result
178
+ }
179
+
180
+ #[derive(Clone, Copy)]
181
+ struct Context {
182
+ node: NodeId,
183
+ position: usize,
184
+ size: usize,
185
+ }
186
+
187
+ type Eval<T> = Result<T, Error>;
188
+
189
+ struct Evaluator<'a> {
190
+ document: &'a Document,
191
+ query: &'a Query,
192
+ namespaces: &'a HashMap<String, String>,
193
+ variables: &'a HashMap<String, Vec<u8>>,
194
+ answers: &'a HashMap<Call, Answer>,
195
+ calls: RefCell<Vec<Call>>,
196
+ noted: RefCell<HashSet<Call>>,
197
+ /// Root of the tree of the context node. `id()` searches it after
198
+ /// the document.
199
+ root: NodeId,
200
+ /// The element of each ID. Built when `id()` first needs it.
201
+ ids: RefCell<Option<HashMap<Vec<u8>, NodeId>>>,
202
+ }
203
+
204
+ impl<'a> Evaluator<'a> {
205
+ fn expr<'q>(&self, expr: &'q Expr, context: Context) -> Eval<Value<'q>> {
206
+ Ok(match expr {
207
+ Expr::Or(list) => {
208
+ for expr in list {
209
+ if self.boolean(expr, context)? {
210
+ return Ok(Value::Boolean(true));
211
+ }
212
+ }
213
+ Value::Boolean(false)
214
+ }
215
+ Expr::And(list) => {
216
+ for expr in list {
217
+ if !self.boolean(expr, context)? {
218
+ return Ok(Value::Boolean(false));
219
+ }
220
+ }
221
+ Value::Boolean(true)
222
+ }
223
+ Expr::Operation(first, rest) => {
224
+ let mut value = self.expr(first, context)?;
225
+ for (operator, operand) in rest {
226
+ let right = self.expr(operand, context)?;
227
+ value = match *operator {
228
+ Operator::Compare(comparison) => {
229
+ Value::Boolean(self.compare(comparison, &value, &right))
230
+ }
231
+ Operator::Arithmetic(operator) => {
232
+ let (left, right) = (self.number(&value), self.number(&right));
233
+ Value::Number(match operator {
234
+ Arithmetic::Add => left + right,
235
+ Arithmetic::Subtract => left - right,
236
+ Arithmetic::Multiply => left * right,
237
+ Arithmetic::Divide => left / right,
238
+ // Same as C's fmod.
239
+ Arithmetic::Modulo => left % right,
240
+ })
241
+ }
242
+ };
243
+ }
244
+ value
245
+ }
246
+ Expr::Negate(expr) => Value::Number(-self.number(&self.expr(expr, context)?)),
247
+ Expr::Number(n) => Value::Number(*n),
248
+ Expr::Literal(s) => Value::String(Cow::Borrowed(s)),
249
+ Expr::Variable(name) => self.variable(name)?,
250
+ Expr::Path(path) => Value::NodeSet(self.path(path, context.node)?),
251
+ Expr::Filter(filter) => Value::NodeSet(self.filter_expr(filter, context)?),
252
+ Expr::Union(list) => self.union(list, context)?,
253
+ Expr::Call(function, arguments) => self.call(*function, arguments, context)?,
254
+ Expr::Custom { site, arguments } => self.custom(*site, arguments, context)?,
255
+ })
256
+ }
257
+
258
+ fn variable(&self, name: &QName) -> Eval<Value<'static>> {
259
+ // Nokogiri binds variables without a namespace.
260
+ if let Some(prefix) = &name.prefix {
261
+ self.resolve(prefix)?;
262
+ return Err(Error::UndefinedVariable);
263
+ }
264
+ let value = self
265
+ .variables
266
+ .get(&name.local)
267
+ .ok_or(Error::UndefinedVariable)?;
268
+ Ok(Value::String(Cow::Owned(value.clone())))
269
+ }
270
+
271
+ fn resolve(&self, prefix: &str) -> Eval<&'a str> {
272
+ lookup(self.namespaces, prefix).ok_or(Error::UndefinedNamespacePrefix)
273
+ }
274
+
275
+ /// libxml2 merges each operand into the previous ones. It checks
276
+ /// that both are node sets after it evaluates the second.
277
+ fn union<'q>(&self, list: &'q [Expr], context: Context) -> Eval<Value<'q>> {
278
+ let Some((first, rest)) = list.split_first() else {
279
+ return Ok(Value::NodeSet(Vec::new()));
280
+ };
281
+ let mut value = self.expr(first, context)?;
282
+ for expr in rest {
283
+ let next = self.expr(expr, context)?;
284
+ let (Value::NodeSet(mut nodes), Value::NodeSet(more)) = (value, next) else {
285
+ return Err(Error::InvalidType);
286
+ };
287
+ nodes.extend(more);
288
+ value = Value::NodeSet(nodes);
289
+ }
290
+ if let Value::NodeSet(nodes) = &mut value {
291
+ if !rest.is_empty() {
292
+ self.document.sort_in_document_order(nodes);
293
+ }
294
+ }
295
+ Ok(value)
296
+ }
297
+
298
+ fn filter_expr(&self, filter: &Filter, context: Context) -> Eval<Vec<NodeId>> {
299
+ let Value::NodeSet(mut nodes) = self.expr(&filter.primary, context)? else {
300
+ return Err(Error::InvalidType);
301
+ };
302
+ for predicate in &filter.predicates {
303
+ nodes = self.filter(nodes, predicate)?;
304
+ }
305
+ self.steps(&filter.steps, nodes)
306
+ }
307
+
308
+ /// libxml2 evaluates the arguments, then checks their number, then
309
+ /// their types.
310
+ fn call<'q>(
311
+ &self,
312
+ function: Function,
313
+ arguments: &'q [Expr],
314
+ context: Context,
315
+ ) -> Eval<Value<'q>> {
316
+ // To know if a path finds a node, only the first is necessary.
317
+ if let (Function::Not, [Expr::Path(path)]) = (function, arguments) {
318
+ return Ok(Value::Boolean(!self.exists(path, context.node)?));
319
+ }
320
+ let mut values = Vec::with_capacity(arguments.len());
321
+ for argument in arguments {
322
+ values.push(self.expr(argument, context)?);
323
+ }
324
+ self.apply(function, values, context)
325
+ }
326
+
327
+ fn custom<'q>(&self, site: usize, arguments: &'q [Expr], context: Context) -> Eval<Value<'q>> {
328
+ let mut values = Vec::with_capacity(arguments.len());
329
+ for argument in arguments {
330
+ values.push(self.expr(argument, context)?);
331
+ }
332
+ let name = self.query.function(site);
333
+ if let Some(prefix) = &name.prefix {
334
+ let href = self.resolve(prefix)?;
335
+ if let Some(function) = Function::in_namespace(href, &name.local) {
336
+ return self.apply(function, values, context);
337
+ }
338
+ }
339
+ let call = Call {
340
+ site,
341
+ node: context.node,
342
+ arguments: values.into_iter().map(Value::into_owned).collect(),
343
+ };
344
+ if let Some(answer) = self.answers.get(&call) {
345
+ return answer.clone();
346
+ }
347
+ if self.noted.borrow_mut().insert(call.clone()) {
348
+ self.calls.borrow_mut().push(call);
349
+ }
350
+ Ok(Value::NodeSet(Vec::new()))
351
+ }
352
+
353
+ fn apply<'q>(
354
+ &self,
355
+ function: Function,
356
+ mut values: Vec<Value<'q>>,
357
+ context: Context,
358
+ ) -> Eval<Value<'q>> {
359
+ use Function::*;
360
+ let count = values.len();
361
+ let arity = match function {
362
+ Last | Position | True | False => count == 0,
363
+ LocalName | NamespaceUri | Name | String | StringLength | NormalizeSpace | Number => {
364
+ count <= 1
365
+ }
366
+ Count | Id | Boolean | Not | Lang | Sum | Floor | Ceiling | Round | LocalNameIs => {
367
+ count == 1
368
+ }
369
+ StartsWith | Contains | SubstringBefore | SubstringAfter | EndsWith | CssClass
370
+ | EscapeUri => count == 2,
371
+ Substring => count == 2 || count == 3,
372
+ Concat => count >= 2,
373
+ Translate => count == 3,
374
+ };
375
+ if !arity {
376
+ return Err(Error::InvalidArity);
377
+ }
378
+ // A missing argument becomes the context node.
379
+ let node_or_context = |values: Vec<Value<'q>>| match values.into_iter().next() {
380
+ None => Ok(Some(context.node)),
381
+ Some(Value::NodeSet(nodes)) => Ok(nodes.first().copied()),
382
+ Some(_) => Err(Error::InvalidType),
383
+ };
384
+ let string_or_context = |values: &mut Vec<Value<'q>>| match values.pop() {
385
+ None => Cow::Owned(self.string_value(context.node)),
386
+ Some(value) => self.string(value),
387
+ };
388
+ let strings = |values: Vec<Value<'q>>| -> Vec<Cow<'q, [u8]>> {
389
+ values.into_iter().map(|value| self.string(value)).collect()
390
+ };
391
+ let boolean = |value: Value| Value::Boolean(self.truthy(&value));
392
+ let number = |values: Vec<Value>| self.number(&values[0]);
393
+ Ok(match function {
394
+ Last => Value::Number(context.size as f64),
395
+ Position => Value::Number(context.position as f64),
396
+ Count => match &values[0] {
397
+ Value::NodeSet(nodes) => Value::Number(nodes.len() as f64),
398
+ _ => return Err(Error::InvalidType),
399
+ },
400
+ Id => Value::NodeSet(self.id(values.pop().expect("one argument"))),
401
+ LocalName => {
402
+ let name = node_or_context(values)?.map(|node| self.local_name_of(node));
403
+ Value::String(Cow::Owned(name.unwrap_or_default()))
404
+ }
405
+ NamespaceUri => {
406
+ let href =
407
+ node_or_context(values)?.and_then(|node| match self.document.node_kind(node) {
408
+ NodeKind::Element(_) | NodeKind::Attribute(_) => self
409
+ .document
410
+ .namespace(node)
411
+ .map(|ns| ns.href.as_bytes().to_vec()),
412
+ _ => None,
413
+ });
414
+ Value::String(Cow::Owned(href.unwrap_or_default()))
415
+ }
416
+ Name => {
417
+ let name = node_or_context(values)?.map(|node| self.qualified_name(node));
418
+ Value::String(Cow::Owned(name.unwrap_or_default()))
419
+ }
420
+ String => Value::String(string_or_context(&mut values)),
421
+ StringLength => {
422
+ let string = string_or_context(&mut values);
423
+ Value::Number(utf8_length(&string) as f64)
424
+ }
425
+ NormalizeSpace => {
426
+ let string = string_or_context(&mut values);
427
+ let words: Vec<&[u8]> = string
428
+ .split(|&byte| is_blank(byte))
429
+ .filter(|word| !word.is_empty())
430
+ .collect();
431
+ Value::String(Cow::Owned(words.join(&b' ')))
432
+ }
433
+ Number if values.is_empty() => {
434
+ Value::Number(string_to_number(&self.string_value(context.node)))
435
+ }
436
+ Number => Value::Number(number(values)),
437
+ Concat => Value::String(Cow::Owned(strings(values).concat())),
438
+ StartsWith => {
439
+ let [haystack, needle] = two(strings(values));
440
+ Value::Boolean(haystack.starts_with(&needle))
441
+ }
442
+ EndsWith => {
443
+ let [haystack, needle] = two(strings(values));
444
+ Value::Boolean(haystack.ends_with(&needle))
445
+ }
446
+ Contains => {
447
+ let [haystack, needle] = two(strings(values));
448
+ Value::Boolean(find(&haystack, &needle).is_some())
449
+ }
450
+ SubstringBefore => {
451
+ let [string, needle] = two(strings(values));
452
+ let before = find(&string, &needle).map_or(&[][..], |at| &string[..at]);
453
+ Value::String(Cow::Owned(before.to_vec()))
454
+ }
455
+ SubstringAfter => {
456
+ let [string, needle] = two(strings(values));
457
+ let after =
458
+ find(&string, &needle).map_or(&[][..], |at| &string[at + needle.len()..]);
459
+ Value::String(Cow::Owned(after.to_vec()))
460
+ }
461
+ Substring => {
462
+ let length = (count == 3).then(|| self.number(&values[2]));
463
+ let start = self.number(&values[1]);
464
+ let string = self.string(values.swap_remove(0));
465
+ Value::String(Cow::Owned(substring(&string, start, length)))
466
+ }
467
+ Translate => {
468
+ let mut strings = strings(values).into_iter();
469
+ let (string, from, to) = (
470
+ strings.next().expect("three"),
471
+ strings.next().expect("three"),
472
+ strings.next().expect("three"),
473
+ );
474
+ Value::String(Cow::Owned(translate(&string, &from, &to)))
475
+ }
476
+ Boolean => boolean(values.pop().expect("one argument")),
477
+ Not => Value::Boolean(!self.truthy(&values[0])),
478
+ True => Value::Boolean(true),
479
+ False => Value::Boolean(false),
480
+ Lang => {
481
+ let lang = self.string(values.pop().expect("one argument"));
482
+ Value::Boolean(self.lang(context.node, &lang))
483
+ }
484
+ Sum => match &values[0] {
485
+ Value::NodeSet(nodes) => Value::Number(
486
+ nodes
487
+ .iter()
488
+ .map(|&node| string_to_number(&self.string_value(node)))
489
+ // `sum` of no floats is -0.
490
+ .fold(0.0, |sum, n| sum + n),
491
+ ),
492
+ _ => return Err(Error::InvalidType),
493
+ },
494
+ Floor => Value::Number(number(values).floor()),
495
+ Ceiling => Value::Number(number(values).ceil()),
496
+ Round => Value::Number(round(number(values))),
497
+ CssClass => {
498
+ let [haystack, needle] = two(strings(values));
499
+ Value::Boolean(css_class(&haystack, &needle))
500
+ }
501
+ LocalNameIs => {
502
+ let name = self.string(values.pop().expect("one argument"));
503
+ Value::Boolean(libxml2_name(self.document, context.node) == Some(&*name))
504
+ }
505
+ EscapeUri => {
506
+ let reserved = self.truthy(&values[1]);
507
+ let string = self.string(values.swap_remove(0));
508
+ Value::String(Cow::Owned(escape_uri(&string, reserved)))
509
+ }
510
+ })
511
+ }
512
+
513
+ /// libxml2's `xmlXPathIdFunction`: the elements with an ID
514
+ /// in the blank-separated tokens of the argument, or of the string
515
+ /// of each node.
516
+ fn id(&self, argument: Value<'_>) -> Vec<NodeId> {
517
+ let strings = match argument {
518
+ Value::NodeSet(nodes) => nodes.iter().map(|&node| self.string_value(node)).collect(),
519
+ value => vec![self.string(value).into_owned()],
520
+ };
521
+ let mut ids = self.ids.borrow_mut();
522
+ let ids = ids.get_or_insert_with(|| self.collect_ids());
523
+ let mut found: Vec<NodeId> = strings
524
+ .iter()
525
+ .flat_map(|string| string.split(|&b| is_blank(b)).filter(|t| !t.is_empty()))
526
+ .filter_map(|token| ids.get(token).copied())
527
+ .collect();
528
+ self.document.sort_in_document_order(&mut found);
529
+ found
530
+ }
531
+
532
+ /// libxml2 keeps the first element registered for each ID. Here
533
+ /// this is the first in document order: first in the document, then
534
+ /// in the tree of the context node. `xmlIsID` makes `id` attributes IDs
535
+ /// in HTML documents, and `name` on `a` elements. In other documents only
536
+ /// `xml:id` is an ID.
537
+ fn collect_ids(&self) -> HashMap<Vec<u8>, NodeId> {
538
+ let document = self.document;
539
+ let html = document.kind() == DocumentKind::Html;
540
+ let mut ids = HashMap::new();
541
+ let roots = std::iter::once(NodeId::DOCUMENT)
542
+ .chain((self.root != NodeId::DOCUMENT).then_some(self.root));
543
+ for root in roots {
544
+ for element in std::iter::once(root).chain(document.descendants(root)) {
545
+ let NodeKind::Element(e) = document.node_kind(element) else {
546
+ continue;
547
+ };
548
+ for &attribute in &e.attributes {
549
+ let NodeKind::Attribute(a) = document.node_kind(attribute) else {
550
+ continue;
551
+ };
552
+ let local = &*a.name.local;
553
+ let is_id = if html {
554
+ local == "id" || (local == "name" && &*e.name.local == "a")
555
+ } else {
556
+ local == "id" && &*a.name.ns == XML_NAMESPACE
557
+ };
558
+ if is_id {
559
+ ids.entry(a.value.clone()).or_insert(element);
560
+ }
561
+ }
562
+ }
563
+ }
564
+ ids
565
+ }
566
+
567
+ /// libxml2's `xmlXPathLangFunction`: the `xml:lang` of the nearest element
568
+ /// that has one. The comparison ignores ASCII case and stops at the end
569
+ /// or at a hyphen.
570
+ fn lang(&self, node: NodeId, lang: &[u8]) -> bool {
571
+ let document = self.document;
572
+ let found = std::iter::once(node)
573
+ .chain(document.ancestors(node))
574
+ .find_map(|node| {
575
+ document.attributes(node).iter().find_map(|&attribute| {
576
+ match document.node_kind(attribute) {
577
+ NodeKind::Attribute(a)
578
+ if &*a.name.local == "lang" && &*a.name.ns == XML_NAMESPACE =>
579
+ {
580
+ Some(&a.value[..])
581
+ }
582
+ _ => None,
583
+ }
584
+ })
585
+ });
586
+ let Some(found) = found else {
587
+ return false;
588
+ };
589
+ found.len() >= lang.len()
590
+ && found[..lang.len()].eq_ignore_ascii_case(lang)
591
+ && matches!(found.get(lang.len()), None | Some(b'-'))
592
+ }
593
+
594
+ fn local_name_of(&self, node: NodeId) -> Vec<u8> {
595
+ match self.document.node_kind(node) {
596
+ NodeKind::Element(_) | NodeKind::Attribute(_) => {
597
+ self.local_name(node).as_bytes().to_vec()
598
+ }
599
+ NodeKind::ProcessingInstruction(pi) => pi.target.clone(),
600
+ _ => Vec::new(),
601
+ }
602
+ }
603
+
604
+ fn qualified_name(&self, node: NodeId) -> Vec<u8> {
605
+ match self.document.node_kind(node) {
606
+ NodeKind::Element(_) | NodeKind::Attribute(_) => {
607
+ let local = self.local_name(node);
608
+ match self.document.namespace(node).and_then(|ns| ns.prefix) {
609
+ Some(prefix) => format!("{prefix}:{local}").into_bytes(),
610
+ None => local.as_bytes().to_vec(),
611
+ }
612
+ }
613
+ _ => self.local_name_of(node),
614
+ }
615
+ }
616
+
617
+ fn boolean(&self, expr: &Expr, context: Context) -> Eval<bool> {
618
+ if let Expr::Path(path) = expr {
619
+ return self.exists(path, context.node);
620
+ }
621
+ Ok(self.truthy(&self.expr(expr, context)?))
622
+ }
623
+
624
+ fn string<'q>(&self, value: Value<'q>) -> Cow<'q, [u8]> {
625
+ match value {
626
+ Value::NodeSet(nodes) => Cow::Owned(
627
+ nodes
628
+ .first()
629
+ .map(|&node| self.string_value(node))
630
+ .unwrap_or_default(),
631
+ ),
632
+ Value::Boolean(b) => Cow::Borrowed(if b { b"true" } else { b"false" }),
633
+ Value::Number(n) => Cow::Owned(number_to_string(n).into_bytes()),
634
+ Value::String(s) => s,
635
+ }
636
+ }
637
+
638
+ fn number(&self, value: &Value<'_>) -> f64 {
639
+ match value {
640
+ Value::NodeSet(nodes) => nodes
641
+ .first()
642
+ .map_or(f64::NAN, |&node| string_to_number(&self.string_value(node))),
643
+ Value::Boolean(b) => f64::from(u8::from(*b)),
644
+ Value::Number(n) => *n,
645
+ Value::String(s) => string_to_number(s),
646
+ }
647
+ }
648
+
649
+ /// libxml2's `xmlXPathCastNodeToString`, which uses `xmlNodeGetContent`.
650
+ fn string_value(&self, node: NodeId) -> Vec<u8> {
651
+ self.document.content(node).unwrap_or_default()
652
+ }
653
+
654
+ /// XPath 1.0 comparison rules. A node set compares as each of its nodes.
655
+ fn compare(&self, comparison: Comparison, left: &Value<'_>, right: &Value<'_>) -> bool {
656
+ use Value::{Boolean, NodeSet, Number, String};
657
+ let equality = matches!(comparison, Comparison::Equal | Comparison::NotEqual);
658
+ match (left, right) {
659
+ (NodeSet(a), NodeSet(b)) => {
660
+ let b: Vec<Vec<u8>> = b.iter().map(|&node| self.string_value(node)).collect();
661
+ a.iter().any(|&node| {
662
+ let a = self.string_value(node);
663
+ b.iter().any(|b| {
664
+ if equality {
665
+ compare_strings(comparison, &a, b)
666
+ } else {
667
+ compare_numbers(comparison, string_to_number(&a), string_to_number(b))
668
+ }
669
+ })
670
+ })
671
+ }
672
+ (NodeSet(nodes), Boolean(_)) | (Boolean(_), NodeSet(nodes)) => {
673
+ let set = Boolean(!nodes.is_empty());
674
+ let (left, right) = if matches!(left, NodeSet(_)) {
675
+ (&set, right)
676
+ } else {
677
+ (left, &set)
678
+ };
679
+ self.compare(comparison, left, right)
680
+ }
681
+ (NodeSet(nodes), other) => nodes.iter().any(|&node| {
682
+ let value = String(Cow::Owned(self.string_value(node)));
683
+ self.compare(comparison, &value, other)
684
+ }),
685
+ (other, NodeSet(nodes)) => nodes.iter().any(|&node| {
686
+ let value = String(Cow::Owned(self.string_value(node)));
687
+ self.compare(comparison, other, &value)
688
+ }),
689
+ _ if !equality => compare_numbers(comparison, self.number(left), self.number(right)),
690
+ (Boolean(_), _) | (_, Boolean(_)) => {
691
+ let (a, b) = (self.truthy(left), self.truthy(right));
692
+ (a == b) == (comparison == Comparison::Equal)
693
+ }
694
+ (Number(_), _) | (_, Number(_)) => {
695
+ compare_numbers(comparison, self.number(left), self.number(right))
696
+ }
697
+ (String(a), String(b)) => compare_strings(comparison, a, b),
698
+ }
699
+ }
700
+
701
+ fn truthy(&self, value: &Value<'_>) -> bool {
702
+ match value {
703
+ Value::NodeSet(nodes) => !nodes.is_empty(),
704
+ Value::Boolean(b) => *b,
705
+ Value::Number(n) => *n != 0.0 && !n.is_nan(),
706
+ Value::String(s) => !s.is_empty(),
707
+ }
708
+ }
709
+
710
+ fn path(&self, path: &Path, context: NodeId) -> Eval<Vec<NodeId>> {
711
+ let start = if path.absolute {
712
+ NodeId::DOCUMENT
713
+ } else {
714
+ context
715
+ };
716
+ self.steps(&path.steps, vec![start])
717
+ }
718
+
719
+ fn steps(&self, steps: &[Step], nodes: Vec<NodeId>) -> Eval<Vec<NodeId>> {
720
+ match steps.split_last() {
721
+ Some((last, init)) => {
722
+ let nodes = self.steps_before(init, nodes)?;
723
+ self.step(last, &nodes, false)
724
+ }
725
+ None => Ok(nodes),
726
+ }
727
+ }
728
+
729
+ fn steps_before(&self, steps: &[Step], mut nodes: Vec<NodeId>) -> Eval<Vec<NodeId>> {
730
+ for step in steps {
731
+ if nodes.is_empty() {
732
+ break;
733
+ }
734
+ nodes = self.step(step, &nodes, true)?;
735
+ }
736
+ Ok(nodes)
737
+ }
738
+
739
+ /// Whether `path` finds a node from `context`. The last step stops
740
+ /// at the first node that passes, unless its predicates read positions.
741
+ /// `:has(…)` and `[@attr]` do not.
742
+ fn exists(&self, path: &Path, context: NodeId) -> Eval<bool> {
743
+ let Some((last, init)) = path.steps.split_last() else {
744
+ return Ok(true);
745
+ };
746
+ if last.predicates.iter().any(Expr::is_positional) {
747
+ return Ok(!self.path(path, context)?.is_empty());
748
+ }
749
+ let start = if path.absolute {
750
+ NodeId::DOCUMENT
751
+ } else {
752
+ context
753
+ };
754
+ for node in self.steps_before(init, vec![start])? {
755
+ for candidate in self.axis(last.axis, node) {
756
+ if !self.passes(&last.test, last.axis, candidate) {
757
+ continue;
758
+ }
759
+ let context = Context {
760
+ node: candidate,
761
+ position: 1,
762
+ size: 1,
763
+ };
764
+ let mut passes = true;
765
+ for predicate in &last.predicates {
766
+ if !self.boolean(predicate, context)? {
767
+ passes = false;
768
+ break;
769
+ }
770
+ }
771
+ if passes {
772
+ return Ok(true);
773
+ }
774
+ }
775
+ }
776
+ Ok(false)
777
+ }
778
+
779
+ fn step(&self, step: &Step, input: &[NodeId], inner: bool) -> Eval<Vec<NodeId>> {
780
+ let document = self.document;
781
+ // libxml2's `node()` does not pass a fragment. So `.//p[@id]`
782
+ // from a fragment skips its children, but `.//p` has them,
783
+ // because libxml2 rewrites it as `descendant::p`. Here `//` continues
784
+ // from a fragment.
785
+ let from_fragment = inner
786
+ && step.axis == Axis::DescendantOrSelf
787
+ && step.test == NodeTest::Node
788
+ && step.predicates.is_empty();
789
+ // The search finds the descendants of a searched node again
790
+ // from it, unless the positions depend on the start node.
791
+ let subsumes = matches!(step.axis, Axis::Descendant | Axis::DescendantOrSelf)
792
+ && !step.predicates.iter().any(Expr::is_positional)
793
+ && !input.iter().any(|&node| self.is_attribute(node));
794
+ // `[k]` keeps at most the k-th candidate, so the walk of the axis stops
795
+ // there. libxml2 does the same for `following-sibling::*[1]` (`a + b`).
796
+ let limit = match step.predicates.first() {
797
+ Some(&Expr::Number(k)) if k >= 1.0 && k.fract() == 0.0 => k as usize,
798
+ Some(Expr::Number(_)) => 0,
799
+ _ => usize::MAX,
800
+ };
801
+ let mut output = Vec::new();
802
+ let mut searched: Option<NodeId> = None;
803
+ for &node in input {
804
+ if subsumes {
805
+ if searched.is_some_and(|root| document.ancestors(node).any(|a| a == root)) {
806
+ continue;
807
+ }
808
+ searched = Some(node);
809
+ }
810
+ let mut candidates: Vec<NodeId> = self
811
+ .axis(step.axis, node)
812
+ .filter(|&candidate| {
813
+ self.passes(&step.test, step.axis, candidate)
814
+ || (from_fragment
815
+ && matches!(document.node_kind(candidate), NodeKind::DocumentFragment))
816
+ })
817
+ .take(limit)
818
+ .collect();
819
+ for predicate in &step.predicates {
820
+ candidates = self.filter(candidates, predicate)?;
821
+ }
822
+ if step.axis.is_reverse() {
823
+ candidates.reverse();
824
+ }
825
+ output.extend(candidates);
826
+ }
827
+ if input.len() > 1 && !subsumes {
828
+ document.sort_in_document_order(&mut output);
829
+ }
830
+ Ok(output)
831
+ }
832
+
833
+ fn filter(&self, candidates: Vec<NodeId>, predicate: &Expr) -> Eval<Vec<NodeId>> {
834
+ let size = candidates.len();
835
+ let mut kept = Vec::new();
836
+ for (i, node) in candidates.into_iter().enumerate() {
837
+ let context = Context {
838
+ node,
839
+ position: i + 1,
840
+ size,
841
+ };
842
+ let passes = match predicate {
843
+ Expr::Path(path) => self.exists(path, node)?,
844
+ predicate => match self.expr(predicate, context)? {
845
+ Value::Number(n) => n == context.position as f64,
846
+ value => self.truthy(&value),
847
+ },
848
+ };
849
+ if passes {
850
+ kept.push(node);
851
+ }
852
+ }
853
+ Ok(kept)
854
+ }
855
+
856
+ fn axis(&self, axis: Axis, node: NodeId) -> Box<dyn Iterator<Item = NodeId> + 'a> {
857
+ let document = self.document;
858
+ let not_doctype = |&id: &NodeId| !matches!(document.node_kind(id), NodeKind::Doctype(_));
859
+ let is_attribute = self.is_attribute(node);
860
+ let siblings = |next: fn(&Document, NodeId) -> Option<NodeId>| {
861
+ std::iter::successors(next(document, node), move |&s| next(document, s))
862
+ };
863
+ match axis {
864
+ Axis::Child | Axis::Descendant | Axis::FollowingSibling | Axis::PrecedingSibling
865
+ if is_attribute =>
866
+ {
867
+ Box::new(std::iter::empty())
868
+ }
869
+ Axis::Child => Box::new(document.children(node)),
870
+ // libxml2 walks past doctypes here, but `child::` has them.
871
+ Axis::Descendant => Box::new(document.descendants(node).filter(not_doctype)),
872
+ Axis::DescendantOrSelf if is_attribute => Box::new(std::iter::once(node)),
873
+ Axis::DescendantOrSelf => Box::new(
874
+ std::iter::once(node).chain(document.descendants(node).filter(not_doctype)),
875
+ ),
876
+ Axis::Self_ => Box::new(std::iter::once(node)),
877
+ Axis::Parent => Box::new(document.parent(node).into_iter()),
878
+ Axis::Ancestor => Box::new(document.ancestors(node)),
879
+ Axis::AncestorOrSelf => Box::new(std::iter::once(node).chain(document.ancestors(node))),
880
+ Axis::Attribute => Box::new(document.attributes(node).iter().copied()),
881
+ Axis::FollowingSibling => Box::new(siblings(Document::next_sibling)),
882
+ Axis::PrecedingSibling => Box::new(siblings(Document::previous_sibling)),
883
+ Axis::Following => {
884
+ let mut nodes = Vec::new();
885
+ // libxml2 starts after the element of an attribute and skips
886
+ // its content.
887
+ let start = match (is_attribute, document.parent(node)) {
888
+ (true, Some(element)) => element,
889
+ _ => node,
890
+ };
891
+ for ancestor in std::iter::once(start).chain(document.ancestors(start)) {
892
+ let mut sibling = document.next_sibling(ancestor);
893
+ while let Some(s) = sibling {
894
+ nodes.push(s);
895
+ nodes.extend(document.descendants(s));
896
+ sibling = document.next_sibling(s);
897
+ }
898
+ }
899
+ Box::new(nodes.into_iter())
900
+ }
901
+ Axis::Preceding => {
902
+ let mut nodes = Vec::new();
903
+ let start = match (is_attribute, document.parent(node)) {
904
+ (true, Some(element)) => element,
905
+ _ => node,
906
+ };
907
+ for ancestor in std::iter::once(start).chain(document.ancestors(start)) {
908
+ let mut sibling = document.previous_sibling(ancestor);
909
+ while let Some(s) = sibling {
910
+ let mut subtree: Vec<NodeId> = document.descendants(s).collect();
911
+ subtree.reverse();
912
+ nodes.extend(subtree);
913
+ nodes.push(s);
914
+ sibling = document.previous_sibling(s);
915
+ }
916
+ }
917
+ Box::new(nodes.into_iter())
918
+ }
919
+ }
920
+ }
921
+
922
+ fn is_attribute(&self, node: NodeId) -> bool {
923
+ matches!(self.document.node_kind(node), NodeKind::Attribute(_))
924
+ }
925
+
926
+ fn passes(&self, test: &NodeTest, axis: Axis, node: NodeId) -> bool {
927
+ let kind = self.document.node_kind(node);
928
+ let principal = match axis {
929
+ Axis::Attribute => matches!(kind, NodeKind::Attribute(_)),
930
+ _ => matches!(kind, NodeKind::Element(_)),
931
+ };
932
+ let href = |node| self.document.namespace(node).map(|ns| ns.href);
933
+ match test {
934
+ // libxml2's `node()` passes no doctypes and no fragments.
935
+ NodeTest::Node => !matches!(kind, NodeKind::Doctype(_) | NodeKind::DocumentFragment),
936
+ NodeTest::Text => matches!(kind, NodeKind::Text(_) | NodeKind::CData(_)),
937
+ NodeTest::Comment => matches!(kind, NodeKind::Comment(_)),
938
+ NodeTest::ProcessingInstruction(target) => match kind {
939
+ NodeKind::ProcessingInstruction(pi) => {
940
+ target.as_ref().is_none_or(|t| *t == pi.target)
941
+ }
942
+ _ => false,
943
+ },
944
+ NodeTest::Any => principal,
945
+ NodeTest::AnyIn(prefix) => principal && href(node) == Some(self.prefixed(prefix)),
946
+ // Nokogiri's patch covers elements only: `@*:id` finds nothing.
947
+ NodeTest::LocalName(local) => {
948
+ matches!(kind, NodeKind::Element(_)) && self.local_name(node) == local.as_str()
949
+ }
950
+ NodeTest::Name(name) => {
951
+ principal
952
+ && self.local_name(node) == name.local
953
+ && href(node) == name.prefix.as_deref().map(|prefix| self.prefixed(prefix))
954
+ }
955
+ }
956
+ }
957
+
958
+ fn local_name(&self, node: NodeId) -> &str {
959
+ match self.document.node_kind(node) {
960
+ NodeKind::Element(element) => &element.name.local,
961
+ NodeKind::Attribute(attribute) => &attribute.name.local,
962
+ _ => "",
963
+ }
964
+ }
965
+
966
+ fn prefixed(&self, prefix: &str) -> &str {
967
+ lookup(self.namespaces, prefix).expect("prefixes are checked before evaluation")
968
+ }
969
+ }
970
+
971
+ fn two<T>(values: Vec<T>) -> [T; 2] {
972
+ values
973
+ .try_into()
974
+ .unwrap_or_else(|_| unreachable!("arity is checked"))
975
+ }
976
+
977
+ /// libxml2's `xmlStrstr`: where `needle` first starts in `haystack`. An
978
+ /// empty needle starts at 0.
979
+ fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
980
+ if needle.is_empty() {
981
+ return Some(0);
982
+ }
983
+ haystack
984
+ .windows(needle.len())
985
+ .position(|window| window == needle)
986
+ }
987
+
988
+ /// libxml2's `xmlUTF8Strlen`: counts characters by their lead bytes.
989
+ fn utf8_length(string: &[u8]) -> usize {
990
+ string.iter().filter(|&&b| b & 0xC0 != 0x80).count()
991
+ }
992
+
993
+ fn utf8_chars(string: &[u8]) -> impl Iterator<Item = &[u8]> {
994
+ let mut rest = string;
995
+ std::iter::from_fn(move || {
996
+ let (&lead, tail) = rest.split_first()?;
997
+ let length = 1 + tail.iter().take_while(|&&b| b & 0xC0 == 0x80).count();
998
+ let length = if lead & 0x80 == 0 { 1 } else { length };
999
+ let (char, tail) = rest.split_at(length);
1000
+ rest = tail;
1001
+ Some(char)
1002
+ })
1003
+ }
1004
+
1005
+ /// libxml2's `xmlXPathSubstringFunction`. It rounds the start and the end,
1006
+ /// clamps them to C's `int`, and counts characters from 1.
1007
+ fn substring(string: &[u8], start: f64, length: Option<f64>) -> Vec<u8> {
1008
+ const INT_MAX: f64 = i32::MAX as f64;
1009
+ let round_half_up = |n: f64| {
1010
+ let floor = n.floor();
1011
+ if n - floor >= 0.5 {
1012
+ floor + 1.0
1013
+ } else {
1014
+ floor
1015
+ }
1016
+ };
1017
+ let mut first: i64 = 1;
1018
+ // NaN goes to the end, as in libxml2's `!(in < INT_MAX)`.
1019
+ if start.is_nan() || start >= INT_MAX {
1020
+ first = i64::from(i32::MAX);
1021
+ } else if start >= 1.0 {
1022
+ first = round_half_up(start) as i64;
1023
+ }
1024
+ let mut end = i64::from(i32::MAX);
1025
+ if let Some(length) = length {
1026
+ let sum = round_half_up(start) + round_half_up(length);
1027
+ if sum.is_nan() || sum < 1.0 {
1028
+ end = 1;
1029
+ } else if sum < INT_MAX {
1030
+ end = sum as i64;
1031
+ }
1032
+ }
1033
+ let (first, end) = (first - 1, end - 1);
1034
+ if first >= end || first >= utf8_length(string) as i64 {
1035
+ return Vec::new();
1036
+ }
1037
+ utf8_chars(string)
1038
+ .skip(first as usize)
1039
+ .take((end - first) as usize)
1040
+ .flatten()
1041
+ .copied()
1042
+ .collect()
1043
+ }
1044
+
1045
+ /// libxml2's `xmlXPathTranslateFunction`: each character of `string`
1046
+ /// in `from` becomes the character at the same position in `to`, or is removed.
1047
+ fn translate(string: &[u8], from: &[u8], to: &[u8]) -> Vec<u8> {
1048
+ let mut to = utf8_chars(to);
1049
+ let mut replacements: HashMap<&[u8], Option<&[u8]>> = HashMap::new();
1050
+ for char in utf8_chars(from) {
1051
+ let replacement = to.next();
1052
+ replacements.entry(char).or_insert(replacement);
1053
+ }
1054
+ let mut translated = Vec::with_capacity(string.len());
1055
+ for char in utf8_chars(string) {
1056
+ match replacements.get(char) {
1057
+ Some(replacement) => translated.extend_from_slice(replacement.unwrap_or_default()),
1058
+ None => translated.extend_from_slice(char),
1059
+ }
1060
+ }
1061
+ translated
1062
+ }
1063
+
1064
+ /// libxml2's `xmlXPathRoundFunction`: halves round up. A value that rounds
1065
+ /// to zero keeps its sign.
1066
+ fn round(n: f64) -> f64 {
1067
+ if (-0.5..0.5).contains(&n) {
1068
+ return n * 0.0;
1069
+ }
1070
+ let floor = n.floor();
1071
+ if n - floor >= 0.5 {
1072
+ floor + 1.0
1073
+ } else {
1074
+ floor
1075
+ }
1076
+ }
1077
+
1078
+ fn escape_uri(string: &[u8], escape_reserved: bool) -> Vec<u8> {
1079
+ let mut escaped = Vec::with_capacity(string.len());
1080
+ for (i, &b) in string.iter().enumerate() {
1081
+ let hex_follows = || {
1082
+ string.get(i + 1).is_some_and(u8::is_ascii_hexdigit)
1083
+ && string.get(i + 2).is_some_and(u8::is_ascii_hexdigit)
1084
+ };
1085
+ let kept = b.is_ascii_alphanumeric()
1086
+ || b"-_.!~*'()".contains(&b)
1087
+ || (b == b'%' && hex_follows())
1088
+ || (!escape_reserved && b";/?:@&=+$,".contains(&b));
1089
+ if kept {
1090
+ escaped.push(b);
1091
+ } else {
1092
+ escaped.extend_from_slice(format!("%{b:02X}").as_bytes());
1093
+ }
1094
+ }
1095
+ escaped
1096
+ }
1097
+
1098
+ /// The `name` that libxml2 gives a node. `local-name-is` compares it.
1099
+ fn libxml2_name(document: &Document, node: NodeId) -> Option<&[u8]> {
1100
+ match document.node_kind(node) {
1101
+ NodeKind::Element(element) => Some(element.name.local.as_bytes()),
1102
+ NodeKind::Attribute(attribute) => Some(attribute.name.local.as_bytes()),
1103
+ NodeKind::Text(_) => Some(b"text"),
1104
+ NodeKind::Comment(_) => Some(b"comment"),
1105
+ NodeKind::ProcessingInstruction(pi) => Some(&pi.target),
1106
+ NodeKind::Doctype(doctype) => Some(&doctype.name),
1107
+ NodeKind::CData(_) | NodeKind::Document | NodeKind::DocumentFragment => None,
1108
+ }
1109
+ }
1110
+
1111
+ /// Nokogiri's `css-class` builtin: `needle` starts a word of `haystack`
1112
+ /// and ends at a blank or at the end. An empty needle is always found.
1113
+ fn css_class(haystack: &[u8], needle: &[u8]) -> bool {
1114
+ if needle.is_empty() {
1115
+ return true;
1116
+ }
1117
+ let mut rest = haystack;
1118
+ while !rest.is_empty() {
1119
+ if rest.starts_with(needle) && rest.get(needle.len()).is_none_or(|&b| is_blank(b)) {
1120
+ return true;
1121
+ }
1122
+ let word = rest.iter().position(|&b| is_blank(b)).unwrap_or(rest.len());
1123
+ rest = &rest[word..];
1124
+ let blanks = rest
1125
+ .iter()
1126
+ .position(|&b| !is_blank(b))
1127
+ .unwrap_or(rest.len());
1128
+ rest = &rest[blanks..];
1129
+ }
1130
+ false
1131
+ }
1132
+
1133
+ fn compare_strings(comparison: Comparison, a: &[u8], b: &[u8]) -> bool {
1134
+ match comparison {
1135
+ Comparison::Equal => a == b,
1136
+ Comparison::NotEqual => a != b,
1137
+ _ => compare_numbers(comparison, string_to_number(a), string_to_number(b)),
1138
+ }
1139
+ }
1140
+
1141
+ fn compare_numbers(comparison: Comparison, a: f64, b: f64) -> bool {
1142
+ match comparison {
1143
+ Comparison::Equal => a == b,
1144
+ Comparison::NotEqual => a != b,
1145
+ Comparison::Less => a < b,
1146
+ Comparison::LessOrEqual => a <= b,
1147
+ Comparison::Greater => a > b,
1148
+ Comparison::GreaterOrEqual => a >= b,
1149
+ }
1150
+ }
1151
+
1152
+ /// libxml2's `xmlXPathStringEvalNumber`: blanks, an optional minus, a number
1153
+ /// as [`scan_number`] reads it, blanks. Anything else is NaN.
1154
+ pub fn string_to_number(s: &[u8]) -> f64 {
1155
+ let start = s.iter().position(|&b| !is_blank(b)).unwrap_or(s.len());
1156
+ let mut rest = &s[start..];
1157
+ let negative = rest.first() == Some(&b'-');
1158
+ if negative {
1159
+ rest = &rest[1..];
1160
+ }
1161
+ if !rest
1162
+ .first()
1163
+ .is_some_and(|&b| b == b'.' || b.is_ascii_digit())
1164
+ {
1165
+ return f64::NAN;
1166
+ }
1167
+ let Some((n, length)) = scan_number(rest) else {
1168
+ return f64::NAN;
1169
+ };
1170
+ if !rest[length..].iter().all(|&b| is_blank(b)) {
1171
+ return f64::NAN;
1172
+ }
1173
+ if negative {
1174
+ -n
1175
+ } else {
1176
+ n
1177
+ }
1178
+ }
1179
+
1180
+ /// libxml2's number reader, used by `xmlXPathCompNumber`
1181
+ /// and `xmlXPathStringEvalNumber`. It accumulates the digits as a double, reads
1182
+ /// at most 20 fraction digits after the leading zeros, and applies the exponent
1183
+ /// with `pow`. The exponent digits can be missing. The result is not correctly
1184
+ /// rounded, so long numbers match libxml2. It returns the value and the bytes
1185
+ /// read, or None for a `.` with no digit on either side.
1186
+ pub(super) fn scan_number(s: &[u8]) -> Option<(f64, usize)> {
1187
+ const MAX_FRAC: i32 = 20;
1188
+ let digit = |at: usize| {
1189
+ s.get(at)
1190
+ .filter(|b| b.is_ascii_digit())
1191
+ .map(|b| f64::from(b - b'0'))
1192
+ };
1193
+ let mut at = 0;
1194
+ let mut n = 0.0;
1195
+ while let Some(d) = digit(at) {
1196
+ n = n * 10.0 + d;
1197
+ at += 1;
1198
+ }
1199
+ let whole = at > 0;
1200
+ if s.get(at) == Some(&b'.') {
1201
+ at += 1;
1202
+ if !whole && digit(at).is_none() {
1203
+ return None;
1204
+ }
1205
+ let mut places = 0;
1206
+ while s.get(at) == Some(&b'0') {
1207
+ places += 1;
1208
+ at += 1;
1209
+ }
1210
+ let max = places + MAX_FRAC;
1211
+ let mut fraction = 0.0;
1212
+ while let Some(d) = digit(at).filter(|_| places < max) {
1213
+ fraction = fraction * 10.0 + d;
1214
+ places += 1;
1215
+ at += 1;
1216
+ }
1217
+ n += fraction / power_of_ten(places);
1218
+ while digit(at).is_some() {
1219
+ at += 1;
1220
+ }
1221
+ }
1222
+ if matches!(s.get(at), Some(b'e' | b'E')) {
1223
+ at += 1;
1224
+ let negative = s.get(at) == Some(&b'-');
1225
+ if negative || s.get(at) == Some(&b'+') {
1226
+ at += 1;
1227
+ }
1228
+ let mut exponent: i32 = 0;
1229
+ while let Some(d) = digit(at) {
1230
+ if exponent < 1_000_000 {
1231
+ exponent = exponent * 10 + d as i32;
1232
+ }
1233
+ at += 1;
1234
+ }
1235
+ if negative {
1236
+ exponent = -exponent;
1237
+ }
1238
+ n *= power_of_ten(exponent);
1239
+ }
1240
+ Some((n, at))
1241
+ }
1242
+
1243
+ /// 10^exponent, correctly rounded, as C's `pow(10, n)` gives it to libxml2.
1244
+ /// Rust's `powf` has no precision guarantee (Miri makes it inexact on purpose).
1245
+ /// Rust float parsing is correctly rounded, and powers up to 22 are exact.
1246
+ fn power_of_ten(exponent: i32) -> f64 {
1247
+ const EXACT: [f64; 23] = [
1248
+ 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16,
1249
+ 1e17, 1e18, 1e19, 1e20, 1e21, 1e22,
1250
+ ];
1251
+ match usize::try_from(exponent).ok().and_then(|e| EXACT.get(e)) {
1252
+ Some(&power) => power,
1253
+ None => format!("1e{exponent}").parse().expect("a float literal"),
1254
+ }
1255
+ }
1256
+
1257
+ /// libxml2's `xmlXPathFormatNumber`: integers strictly inside the range of C's
1258
+ /// `int` stay as they are. Other values below 1e-5 or above 1e9 use `%.14e`.
1259
+ /// The rest use `%f` with 15 significant digits. Trailing zeros of the fraction
1260
+ /// are removed.
1261
+ pub fn number_to_string(n: f64) -> String {
1262
+ const INT_MIN: f64 = i32::MIN as f64;
1263
+ const INT_MAX: f64 = i32::MAX as f64;
1264
+ if n.is_nan() {
1265
+ return "NaN".into();
1266
+ }
1267
+ if n.is_infinite() {
1268
+ return if n > 0.0 { "Infinity" } else { "-Infinity" }.into();
1269
+ }
1270
+ if n == 0.0 {
1271
+ return "0".into();
1272
+ }
1273
+ if n > INT_MIN && n < INT_MAX && n == n.trunc() {
1274
+ return format!("{}", n as i32);
1275
+ }
1276
+ let absolute = n.abs();
1277
+ if !(1e-5..=1e9).contains(&absolute) {
1278
+ // Rust writes `1.5e9`, C writes `1.5e+09`.
1279
+ let formatted = format!("{n:.14e}");
1280
+ let (mantissa, exponent) = formatted.split_once('e').expect("an exponent");
1281
+ let exponent: i32 = exponent.parse().expect("a decimal exponent");
1282
+ let sign = if exponent < 0 { '-' } else { '+' };
1283
+ return format!(
1284
+ "{}e{sign}{:02}",
1285
+ trim_fraction(mantissa),
1286
+ exponent.unsigned_abs()
1287
+ );
1288
+ }
1289
+ let integer_place = absolute.log10() as i32;
1290
+ let fraction_place = if integer_place > 0 {
1291
+ 15 - integer_place - 1
1292
+ } else {
1293
+ 15 - integer_place
1294
+ };
1295
+ let precision = usize::try_from(fraction_place).expect("at most 20");
1296
+ trim_fraction(&format!("{n:.precision$}")).into()
1297
+ }
1298
+
1299
+ fn trim_fraction(number: &str) -> &str {
1300
+ if number.contains('.') {
1301
+ number.trim_end_matches('0').trim_end_matches('.')
1302
+ } else {
1303
+ number
1304
+ }
1305
+ }