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,729 @@
1
+ //! Parses XPath strings into the trees that [`evaluate`](super::evaluate) runs.
2
+ //!
3
+ //! The parser reads XPath 1.0 as libxml2 does. An expression that libxml2
4
+ //! rejects fails with the error of libxml2. libxml2 accepts two things
5
+ //! that fail here with [`ParseError::Unsupported`]: the `namespace` axis,
6
+ //! and brackets nested deeper than [`MAX_NESTING`].
7
+
8
+ use super::ast::{
9
+ Arithmetic, Axis, Comparison, Expr, Filter, Function, NodeTest, Operator, Path, QName, Step,
10
+ };
11
+ use super::chars::{is_blank, is_name_char, is_name_start, is_xml_char};
12
+ use super::eval::scan_number;
13
+ use super::{Error, FunctionName, Query};
14
+
15
+ #[derive(Clone, Debug, PartialEq, Eq)]
16
+ pub enum ParseError {
17
+ /// libxml2 cannot compile it either.
18
+ Syntax(Error),
19
+ /// Valid XPath that lobzique leaves out. Holds the construct it uses.
20
+ Unsupported(String),
21
+ }
22
+
23
+ impl From<Error> for ParseError {
24
+ fn from(error: Error) -> ParseError {
25
+ ParseError::Syntax(error)
26
+ }
27
+ }
28
+
29
+ /// Maximum nesting of predicates, parentheses and argument lists, as in CSS.
30
+ /// Each level uses stack to parse and evaluate.
31
+ pub const MAX_NESTING: usize = 32;
32
+
33
+ pub fn parse(expression: &[u8]) -> Result<Query> {
34
+ let mut parser = Parser {
35
+ input: expression,
36
+ at: 0,
37
+ depth: 0,
38
+ unsupported: None,
39
+ functions: Vec::new(),
40
+ };
41
+ parser.skip_blanks();
42
+ let expr = parser.expr()?;
43
+ parser.skip_blanks();
44
+ if parser.at < parser.input.len() {
45
+ return Err(Error::InvalidExpression.into());
46
+ }
47
+ if let Some(construct) = parser.unsupported {
48
+ return Err(ParseError::Unsupported(construct));
49
+ }
50
+ Ok(Query::xpath(expr, parser.functions))
51
+ }
52
+
53
+ type Result<T> = std::result::Result<T, ParseError>;
54
+
55
+ struct Parser<'a> {
56
+ input: &'a [u8],
57
+ at: usize,
58
+ depth: usize,
59
+ /// The first construct left out, in reading order. Parsing continues,
60
+ /// so a later syntax error wins, as libxml2 raises it.
61
+ unsupported: Option<String>,
62
+ /// The name of each call to a function that is not in XPath 1.0, by site.
63
+ functions: Vec<FunctionName>,
64
+ }
65
+
66
+ /// Stands in for a construct that is left out. It is never evaluated.
67
+ const PLACEHOLDER: Expr = Expr::Number(0.0);
68
+
69
+ impl Parser<'_> {
70
+ fn peek(&self) -> Option<u8> {
71
+ self.input.get(self.at).copied()
72
+ }
73
+
74
+ fn peek_at(&self, offset: usize) -> Option<u8> {
75
+ self.input.get(self.at + offset).copied()
76
+ }
77
+
78
+ fn rest(&self) -> &[u8] {
79
+ &self.input[self.at..]
80
+ }
81
+
82
+ fn skip_blanks(&mut self) {
83
+ while self.peek().is_some_and(is_blank) {
84
+ self.at += 1;
85
+ }
86
+ }
87
+
88
+ fn eat(&mut self, token: &[u8]) -> bool {
89
+ let found = self.rest().starts_with(token);
90
+ if found {
91
+ self.at += token.len();
92
+ }
93
+ found
94
+ }
95
+
96
+ fn unsupported(&mut self, construct: impl Into<String>) {
97
+ self.unsupported.get_or_insert_with(|| construct.into());
98
+ }
99
+
100
+ /// Called after an opening bracket: whether to parse what it holds. Past
101
+ /// [`MAX_NESTING`], it skips to the matching bracket. The stack then stays
102
+ /// bounded, and an unclosed bracket or literal still raises the error
103
+ /// of libxml2. Other syntax errors in the skipped text are not reported.
104
+ fn nest(&mut self) -> Result<bool> {
105
+ if self.depth == MAX_NESTING {
106
+ self.unsupported(format!("nesting deeper than {MAX_NESTING}"));
107
+ self.skip_nested()?;
108
+ return Ok(false);
109
+ }
110
+ self.depth += 1;
111
+ Ok(true)
112
+ }
113
+
114
+ fn skip_nested(&mut self) -> Result<()> {
115
+ let mut open = vec![self.input[self.at - 1]];
116
+ while let Some(&innermost) = open.last() {
117
+ let unclosed = || match innermost {
118
+ b'[' => Error::InvalidPredicate,
119
+ _ => Error::InvalidExpression,
120
+ };
121
+ match self.peek() {
122
+ None => return Err(unclosed().into()),
123
+ Some(b'\'' | b'"') => {
124
+ self.literal()?;
125
+ continue;
126
+ }
127
+ Some(b @ (b'[' | b'(')) => open.push(b),
128
+ Some(b']') if innermost == b'[' => _ = open.pop(),
129
+ Some(b')') if innermost == b'(' => _ = open.pop(),
130
+ Some(b']' | b')') => return Err(unclosed().into()),
131
+ Some(_) => {}
132
+ }
133
+ self.at += 1;
134
+ }
135
+ Ok(())
136
+ }
137
+
138
+ fn expr(&mut self) -> Result<Expr> {
139
+ let first = self.and_expr()?;
140
+ let mut rest = Vec::new();
141
+ // libxml2 matches operator names without looking past them.
142
+ while self.skip_operator(b"or") {
143
+ rest.push(self.and_expr()?);
144
+ }
145
+ Ok(list(first, rest, Expr::Or))
146
+ }
147
+
148
+ fn and_expr(&mut self) -> Result<Expr> {
149
+ let first = self.equality_expr()?;
150
+ let mut rest = Vec::new();
151
+ while self.skip_operator(b"and") {
152
+ rest.push(self.equality_expr()?);
153
+ }
154
+ Ok(list(first, rest, Expr::And))
155
+ }
156
+
157
+ fn skip_operator(&mut self, operator: &[u8]) -> bool {
158
+ self.skip_blanks();
159
+ let found = self.eat(operator);
160
+ self.skip_blanks();
161
+ found
162
+ }
163
+
164
+ fn operation(
165
+ &mut self,
166
+ operators: &[(&[u8], Operator)],
167
+ operand: fn(&mut Self) -> Result<Expr>,
168
+ ) -> Result<Expr> {
169
+ let first = operand(self)?;
170
+ let mut rest = Vec::new();
171
+ loop {
172
+ self.skip_blanks();
173
+ let Some(&(token, operator)) = operators
174
+ .iter()
175
+ .find(|(token, _)| self.rest().starts_with(token))
176
+ else {
177
+ break;
178
+ };
179
+ self.at += token.len();
180
+ self.skip_blanks();
181
+ rest.push((operator, operand(self)?));
182
+ }
183
+ Ok(if rest.is_empty() {
184
+ first
185
+ } else {
186
+ Expr::Operation(Box::new(first), rest)
187
+ })
188
+ }
189
+
190
+ fn equality_expr(&mut self) -> Result<Expr> {
191
+ use Comparison::*;
192
+ self.operation(
193
+ &[
194
+ (&b"="[..], Operator::Compare(Equal)),
195
+ (&b"!="[..], Operator::Compare(NotEqual)),
196
+ ],
197
+ Self::relational_expr,
198
+ )
199
+ }
200
+
201
+ fn relational_expr(&mut self) -> Result<Expr> {
202
+ use Comparison::*;
203
+ self.operation(
204
+ &[
205
+ (&b"<="[..], Operator::Compare(LessOrEqual)),
206
+ (&b"<"[..], Operator::Compare(Less)),
207
+ (&b">="[..], Operator::Compare(GreaterOrEqual)),
208
+ (&b">"[..], Operator::Compare(Greater)),
209
+ ],
210
+ Self::additive_expr,
211
+ )
212
+ }
213
+
214
+ fn additive_expr(&mut self) -> Result<Expr> {
215
+ use Arithmetic::*;
216
+ self.operation(
217
+ &[
218
+ (&b"+"[..], Operator::Arithmetic(Add)),
219
+ (&b"-"[..], Operator::Arithmetic(Subtract)),
220
+ ],
221
+ Self::multiplicative_expr,
222
+ )
223
+ }
224
+
225
+ fn multiplicative_expr(&mut self) -> Result<Expr> {
226
+ use Arithmetic::*;
227
+ self.operation(
228
+ &[
229
+ (&b"*"[..], Operator::Arithmetic(Multiply)),
230
+ (&b"div"[..], Operator::Arithmetic(Divide)),
231
+ (&b"mod"[..], Operator::Arithmetic(Modulo)),
232
+ ],
233
+ Self::unary_expr,
234
+ )
235
+ }
236
+
237
+ /// libxml2's `xmlXPathCompUnaryExpr`: an odd number of minus signs negates.
238
+ /// An even number converts to a number. Before a number, the signs are part
239
+ /// of it.
240
+ fn unary_expr(&mut self) -> Result<Expr> {
241
+ self.skip_blanks();
242
+ let mut negative = false;
243
+ let mut signed = false;
244
+ while self.peek() == Some(b'-') {
245
+ self.at += 1;
246
+ negative = !negative;
247
+ signed = true;
248
+ self.skip_blanks();
249
+ }
250
+ let expr = self.union_expr()?;
251
+ Ok(match expr {
252
+ expr if !signed => expr,
253
+ Expr::Number(n) if negative => Expr::Number(-n),
254
+ expr @ Expr::Number(_) => expr,
255
+ expr if negative => Expr::Negate(Box::new(expr)),
256
+ expr => Expr::Call(Function::Number, vec![expr]),
257
+ })
258
+ }
259
+
260
+ fn union_expr(&mut self) -> Result<Expr> {
261
+ let first = self.path_expr()?;
262
+ let mut rest = Vec::new();
263
+ loop {
264
+ self.skip_blanks();
265
+ if !self.eat(b"|") {
266
+ break;
267
+ }
268
+ self.skip_blanks();
269
+ rest.push(self.path_expr()?);
270
+ }
271
+ Ok(list(first, rest, Expr::Union))
272
+ }
273
+
274
+ /// libxml2's `xmlXPathCompPathExpr`: a location path, or a primary
275
+ /// expression with optional predicates and a path after it.
276
+ fn path_expr(&mut self) -> Result<Expr> {
277
+ self.skip_blanks();
278
+ let starts_primary = match self.peek() {
279
+ Some(b'$' | b'(' | b'\'' | b'"' | b'0'..=b'9') => true,
280
+ Some(b'.') => self.peek_at(1).is_some_and(|b| b.is_ascii_digit()),
281
+ _ => self.function_name_ahead()?,
282
+ };
283
+ if !starts_primary {
284
+ return Ok(Expr::Path(self.location_path()?));
285
+ }
286
+ let primary = self.primary_expr()?;
287
+ self.skip_blanks();
288
+ let mut predicates = Vec::new();
289
+ while self.peek() == Some(b'[') {
290
+ predicates.push(self.predicate()?);
291
+ self.skip_blanks();
292
+ }
293
+ let mut steps = Vec::new();
294
+ if self.eat(b"//") {
295
+ steps.push(descendant_or_self());
296
+ } else if !self.eat(b"/") {
297
+ return Ok(filter(primary, predicates, steps));
298
+ }
299
+ self.skip_blanks();
300
+ steps = self.relative_path(steps)?;
301
+ Ok(filter(primary, predicates, steps))
302
+ }
303
+
304
+ fn function_name_ahead(&mut self) -> Result<bool> {
305
+ let start = self.at;
306
+ let ahead = (|| {
307
+ if !self.scan_ncname(|_| ())? {
308
+ return Ok(false);
309
+ }
310
+ if self.peek() == Some(b':') && self.peek_at(1) != Some(b':') {
311
+ self.at += 1;
312
+ if !self.scan_ncname(|_| ())? {
313
+ return Ok(false);
314
+ }
315
+ } else if is_node_type(&self.input[start..self.at]) {
316
+ return Ok(false);
317
+ }
318
+ self.skip_blanks();
319
+ Ok(self.peek() == Some(b'('))
320
+ })();
321
+ self.at = start;
322
+ ahead
323
+ }
324
+
325
+ fn primary_expr(&mut self) -> Result<Expr> {
326
+ match self.peek() {
327
+ Some(b'$') => {
328
+ self.at += 1;
329
+ let name = self.qname()?.ok_or(Error::VariableReference)?;
330
+ Ok(Expr::Variable(name))
331
+ }
332
+ Some(b'(') => {
333
+ self.at += 1;
334
+ if !self.nest()? {
335
+ return Ok(PLACEHOLDER);
336
+ }
337
+ self.skip_blanks();
338
+ let expr = self.expr()?;
339
+ self.skip_blanks();
340
+ if !self.eat(b")") {
341
+ return Err(Error::InvalidExpression.into());
342
+ }
343
+ self.depth -= 1;
344
+ Ok(expr)
345
+ }
346
+ Some(b'\'' | b'"') => Ok(Expr::Literal(self.literal()?)),
347
+ Some(b'0'..=b'9' | b'.') => Ok(Expr::Number(self.number())),
348
+ _ => self.function_call(),
349
+ }
350
+ }
351
+
352
+ /// A call to a function of XPath 1.0, or to one that the caller must find.
353
+ /// libxml2 looks up the second kind when it evaluates the call.
354
+ fn function_call(&mut self) -> Result<Expr> {
355
+ let name = self.qname()?.ok_or(Error::InvalidExpression)?;
356
+ self.skip_blanks();
357
+ self.at += 1;
358
+ if !self.nest()? {
359
+ return Ok(PLACEHOLDER);
360
+ }
361
+ self.skip_blanks();
362
+ let mut arguments = Vec::new();
363
+ if self.peek() != Some(b')') {
364
+ loop {
365
+ arguments.push(self.expr()?);
366
+ self.skip_blanks();
367
+ if self.peek() == Some(b')') {
368
+ break;
369
+ }
370
+ if !self.eat(b",") {
371
+ return Err(Error::InvalidExpression.into());
372
+ }
373
+ self.skip_blanks();
374
+ }
375
+ }
376
+ self.at += 1;
377
+ self.depth -= 1;
378
+ let builtin = match &name.prefix {
379
+ None => Function::named(&name.local),
380
+ Some(_) => None,
381
+ };
382
+ if let Some(function) = builtin {
383
+ return Ok(Expr::Call(function, arguments));
384
+ }
385
+ let site = self.functions.len();
386
+ self.functions.push(FunctionName {
387
+ prefix: name.prefix,
388
+ local: name.local,
389
+ });
390
+ Ok(Expr::Custom { site, arguments })
391
+ }
392
+
393
+ /// libxml2's `xmlXPathCompLocationPath`. It reads `/` again after
394
+ /// a `/` that no step follows: `/ /p` is `/p`.
395
+ fn location_path(&mut self) -> Result<Path> {
396
+ if self.peek() != Some(b'/') {
397
+ return Ok(Path::relative(self.relative_path(Vec::new())?));
398
+ }
399
+ let mut steps = Vec::new();
400
+ while self.peek() == Some(b'/') {
401
+ if self.eat(b"//") {
402
+ self.skip_blanks();
403
+ steps.push(descendant_or_self());
404
+ steps = self.relative_path(steps)?;
405
+ } else {
406
+ self.at += 1;
407
+ self.skip_blanks();
408
+ if self.step_ahead() {
409
+ steps = self.relative_path(steps)?;
410
+ }
411
+ }
412
+ }
413
+ Ok(Path {
414
+ absolute: true,
415
+ steps,
416
+ })
417
+ }
418
+
419
+ /// Whether libxml2 reads a step after `/`. It decides from the byte alone.
420
+ fn step_ahead(&self) -> bool {
421
+ self.peek().is_some_and(|b| {
422
+ b.is_ascii_alphabetic() || b >= 0x80 || matches!(b, b'_' | b'.' | b'@' | b'*')
423
+ })
424
+ }
425
+
426
+ fn relative_path(&mut self, mut steps: Vec<Step>) -> Result<Vec<Step>> {
427
+ steps.extend(self.step()?);
428
+ loop {
429
+ self.skip_blanks();
430
+ if self.eat(b"//") {
431
+ steps.push(descendant_or_self());
432
+ } else if !self.eat(b"/") {
433
+ return Ok(steps);
434
+ }
435
+ self.skip_blanks();
436
+ steps.extend(self.step()?);
437
+ }
438
+ }
439
+
440
+ /// libxml2's `xmlXPathCompStep`. `.` is no step at all, not `self::node()`,
441
+ /// because a fragment does not pass `self::node()`.
442
+ fn step(&mut self) -> Result<Option<Step>> {
443
+ if self.eat(b"..") {
444
+ return Ok(Some(Step::new(Axis::Parent, NodeTest::Node)));
445
+ }
446
+ if self.eat(b".") {
447
+ return Ok(None);
448
+ }
449
+ let (axis, name) = if self.eat(b"@") {
450
+ self.skip_blanks();
451
+ (Axis::Attribute, None)
452
+ } else if let Some(name) = self.ncname()? {
453
+ self.skip_blanks();
454
+ if self.eat(b"::") {
455
+ self.skip_blanks();
456
+ (self.axis(&name)?, None)
457
+ } else {
458
+ (Axis::Child, Some(name))
459
+ }
460
+ } else {
461
+ (Axis::Child, None)
462
+ };
463
+ let test = self.node_test(name)?;
464
+ let mut step = Step::new(axis, test);
465
+ loop {
466
+ self.skip_blanks();
467
+ if self.peek() != Some(b'[') {
468
+ return Ok(Some(step));
469
+ }
470
+ let predicate = self.predicate()?;
471
+ step.predicates.push(predicate);
472
+ }
473
+ }
474
+
475
+ fn axis(&mut self, name: &str) -> Result<Axis> {
476
+ Ok(match name {
477
+ "ancestor" => Axis::Ancestor,
478
+ "ancestor-or-self" => Axis::AncestorOrSelf,
479
+ "attribute" => Axis::Attribute,
480
+ "child" => Axis::Child,
481
+ "descendant" => Axis::Descendant,
482
+ "descendant-or-self" => Axis::DescendantOrSelf,
483
+ "following" => Axis::Following,
484
+ "following-sibling" => Axis::FollowingSibling,
485
+ "parent" => Axis::Parent,
486
+ "preceding" => Axis::Preceding,
487
+ "preceding-sibling" => Axis::PrecedingSibling,
488
+ "self" => Axis::Self_,
489
+ "namespace" => {
490
+ self.unsupported("the namespace axis");
491
+ Axis::Child
492
+ }
493
+ _ => return Err(Error::InvalidExpression.into()),
494
+ })
495
+ }
496
+
497
+ /// libxml2's `xmlXPathCompNodeTest`, after `name` and, if the step already
498
+ /// read them, the blanks after it. Blanks can come before the colon
499
+ /// of a QName. libxml2 skips them while it looks for `::`. It does not skip
500
+ /// them after the colon.
501
+ fn node_test(&mut self, name: Option<String>) -> Result<NodeTest> {
502
+ let name = match name {
503
+ Some(name) => name,
504
+ None => {
505
+ if self.eat(b"*") {
506
+ // Nokogiri's patch: `*:name` is the name in any namespace.
507
+ if !self.eat(b":") {
508
+ return Ok(NodeTest::Any);
509
+ }
510
+ if self.eat(b"*") {
511
+ return Ok(NodeTest::LocalName("*".into()));
512
+ }
513
+ let local = self.ncname()?.ok_or(Error::InvalidExpression)?;
514
+ return Ok(NodeTest::LocalName(local));
515
+ }
516
+ let name = self.ncname()?.ok_or(Error::InvalidExpression)?;
517
+ self.skip_blanks();
518
+ name
519
+ }
520
+ };
521
+ if self.eat(b"(") {
522
+ return self.node_type(&name);
523
+ }
524
+ if !self.eat(b":") {
525
+ return Ok(NodeTest::Name(QName {
526
+ prefix: None,
527
+ local: name,
528
+ }));
529
+ }
530
+ if self.eat(b"*") {
531
+ return Ok(NodeTest::AnyIn(name));
532
+ }
533
+ let local = self.ncname()?.ok_or(Error::InvalidExpression)?;
534
+ Ok(NodeTest::Name(QName {
535
+ prefix: Some(name),
536
+ local,
537
+ }))
538
+ }
539
+
540
+ fn node_type(&mut self, name: &str) -> Result<NodeTest> {
541
+ self.skip_blanks();
542
+ let test = match name {
543
+ "node" => NodeTest::Node,
544
+ "text" => NodeTest::Text,
545
+ "comment" => NodeTest::Comment,
546
+ "processing-instruction" => {
547
+ let mut target = None;
548
+ if matches!(self.peek(), Some(b'\'' | b'"')) {
549
+ target = Some(self.literal()?);
550
+ self.skip_blanks();
551
+ } else if self.peek() != Some(b')') {
552
+ return Err(Error::StartLiteral.into());
553
+ }
554
+ NodeTest::ProcessingInstruction(target)
555
+ }
556
+ _ => return Err(Error::InvalidExpression.into()),
557
+ };
558
+ if !self.eat(b")") {
559
+ return Err(Error::Unclosed.into());
560
+ }
561
+ Ok(test)
562
+ }
563
+
564
+ fn predicate(&mut self) -> Result<Expr> {
565
+ self.at += 1;
566
+ if !self.nest()? {
567
+ return Ok(PLACEHOLDER);
568
+ }
569
+ self.skip_blanks();
570
+ let expr = self.expr()?;
571
+ self.skip_blanks();
572
+ if !self.eat(b"]") {
573
+ return Err(Error::InvalidPredicate.into());
574
+ }
575
+ self.depth -= 1;
576
+ Ok(expr)
577
+ }
578
+
579
+ /// libxml2's `xmlXPathParseLiteral`: no escapes, any XML character.
580
+ /// It checks characters while it reads, so a bad character before the end
581
+ /// is reported, not the missing quote.
582
+ fn literal(&mut self) -> Result<Vec<u8>> {
583
+ let quote = self.input[self.at];
584
+ self.at += 1;
585
+ let start = self.at;
586
+ loop {
587
+ match self.peek() {
588
+ None => return Err(Error::UnfinishedLiteral.into()),
589
+ Some(b) if b == quote => break,
590
+ // `xmlGetUTF8Char` rejects these leads and overlong forms.
591
+ // `xmlXPathCurrentChar` does not.
592
+ Some(0x80..=0xC1) => return Err(Error::InvalidChar.into()),
593
+ Some(_) => {}
594
+ }
595
+ let (value, length) = decode(self.rest()).ok_or(Error::InvalidChar)?;
596
+ let shortest = [0, 0, 0x80, 0x800, 0x10000][length];
597
+ let valid = value >= shortest && char::from_u32(value).is_some_and(is_xml_char);
598
+ if !valid {
599
+ return Err(Error::InvalidChar.into());
600
+ }
601
+ self.at += length;
602
+ }
603
+ let content = self.input[start..self.at].to_vec();
604
+ self.at += 1;
605
+ Ok(content)
606
+ }
607
+
608
+ fn number(&mut self) -> f64 {
609
+ let (n, length) = scan_number(self.rest()).expect("a digit");
610
+ self.at += length;
611
+ n
612
+ }
613
+
614
+ fn qname(&mut self) -> Result<Option<QName>> {
615
+ let Some(name) = self.ncname()? else {
616
+ return Ok(None);
617
+ };
618
+ if !self.eat(b":") {
619
+ return Ok(Some(QName {
620
+ prefix: None,
621
+ local: name,
622
+ }));
623
+ }
624
+ Ok(self.ncname()?.map(|local| QName {
625
+ prefix: Some(name),
626
+ local,
627
+ }))
628
+ }
629
+
630
+ fn ncname(&mut self) -> Result<Option<String>> {
631
+ let mut name = String::new();
632
+ Ok(self.scan_ncname(|c| name.push(c))?.then_some(name))
633
+ }
634
+
635
+ /// Reads an NCName, if one starts here, and passes each decoded character
636
+ /// on. An overlong form is the character it encodes.
637
+ fn scan_ncname(&mut self, mut each: impl FnMut(char)) -> Result<bool> {
638
+ let Some((first, length)) = self.char_here()? else {
639
+ return Ok(false);
640
+ };
641
+ if !is_name_start(first) {
642
+ return Ok(false);
643
+ }
644
+ each(first);
645
+ self.at += length;
646
+ while let Some((c, length)) = self.char_here()? {
647
+ if !is_name_char(c) {
648
+ break;
649
+ }
650
+ each(c);
651
+ self.at += length;
652
+ }
653
+ Ok(true)
654
+ }
655
+
656
+ /// libxml2's `xmlXPathCurrentChar`: the character here and its length
657
+ /// in bytes. Bytes that form no sequence are an encoding error. A sequence
658
+ /// that is not an XML `Char`, for example an overlong `NUL` or a surrogate,
659
+ /// is an invalid character.
660
+ fn char_here(&self) -> Result<Option<(char, usize)>> {
661
+ let rest = self.rest();
662
+ match rest.first() {
663
+ None => return Ok(None),
664
+ Some(&b) if b.is_ascii() => return Ok(Some((char::from(b), 1))),
665
+ Some(0xF8..) => return Err(Error::Encoding.into()),
666
+ Some(_) => {}
667
+ }
668
+ let (value, length) = decode(rest).ok_or(Error::Encoding)?;
669
+ let c = char::from_u32(value)
670
+ .filter(|&c| is_xml_char(c))
671
+ .ok_or(Error::InvalidChar)?;
672
+ Ok(Some((c, length)))
673
+ }
674
+ }
675
+
676
+ /// The code point and length of the UTF-8 sequence at the start of `bytes`,
677
+ /// as libxml2 reads it: the lead byte sets the length, and the value
678
+ /// is not checked. None if a continuation byte is missing.
679
+ fn decode(bytes: &[u8]) -> Option<(u32, usize)> {
680
+ let lead = bytes[0];
681
+ let length = match lead {
682
+ 0..=0x7F => return Some((lead.into(), 1)),
683
+ 0x80..=0xDF => 2,
684
+ 0xE0..=0xEF => 3,
685
+ _ => 4,
686
+ };
687
+ let continuations = bytes.get(1..length)?;
688
+ if !continuations.iter().all(|b| b & 0xC0 == 0x80) {
689
+ return None;
690
+ }
691
+ let value = continuations
692
+ .iter()
693
+ .fold(u32::from(lead) & (0x7F >> length), |value, b| {
694
+ value << 6 | u32::from(b & 0x3F)
695
+ });
696
+ Some((value, length))
697
+ }
698
+
699
+ fn list(first: Expr, mut rest: Vec<Expr>, make: fn(Vec<Expr>) -> Expr) -> Expr {
700
+ if rest.is_empty() {
701
+ return first;
702
+ }
703
+ rest.insert(0, first);
704
+ make(rest)
705
+ }
706
+
707
+ /// libxml2 checks that a primary expression is a node set only for the
708
+ /// predicates and steps after it: `'x'/.` is `'x'`.
709
+ fn filter(primary: Expr, predicates: Vec<Expr>, steps: Vec<Step>) -> Expr {
710
+ if predicates.is_empty() && steps.is_empty() {
711
+ return primary;
712
+ }
713
+ Expr::Filter(Box::new(Filter {
714
+ primary,
715
+ predicates,
716
+ steps,
717
+ }))
718
+ }
719
+
720
+ fn descendant_or_self() -> Step {
721
+ Step::new(Axis::DescendantOrSelf, NodeTest::Node)
722
+ }
723
+
724
+ fn is_node_type(name: &[u8]) -> bool {
725
+ matches!(
726
+ name,
727
+ b"node" | b"text" | b"comment" | b"processing-instruction"
728
+ )
729
+ }