libxml-rs 0.1.0-alpha.37

Native-Rust forensic reimplementation of libxml2+libxslt with C ABI drop-in replacement. Cross-version oracle matrix (libxml2 2.7.8-2.15.3, libxslt 1.1.26-1.1.45) with semantic epochs correlated to upstream commits; full xmllint/xmlcatalog/xsltproc CLIs; differential-court-verified C API closure; three-DSO ELF packaging (libxml2.so.16 core + libxslt.so.1/libexslt.so.0 facades, upstream NEEDED chain); fail-closed oracle-isolated function-signature ABI plane (SOURCE_PROTOTYPE + MACHINE_ABI fingerprints, zero silent omissions) and the libc default allocator (ALLOCATOR-DEFAULT-001) verified byte-identical; proof-scoped safety commentary (0 unaccounted unsafe sites); residual ledger 79 FIXED / 3 OPEN; 1183 tests passing.
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
//! XPath 1.0 Core Function Library (§25).
//!
//! Implements all XPath 1.0 core functions as specified in §4 of the
//! XPath 1.0 Recommendation.
//!
//! # UPSTREAM-PARITY
//!
//! All functions follow the XPath 1.0 specification and libxml2
//! observable behavior, including edge cases and historical quirks.
//!
//! # Courts
//!
//! XPATH-FUNCTIONS-*
//!
//! # Upstream contract
//!
//! Mirrors the core-function library of upstream `xpath.c`
//! (`SRC-LIBXML2-2.15.0-XPATH-C`, parity target libxml2 2.15.3 oracle):
//! the 25 XPath 1.0 §4 functions (node-set, string, boolean, number
//! groups) with libxml2 observable edge cases.
//!
//! # Conceptual behavior
//!
//! Implements each function over already-evaluated `XPathValue` arguments
//! with the upstream argument-count and coercion behavior: node-set
//! functions (last, position, count, id, local-name, namespace-uri, name),
//! string functions (string, concat, starts-with, substring, translate,
//! ...), boolean functions and number functions (number, sum, floor,
//! ceiling, round). number()/string() route through the R-000166 number
//! formatter (1e9/1e-5 scientific threshold, DBL_DIG=15 fraction digits).
//!
//! # Ownership & safety invariants
//!
//! Functions return owned `XPathValue`s; node-set arguments are borrowed
//! views over the tree (valid for the call). No function stores or caches
//! argument pointers — values are copied at the boundary, so the registry
//! is safe to share.
//!
//! # Historical quirks & epochs
//!
//! R-000114 (attribute string-value must be the attribute content, not
//! empty) and R-000166 (full double-precision value-of printing) were
//! fixed against the 2.15.3 oracle; the number() corpus (967/967 cases)
//! locks the formatting epoch. The E-008 stable libxslt epoch means any
//! function-level divergence is a candidate bug, not an epoch difference.
//!
//! # Deliberate oddities
//!
//! round()/floor()/ceiling() reproduce libxml2 IEEE-754 handling
//! (including negative zero and NaN propagation) rather than Rust
//! rounding helpers, which differ on ties and sign.
//!
//! # Proving courts
//!
//! XPATH-FUNCTIONS-* differential probes and the 967/967 number() corpus
//! compare results byte-identical against the oracle; the XSLT courts
//! (CLI-XSLTPROC-0014/0015/0017) exercise value-of/format-number through
//! these functions.
//!
//! # Tempting simplifications that would break parity
//!
//! Do not delegate number formatting to Rust float formatting: the
//! scientific threshold, digit counts and exponent padding are
//! oracle-observable (R-000166). Do not coerce arguments more eagerly
//! than upstream (e.g. empty node-sets to string) — R-000114 proved the
//! string-value rules are observable.

use crate::xml::xpath::context::XPathContext;
use crate::xml::xpath::types::{node_string_value, string_to_number, NodeSet, XPathValue};
use std::collections::HashMap;

/// Type alias for XPath functions.
///
/// Functions receive already-evaluated arguments as `XPathValue` slices.
pub type XPathFunction = fn(&mut XPathContext, &[XPathValue]) -> Result<XPathValue, String>;

