libxml-rs 0.1.0-alpha.6

Phase 5: XPath 1.0 engine, XPointer, XInclude. Native-Rust forensic reimplementation of libxml2+libxslt with C ABI drop-in replacement. 522 tests passing, full XPath 1.0 lexer/parser/AST/eval (25 functions), XPointer element scheme + shorthand pointers, XInclude process/process_flags, C ABI exports.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
//! XPath 1.0 Expression Lexer/Tokenizer (§25).
//!
//! Tokenizes XPath expression strings into a stream of tokens
//! for the parser to consume.
//!
//! # UPSTREAM-PARITY
//!
//! Covers all XPath 1.0 token types: names, numbers, strings, operators,
//! axes, function names, variable references, punctuation.
//!
//! # Courts
//!
//! XPATH-LEXER-*

use std::fmt;

// ═══════════════════════════════════════════════════════════════════════════════
// Token Types
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone, PartialEq)]
pub enum Token {
    // ── Names ────────────────────────────────────────────────────────────
    /// Name (NCName or QName)
    Name(String),
    /// `*` wildcard
    Star,
    /// `.` (self)
    Dot,
    /// `..` (parent)
    DotDot,

    // ── Operators ────────────────────────────────────────────────────────
    /// `@` (attribute axis)
    At,
    /// `::` (axis separator)
    DoubleColon,
    /// `/`
    Slash,
    /// `//`
    DoubleSlash,
    /// `|`
    Pipe,
    /// `+`
    Plus,
    /// `-`
    Minus,
    /// `=`
    Eq,
    /// `!=`
    Ne,
    /// `<`
    Lt,
    /// `>`
    Gt,
    /// `<=`
    Le,
    /// `>=`
    Ge,
    /// `*` (multiplication operator, distinct from wildcard)
    Multiply,

    // ── Keywords ─────────────────────────────────────────────────────────
    /// `or`
    Or,
    /// `and`
    And,
    /// `mod`
    Mod,
    /// `div`
    Div,
    /// `ancestor`
    Ancestor,
    /// `ancestor-or-self`
    AncestorOrSelf,
    /// `attribute`
    Attribute,
    /// `child`
    Child,
    /// `descendant`
    Descendant,
    /// `descendant-or-self`
    DescendantOrSelf,
    /// `following`
    Following,
    /// `following-sibling`
    FollowingSibling,
    /// `namespace`
    Namespace,
    /// `parent`
    Parent,
    /// `preceding`
    Preceding,
    /// `preceding-sibling`
    PrecedingSibling,
    /// `self`
    Self_,

    // ── Literals ─────────────────────────────────────────────────────────
    /// String literal (without quotes)
    StringLiteral(String),
    /// Numeric literal
    NumberLiteral(f64),

    // ── Punctuation ──────────────────────────────────────────────────────
    LParen,
    RParen,
    LBracket,
    RBracket,
    LBrace, // for XSLT attribute value templates; rare in XPath
    RBrace,
    Comma,
    /// `$` (variable reference)
    Dollar,

    // ── Special ──────────────────────────────────────────────────────────
    /// End of expression
    Eof,
}

impl fmt::Display for Token {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Token::Name(n) => write!(f, "{}", n),
            Token::Star => write!(f, "*"),
            Token::Dot => write!(f, "."),
            Token::DotDot => write!(f, ".."),
            Token::At => write!(f, "@"),
            Token::DoubleColon => write!(f, "::"),
            Token::Slash => write!(f, "/"),
            Token::DoubleSlash => write!(f, "//"),
            Token::Pipe => write!(f, "|"),
            Token::Plus => write!(f, "+"),
            Token::Minus => write!(f, "-"),
            Token::Eq => write!(f, "="),
            Token::Ne => write!(f, "!="),
            Token::Lt => write!(f, "<"),
            Token::Gt => write!(f, ">"),
            Token::Le => write!(f, "<="),
            Token::Ge => write!(f, ">="),
            Token::Multiply => write!(f, "*"),
            Token::Or => write!(f, "or"),
            Token::And => write!(f, "and"),
            Token::Mod => write!(f, "mod"),
            Token::Div => write!(f, "div"),
            Token::Ancestor => write!(f, "ancestor"),
            Token::AncestorOrSelf => write!(f, "ancestor-or-self"),
            Token::Attribute => write!(f, "attribute"),
            Token::Child => write!(f, "child"),
            Token::Descendant => write!(f, "descendant"),
            Token::DescendantOrSelf => write!(f, "descendant-or-self"),
            Token::Following => write!(f, "following"),
            Token::FollowingSibling => write!(f, "following-sibling"),
            Token::Namespace => write!(f, "namespace"),
            Token::Parent => write!(f, "parent"),
            Token::Preceding => write!(f, "preceding"),
            Token::PrecedingSibling => write!(f, "preceding-sibling"),
            Token::Self_ => write!(f, "self"),
            Token::StringLiteral(s) => write!(f, "'{}'", s),
            Token::NumberLiteral(n) => write!(f, "{}", n),
            Token::LParen => write!(f, "("),
            Token::RParen => write!(f, ")"),
            Token::LBracket => write!(f, "["),
            Token::RBracket => write!(f, "]"),
            Token::LBrace => write!(f, "{{"),
            Token::RBrace => write!(f, "}}"),
            Token::Comma => write!(f, ","),
            Token::Dollar => write!(f, "$"),
            Token::Eof => write!(f, "<EOF>"),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Lexer
// ═══════════════════════════════════════════════════════════════════════════════

/// XPath expression lexer.
///
/// Produces a stream of tokens from an XPath expression string.
#[derive(Debug, Clone)]
pub struct Lexer {
    /// Input bytes
    input: Vec<u8>,
    /// Current position
    pos: usize,
    /// Look-ahead character (0 if EOF)
    ch: u8,
    /// Whether we're at the start of an expression (helps with `-` vs `-`)
    at_start: bool,
}

impl Lexer {
    pub fn new(input: &str) -> Self {
        let bytes = input.as_bytes().to_vec();
        let ch = if bytes.is_empty() { 0 } else { bytes[0] };
        Self {
            input: bytes,
            pos: 0,
            ch,
            at_start: true,
        }
    }

    /// Advance to the next character.
    fn advance(&mut self) {
        self.pos += 1;
        self.ch = if self.pos < self.input.len() {
            self.input[self.pos]
        } else {
            0
        };
    }

    /// Peek at the next character without consuming it.
    fn peek(&self) -> u8 {
        if self.pos + 1 < self.input.len() {
            self.input[self.pos + 1]
        } else {
            0
        }
    }

    /// Skip whitespace.
    fn skip_ws(&mut self) {
        while self.ch != 0
            && (self.ch == b' ' || self.ch == b'\t' || self.ch == b'\n' || self.ch == b'\r')
        {
            self.advance();
        }
    }

    /// Read a name token (NCName).
    fn read_name(&mut self) -> String {
        let start = self.pos;
        while self.ch != 0
            && (self.ch.is_ascii_alphanumeric()
                || self.ch == b'_'
                || self.ch == b'-'
                || self.ch == b'.')
        {
            self.advance();
        }
        String::from_utf8_lossy(&self.input[start..self.pos]).to_string()
    }

    /// Try to match an axis name or keyword.
    fn try_keyword_or_axis(&self, name: &str) -> Option<Token> {
        match name {
            "or" => Some(Token::Or),
            "and" => Some(Token::And),
            "mod" => Some(Token::Mod),
            "div" => Some(Token::Div),
            "ancestor" => Some(Token::Ancestor),
            "ancestor-or-self" => Some(Token::AncestorOrSelf),
            "attribute" => Some(Token::Attribute),
            "child" => Some(Token::Child),
            "descendant" => Some(Token::Descendant),
            "descendant-or-self" => Some(Token::DescendantOrSelf),
            "following" => Some(Token::Following),
            "following-sibling" => Some(Token::FollowingSibling),
            "namespace" => Some(Token::Namespace),
            "parent" => Some(Token::Parent),
            "preceding" => Some(Token::Preceding),
            "preceding-sibling" => Some(Token::PrecedingSibling),
            "self" => Some(Token::Self_),
            _ => None,
        }
    }