/// Get all registered XPath core functions.
pub fn core_functions() -> HashMap<String, XPathFunction> {
    let mut funcs: HashMap<String, XPathFunction> = HashMap::new();

    // Node set functions (§4.1)
    funcs.insert("last".into(), fn_last);
    funcs.insert("position".into(), fn_position);
    funcs.insert("count".into(), fn_count);
    funcs.insert("id".into(), fn_id);
    funcs.insert("local-name".into(), fn_local_name);
    funcs.insert("namespace-uri".into(), fn_namespace_uri);
    funcs.insert("name".into(), fn_name);

    // String functions (§4.2)
    funcs.insert("string".into(), fn_string);
    funcs.insert("concat".into(), fn_concat);
    funcs.insert("starts-with".into(), fn_starts_with);
    funcs.insert("contains".into(), fn_contains);
    funcs.insert("substring-before".into(), fn_substring_before);
    funcs.insert("substring-after".into(), fn_substring_after);
    funcs.insert("substring".into(), fn_substring);
    funcs.insert("string-length".into(), fn_string_length);
    funcs.insert("normalize-space".into(), fn_normalize_space);
    funcs.insert("translate".into(), fn_translate);

    // Boolean functions (§4.3)
    funcs.insert("boolean".into(), fn_boolean);
    funcs.insert("not".into(), fn_not);
    funcs.insert("true".into(), fn_true);
    funcs.insert("false".into(), fn_false);
    funcs.insert("lang".into(), fn_lang);

    // Number functions (§4.4)
    funcs.insert("number".into(), fn_number);
    funcs.insert("sum".into(), fn_sum);
    funcs.insert("floor".into(), fn_floor);
    funcs.insert("ceiling".into(), fn_ceiling);
    funcs.insert("round".into(), fn_round);

    funcs
}

// ═══════════════════════════════════════════════════════════════════════════════
// Helper: extract typed arguments
// ═══════════════════════════════════════════════════════════════════════════════

fn get_string_arg(args: &[XPathValue], index: usize) -> String {
    if index < args.len() {
        args[index].as_string()
    } else {
        String::new()
    }
}

fn get_number_arg(args: &[XPathValue], index: usize) -> f64 {
    if index < args.len() {
        args[index].as_number()
    } else {
        f64::NAN
    }
}

fn get_boolean_arg(args: &[XPathValue], index: usize) -> bool {
    if index < args.len() {
        args[index].as_boolean()
    } else {
        false
    }
}

fn get_node_set_arg(args: &[XPathValue], index: usize) -> NodeSet {
    if index < args.len() {
        match &args[index] {
            XPathValue::NodeSet(ns) => ns.clone(),
            _ => NodeSet::new(),
        }
    } else {
        NodeSet::new()
    }
}

fn get_first_node(
    ctx: &XPathContext,
    args: &[XPathValue],
    index: usize,
) -> Option<*mut crate::abi::structs::_xmlNode> {
    if index < args.len() {
        match &args[index] {
            XPathValue::NodeSet(ns) => ns.first(),
            _ => None,
        }
    } else {
        // Default to context node
        Some(ctx.context_node)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Node Set Functions (§4.1)
// ═══════════════════════════════════════════════════════════════════════════════

/// last() — context size.
const fn fn_last(ctx: &mut XPathContext, _args: &[XPathValue]) -> Result<XPathValue, String> {
    Ok(XPathValue::Number(ctx.last() as f64))
}

/// position() — context position.
const fn fn_position(ctx: &mut XPathContext, _args: &[XPathValue]) -> Result<XPathValue, String> {
    Ok(XPathValue::Number(ctx.position() as f64))
}

/// count(node-set) — number of nodes in node-set.
fn fn_count(_ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    let ns = get_node_set_arg(args, 0);
    Ok(XPathValue::Number(ns.len() as f64))
}

/// id(object) — select elements by ID.
const fn fn_id(_ctx: &mut XPathContext, _args: &[XPathValue]) -> Result<XPathValue, String> {
    // id() is complex: requires DTD validation to know which attributes are ID.
    // For now, return empty node-set.
    Ok(XPathValue::NodeSet(NodeSet::new()))
}

/// local-name(node-set?) — local part of name.
///
/// # Safety
///
/// - The node returned by `get_first_node` must be NULL or a valid
///   `_xmlNode` that stays alive for the call; its `name` field must be
///   NULL or a valid NUL-terminated string.
fn fn_local_name(ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    let node = get_first_node(ctx, args, 0);
    if let Some(node) = node {
        unsafe {
            let name = crate::xml::string::xmlstr_to_string((*node).name);
            // Strip prefix if present
            if let Some(pos) = name.find(':') {
                Ok(XPathValue::String(name[pos + 1..].to_string()))
            } else {
                Ok(XPathValue::String(name))
            }
        }
    } else {
        Ok(XPathValue::String(String::new()))
    }
}

/// namespace-uri(node-set?) — namespace URI of node.
///
/// # Safety
///
/// - The node returned by `get_first_node` must be NULL or a valid
///   `_xmlNode` that stays alive for the call; its `ns` pointer, when
///   non-NULL, must point to a valid `_xmlNs` whose `href` is NULL or a
///   valid NUL-terminated string.
fn fn_namespace_uri(ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    let node = get_first_node(ctx, args, 0);
    if let Some(node) = node {
        unsafe {
            if let Some(ns) = (*node).ns.as_ref() {
                let uri = crate::xml::string::xmlstr_to_string(ns.href);
                Ok(XPathValue::String(uri))
            } else {
                Ok(XPathValue::String(String::new()))
            }
        }
    } else {
        Ok(XPathValue::String(String::new()))
    }
}

/// name(node-set?) — QName of node.
///
/// # Safety
///
/// - The node returned by `get_first_node` must be NULL or a valid
///   `_xmlNode` that stays alive for the call; its `name` field must be
///   NULL or a valid NUL-terminated string.
fn fn_name(ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    let node = get_first_node(ctx, args, 0);
    if let Some(node) = node {
        unsafe {
            let name = crate::xml::string::xmlstr_to_string((*node).name);
            Ok(XPathValue::String(name))
        }
    } else {
        Ok(XPathValue::String(String::new()))
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// String Functions (§4.2)
// ═══════════════════════════════════════════════════════════════════════════════

/// string(object?) — convert to string.
fn fn_string(ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    if args.is_empty() {
        // Default: context node's string value
        Ok(XPathValue::String(node_string_value(ctx.context_node)))
    } else {
        Ok(XPathValue::String(args[0].as_string()))
    }
}

/// concat(string, string, ...) — concatenate strings.
fn fn_concat(_ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    let mut result = String::new();
    for arg in args {
        result.push_str(&arg.as_string());
    }
    Ok(XPathValue::String(result))
}

/// starts-with(string1, string2) — check prefix.
fn fn_starts_with(_ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    let s1 = get_string_arg(args, 0);
    let s2 = get_string_arg(args, 1);
    Ok(XPathValue::Boolean(s1.starts_with(&s2)))
}

/// contains(string1, string2) — check substring.
fn fn_contains(_ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    let s1 = get_string_arg(args, 0);
    let s2 = get_string_arg(args, 1);
    Ok(XPathValue::Boolean(s1.contains(&s2)))
}

/// substring-before(string1, string2) — before first occurrence.
fn fn_substring_before(_ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    let s1 = get_string_arg(args, 0);
    let s2 = get_string_arg(args, 1);
    if let Some(pos) = s1.find(&s2) {
        Ok(XPathValue::String(s1[..pos].to_string()))
    } else {
        Ok(XPathValue::String(String::new()))
    }
}

/// substring-after(string1, string2) — after first occurrence.
fn fn_substring_after(_ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    let s1 = get_string_arg(args, 0);
    let s2 = get_string_arg(args, 1);
    if let Some(pos) = s1.find(&s2) {
        Ok(XPathValue::String(s1[pos + s2.len()..].to_string()))
    } else {
        Ok(XPathValue::String(String::new()))
    }
}

/// substring(string, number, number?) — substring extraction.
///
/// UPSTREAM-PARITY: XPath substring uses 1-based indexing with rounding.
fn fn_substring(_ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    let s = get_string_arg(args, 0);
    let start = get_number_arg(args, 1);
    let has_length = args.len() >= 3;
    let length = if has_length {
        get_number_arg(args, 2)
    } else {
        f64::MAX
    };

    let start_rounded = start.round() as isize;
    let length_rounded = length.round() as isize;

    // XPath 1.0: 1-based indexing
    let start_index = if start_rounded < 1 {
        0
    } else {
        (start_rounded - 1) as usize
    };
    let length = if length_rounded < 0 {
        0
    } else {
        length_rounded as usize
    };

    if start_index >= s.len() || length == 0 {
        Ok(XPathValue::String(String::new()))
    } else {
        let end = std::cmp::min(start_index + length, s.len());
        Ok(XPathValue::String(s[start_index..end].to_string()))
    }
}

/// string-length(string?) — length of string.
fn fn_string_length(ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    let s = if args.is_empty() {
        node_string_value(ctx.context_node)
    } else {
        get_string_arg(args, 0)
    };
    Ok(XPathValue::Number(s.len() as f64))
}

/// normalize-space(string?) — normalize whitespace.
fn fn_normalize_space(ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    let s = if args.is_empty() {
        node_string_value(ctx.context_node)
    } else {
        get_string_arg(args, 0)
    };
    let normalized: Vec<&str> = s.split_whitespace().collect();
    Ok(XPathValue::String(normalized.join(" ")))
}

/// translate(string1, string2, string3) — character translation.
fn fn_translate(_ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    let s = get_string_arg(args, 0);
    let from = get_string_arg(args, 1);
    let to = get_string_arg(args, 2);

    let result: String = s
        .chars()
        .map(|c| {
            if let Some(pos) = from.find(c) {
                if pos < to.len() {
                    to.chars().nth(pos).unwrap_or(c)
                } else {
                    '\0' // Remove character
                }
            } else {
                c
            }
        })
        .filter(|&c| c != '\0')
        .collect();

    Ok(XPathValue::String(result))
}

// ═══════════════════════════════════════════════════════════════════════════════
// Boolean Functions (§4.3)
// ═══════════════════════════════════════════════════════════════════════════════

/// boolean(object) — convert to boolean.
fn fn_boolean(_ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    Ok(XPathValue::Boolean(get_boolean_arg(args, 0)))
}

/// not(boolean) — logical NOT.
fn fn_not(_ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    Ok(XPathValue::Boolean(!get_boolean_arg(args, 0)))
}

/// true() — constant true.
const fn fn_true(_ctx: &mut XPathContext, _args: &[XPathValue]) -> Result<XPathValue, String> {
    Ok(XPathValue::Boolean(true))
}

/// false() — constant false.
const fn fn_false(_ctx: &mut XPathContext, _args: &[XPathValue]) -> Result<XPathValue, String> {
    Ok(XPathValue::Boolean(false))
}

/// lang(string) — language test.
///
/// # Safety
///
/// - `ctx.context_node` must be NULL or a valid `_xmlNode`; the walk up
///   the `parent` chain and through each node's `properties` must only
///   touch valid nodes and attributes whose `name` and child `content`
///   fields are NULL or valid NUL-terminated strings; the chain must stay
///   alive and acyclic for the duration of the call.
fn fn_lang(ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    let lang = get_string_arg(args, 0);
    let mut node = ctx.context_node;
    unsafe {
        while !node.is_null() {
            let mut prop = (*node).properties;
            while !prop.is_null() {
                let attr_name = crate::xml::string::xmlstr_to_string((*prop).name);
                if attr_name == "lang" || attr_name == "xml:lang" {
                    // Attribute value is stored in children (text node's content)
                    if !(*prop).children.is_null() {
                        let attr_val =
                            crate::xml::string::xmlstr_to_string((*(*prop).children).content);
                        if attr_val.to_lowercase() == lang.to_lowercase()
                            || attr_val
                                .to_lowercase()
                                .starts_with(&format!("{}-", lang.to_lowercase()))
                        {
                            return Ok(XPathValue::Boolean(true));
                        }
                    }
                }
                prop = (*prop).next;
            }
            node = (*node).parent;
        }
    }
    Ok(XPathValue::Boolean(false))
}

// ═══════════════════════════════════════════════════════════════════════════════
// Number Functions (§4.4)
// ═══════════════════════════════════════════════════════════════════════════════

/// number(object?) — convert to number.
fn fn_number(ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    if args.is_empty() {
        Ok(XPathValue::Number(string_to_number(&node_string_value(
            ctx.context_node,
        ))))
    } else {
        Ok(XPathValue::Number(get_number_arg(args, 0)))
    }
}

/// sum(node-set) — sum of string->number conversions.
fn fn_sum(_ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    let ns = get_node_set_arg(args, 0);
    let mut total = 0.0;
    for node in ns.iter() {
        let s = node_string_value(node);
        total += string_to_number(&s);
    }
    Ok(XPathValue::Number(total))
}

/// floor(number) — largest integer <= value.
fn fn_floor(_ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    let n = get_number_arg(args, 0);
    Ok(XPathValue::Number(n.floor()))
}

/// ceiling(number) — smallest integer >= value.
fn fn_ceiling(_ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    let n = get_number_arg(args, 0);
    Ok(XPathValue::Number(n.ceil()))
}

/// round(number) — round to nearest integer.
///
/// UPSTREAM-PARITY: XPath 1.0 rounds towards positive infinity for .5 cases.
/// Rust's f64::round() rounds half away from zero, which differs for negative .5 values.
/// See XPath 1.0 §4.4.
fn fn_round(_ctx: &mut XPathContext, args: &[XPathValue]) -> Result<XPathValue, String> {
    let n = get_number_arg(args, 0);
    if n.is_nan() || n.is_infinite() || n == 0.0 {
        return Ok(XPathValue::Number(n));
    }
    // Rust's f64::round() uses "round half away from zero"
    // XPath 1.0 uses "round half towards positive infinity"
    // These differ for negative numbers with .5 fractional part
    let rust_rounded = n.round();
    let result = if n.is_sign_negative() && (n - rust_rounded).abs() == 0.5 {
        // XPath: move towards positive infinity (i.e., add 1.0 to the Rust result)
        rust_rounded + 1.0
    } else {
        rust_rounded
    };
    Ok(XPathValue::Number(result))
}

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

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

    #[test]
    fn test_true_false() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        assert!(fn_true(&mut ctx, &[]).unwrap().as_boolean());
        assert!(!fn_false(&mut ctx, &[]).unwrap().as_boolean());
    }

    #[test]
    fn test_boolean_conversion() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        assert!(fn_boolean(&mut ctx, &[XPathValue::Boolean(true)])
            .unwrap()
            .as_boolean());
        assert!(!fn_boolean(&mut ctx, &[XPathValue::Boolean(false)])
            .unwrap()
            .as_boolean());
    }

    #[test]
    fn test_not() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        assert!(!fn_not(&mut ctx, &[XPathValue::Boolean(true)])
            .unwrap()
            .as_boolean());
        assert!(fn_not(&mut ctx, &[XPathValue::Boolean(false)])
            .unwrap()
            .as_boolean());
    }

    #[test]
    fn test_number_round() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        assert_eq!(
            fn_floor(&mut ctx, &[XPathValue::Number(3.7)])
                .unwrap()
                .as_number(),
            3.0
        );
        assert_eq!(
            fn_ceiling(&mut ctx, &[XPathValue::Number(3.2)])
                .unwrap()
                .as_number(),
            4.0
        );
        assert_eq!(
            fn_round(&mut ctx, &[XPathValue::Number(3.5)])
                .unwrap()
                .as_number(),
            4.0
        );
        assert_eq!(
            fn_round(&mut ctx, &[XPathValue::Number(-3.5)])
                .unwrap()
                .as_number(),
            -3.0
        );
    }

    #[test]
    fn test_string_functions() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        assert_eq!(
            fn_concat(
                &mut ctx,
                &[
                    XPathValue::String("a".into()),
                    XPathValue::String("b".into()),
                    XPathValue::String("c".into())
                ]
            )
            .unwrap()
            .as_string(),
            "abc"
        );
        assert!(fn_starts_with(
            &mut ctx,
            &[
                XPathValue::String("hello".into()),
                XPathValue::String("he".into())
            ]
        )
        .unwrap()
        .as_boolean());
        assert!(!fn_starts_with(
            &mut ctx,
            &[
                XPathValue::String("hello".into()),
                XPathValue::String("x".into())
            ]
        )
        .unwrap()
        .as_boolean());
        assert!(fn_contains(
            &mut ctx,
            &[
                XPathValue::String("hello".into()),
                XPathValue::String("ell".into())
            ]
        )
        .unwrap()
        .as_boolean());
        assert_eq!(
            fn_string_length(&mut ctx, &[XPathValue::String("hello".into())])
                .unwrap()
                .as_number(),
            5.0
        );
    }

    #[test]
    fn test_core_functions_registered() {
        let funcs = core_functions();
        assert!(funcs.contains_key("last"));
        assert!(funcs.contains_key("position"));
        assert!(funcs.contains_key("count"));
        assert!(funcs.contains_key("string"));
        assert!(funcs.contains_key("concat"));
        assert!(funcs.contains_key("boolean"));
        assert!(funcs.contains_key("not"));
        assert!(funcs.contains_key("number"));
        assert!(funcs.contains_key("sum"));
        assert!(funcs.contains_key("floor"));
        assert!(funcs.contains_key("ceiling"));
        assert!(funcs.contains_key("round"));
        assert!(funcs.contains_key("name"));
        assert!(funcs.contains_key("local-name"));
        assert_eq!(funcs.len(), 27);
        assert!(funcs.contains_key("namespace-uri"));
    }
}