    /// Read a number literal.
    fn read_number(&mut self) -> f64 {
        let start = self.pos;
        // Integer part
        while self.ch != 0 && self.ch.is_ascii_digit() {
            self.advance();
        }
        // Fractional part
        if self.ch == b'.' && self.peek().is_ascii_digit() {
            self.advance(); // consume '.'
            while self.ch != 0 && self.ch.is_ascii_digit() {
                self.advance();
            }
        }
        let s = String::from_utf8_lossy(&self.input[start..self.pos]).to_string();
        s.parse::<f64>().unwrap_or(0.0)
    }

    /// Read a string literal.
    fn read_string(&mut self, quote: u8) -> String {
        self.advance(); // consume opening quote
        let start = self.pos;
        while self.ch != 0 && self.ch != quote {
            self.advance();
        }
        let s = String::from_utf8_lossy(&self.input[start..self.pos]).to_string();
        if self.ch == quote {
            self.advance(); // consume closing quote
        }
        s
    }

    /// Get the next token.
    pub fn next_token(&mut self) -> Token {
        self.skip_ws();

        if self.ch == 0 {
            return Token::Eof;
        }

        // Save at_start for unary minus detection
        let was_at_start = self.at_start;
        self.at_start = false;

        // ── Single-char tokens ────────────────────────────────────────────
        match self.ch {
            b'(' => {
                self.advance();
                return Token::LParen;
            }
            b')' => {
                self.advance();
                return Token::RParen;
            }
            b'[' => {
                self.advance();
                return Token::LBracket;
            }
            b']' => {
                self.advance();
                return Token::RBracket;
            }
            b'{' => {
                self.advance();
                return Token::LBrace;
            }
            b'}' => {
                self.advance();
                return Token::RBrace;
            }
            b',' => {
                self.advance();
                return Token::Comma;
            }
            b'$' => {
                self.advance();
                return Token::Dollar;
            }
            b'|' => {
                self.advance();
                return Token::Pipe;
            }
            b'+' => {
                self.advance();
                return Token::Plus;
            }
            b'@' => {
                self.advance();
                return Token::At;
            }
            b'.' => {
                if self.peek() == b'.' {
                    self.advance();
                    self.advance();
                    return Token::DotDot;
                }
                // Check if it's a number starting with '.'
                if self.peek().is_ascii_digit() {
                    return Token::NumberLiteral(self.read_number());
                }
                self.advance();
                return Token::Dot;
            }
            b'-' => {
                self.advance();
                // If at start or after operator, this is unary minus
                // We handle this at the parser level, just return Minus
                return Token::Minus;
            }
            b'=' => {
                self.advance();
                return Token::Eq;
            }
            b'!' => {
                if self.peek() == b'=' {
                    self.advance();
                    self.advance();
                    return Token::Ne;
                }
                // Invalid character, skip
                self.advance();
                return self.next_token();
            }
            b'<' => {
                self.advance();
                if self.ch == b'=' {
                    self.advance();
                    return Token::Le;
                }
                return Token::Lt;
            }
            b'>' => {
                self.advance();
                if self.ch == b'=' {
                    self.advance();
                    return Token::Ge;
                }
                return Token::Gt;
            }
            b'/' => {
                self.advance();
                if self.ch == b'/' {
                    self.advance();
                    return Token::DoubleSlash;
                }
                return Token::Slash;
            }
            b'*' => {
                self.advance();
                return Token::Star; // lexer returns Star; parser disambiguates
            }
            b':' => {
                if self.peek() == b':' {
                    self.advance();
                    self.advance();
                    return Token::DoubleColon;
                }
                // Single colon is part of a QName, handled below
                // Actually, if we see a colon, it should be part of a name
                // This case handles axis::name or prefix:name
                // Since we read the full name first, this shouldn't normally happen alone
                self.advance();
                return self.next_token();
            }
            b'\'' | b'"' => {
                let quote = self.ch;
                let s = self.read_string(quote);
                return Token::StringLiteral(s);
            }
            _ => {}
        }

        // ── Number ───────────────────────────────────────────────────────
        if self.ch.is_ascii_digit() {
            return Token::NumberLiteral(self.read_number());
        }

        // ── Name ─────────────────────────────────────────────────────────
        if self.ch.is_ascii_alphabetic() || self.ch == b'_' {
            let name = self.read_name();

            // Check for QName (prefix:local)
            if self.ch == b':' && self.peek() != b':' {
                self.advance(); // consume ':'
                if self.ch.is_ascii_alphabetic() || self.ch == b'_' || self.ch == b'*' {
                    if self.ch == b'*' {
                        self.advance();
                        let full = format!("{}:*", name);
                        return Token::Name(full);
                    }
                    let local = self.read_name();
                    return Token::Name(format!("{}:{}", name, local));
                }
                // If the colon is not followed by a valid name character,
                // it might be an axis separator that got split. Push back?
                // Actually in well-formed XPath, `name:` is followed by `:`
                // for axis:: or by a local name for QName.
                // We already checked peek != ':', so this is a QName prefix.
                // If the local part is missing, treat the whole thing as a name.
                return Token::Name(name);
            }

            // Check for axis separator: name::
            // We DON'T consume the :: here — we return just the axis keyword token.
            // The :: will be tokenized as DoubleColon on the next call to next_token().
            if self.ch == b':' && self.peek() == b':' {
                if let Some(axis) = self.try_keyword_or_axis(&name) {
                    return axis;
                }
                // Not an axis keyword — could be a QName prefix followed by ::?
                // Treat it as a regular name and let the :: be consumed separately.
                return Token::Name(name);
            }

            // Check for keyword or axis
            if let Some(keyword) = self.try_keyword_or_axis(&name) {
                return keyword;
            }

            return Token::Name(name);
        }

        // Unknown character, skip
        self.advance();
        self.next_token()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;

    fn tokenize(s: &str) -> Vec<Token> {
        let mut lexer = Lexer::new(s);
        let mut tokens = Vec::new();
        loop {
            let tok = lexer.next_token();
            let is_eof = matches!(tok, Token::Eof);
            tokens.push(tok);
            if is_eof {
                break;
            }
        }
        tokens
    }

    #[test]
    fn test_empty() {
        let tokens = tokenize("");
        assert_eq!(tokens.len(), 1);
        assert_eq!(tokens[0], Token::Eof);
    }

    #[test]
    fn test_simple_path() {
        let tokens = tokenize("child::para");
        assert_eq!(
            tokens,
            vec![
                Token::Child,
                Token::DoubleColon,
                Token::Name("para".into()),
                Token::Eof,
            ]
        );
    }

    #[test]
    fn test_absolute_path() {
        let tokens = tokenize("/child::para");
        assert_eq!(
            tokens,
            vec![
                Token::Slash,
                Token::Child,
                Token::DoubleColon,
                Token::Name("para".into()),
                Token::Eof,
            ]
        );
    }

    #[test]
    fn test_short_form() {
        let tokens = tokenize("para");
        assert_eq!(tokens, vec![Token::Name("para".into()), Token::Eof]);
    }

    #[test]
    fn test_attribute() {
        let tokens = tokenize("@attr");
        assert_eq!(
            tokens,
            vec![Token::At, Token::Name("attr".into()), Token::Eof]
        );
    }

    #[test]
    fn test_predicate() {
        let tokens = tokenize("para[1]");
        assert_eq!(
            tokens,
            vec![
                Token::Name("para".into()),
                Token::LBracket,
                Token::NumberLiteral(1.0),
                Token::RBracket,
                Token::Eof,
            ]
        );
    }

    #[test]
    fn test_function_call() {
        let tokens = tokenize("position()");
        assert_eq!(
            tokens,
            vec![
                Token::Name("position".into()),
                Token::LParen,
                Token::RParen,
                Token::Eof,
            ]
        );
    }

    #[test]
    fn test_string_literal() {
        let tokens = tokenize("'hello'");
        assert_eq!(
            tokens,
            vec![Token::StringLiteral("hello".into()), Token::Eof]
        );
    }

    #[test]
    fn test_number() {
        let tokens = tokenize("42");
        assert_eq!(tokens, vec![Token::NumberLiteral(42.0), Token::Eof]);
    }

    #[test]
    fn test_decimal() {
        let tokens = tokenize("3.14");
        assert_eq!(tokens, vec![Token::NumberLiteral(3.14), Token::Eof]);
    }

    #[test]
    fn test_operators() {
        let tokens = tokenize("a = b and c != d or e < f");
        assert!(tokens.contains(&Token::Eq));
        assert!(tokens.contains(&Token::And));
        assert!(tokens.contains(&Token::Ne));
        assert!(tokens.contains(&Token::Or));
        assert!(tokens.contains(&Token::Lt));
    }

    #[test]
    fn test_union() {
        let tokens = tokenize("a | b");
        assert_eq!(
            tokens,
            vec![
                Token::Name("a".into()),
                Token::Pipe,
                Token::Name("b".into()),
                Token::Eof,
            ]
        );
    }

    #[test]
    fn test_double_slash() {
        let tokens = tokenize("//para");
        assert_eq!(
            tokens,
            vec![Token::DoubleSlash, Token::Name("para".into()), Token::Eof]
        );
    }

    #[test]
    fn test_qname() {
        let tokens = tokenize("xslt:template");
        assert_eq!(
            tokens,
            vec![Token::Name("xslt:template".into()), Token::Eof]
        );
    }

    #[test]
    fn test_wildcard() {
        let tokens = tokenize("*");
        assert_eq!(tokens, vec![Token::Star, Token::Eof]);
    }

    #[test]
    fn test_ns_wildcard() {
        let tokens = tokenize("ns:*");
        assert_eq!(tokens, vec![Token::Name("ns:*".into()), Token::Eof]);
    }

    #[test]
    fn test_dot_dot() {
        let tokens = tokenize("..");
        assert_eq!(tokens, vec![Token::DotDot, Token::Eof]);
    }

    #[test]
    fn test_axis_keyword() {
        let tokens = tokenize("ancestor-or-self::node()");
        assert_eq!(
            tokens,
            vec![
                Token::AncestorOrSelf,
                Token::DoubleColon,
                Token::Name("node".into()),
                Token::LParen,
                Token::RParen,
                Token::Eof,
            ]
        );
    }

    #[test]
    fn test_complex_expression() {
        let tokens = tokenize("/html/body//div[@class='main']/p[1]");
        // Collect name-like tokens (including keyword tokens that can be element names)
        let names: Vec<String> = tokens
            .iter()
            .filter_map(|t| match t {
                Token::Name(n) => Some(n.clone()),
                Token::Div => Some("div".to_string()),
                Token::Mod => Some("mod".to_string()),
                Token::And => Some("and".to_string()),
                Token::Or => Some("or".to_string()),
                _ => None,
            })
            .collect();
        assert_eq!(names, vec!["html", "body", "div", "class", "p"]);
    }

    #[test]
    fn test_variable() {
        let tokens = tokenize("$var");
        assert_eq!(
            tokens,
            vec![Token::Dollar, Token::Name("var".into()), Token::Eof]
        );
    }
}