xsd-schema 0.1.0

XML Schema (XSD 1.0/1.1) validator with PSVI and a built-in XPath 2.0 engine
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
//! Sequence operations for XPath evaluation.
//!
//! This module implements XPath 2.0 sequence operations:
//! - Union (|) - node-only, returns nodes in document order
//! - Intersect - node-only, returns nodes in document order
//! - Except - node-only, returns nodes in document order
//!
//! Note: Union, intersect, and except are NODE-ONLY operations in XPath 2.0.
//! Applying them to atomic values results in XPTY0004.

use std::collections::HashSet;

use crate::types::value::XmlValue;

use super::error::XPathError;
use super::item_set::{ItemSet, XPathComparer, XPathEqualityComparer};
use super::iterator::XmlItem;
use super::DomNavigator;

// ============================================================================
// Node-only sequence operations (union, intersect, except)
// ============================================================================

/// Compute the union of two node sequences.
///
/// Returns all nodes from both sequences, deduplicated by node identity,
/// sorted in document order.
///
/// # XPath Semantics
///
/// The union operator `|` is defined only for node sequences. The result
/// contains all nodes that are in either operand, in document order, with
/// duplicates removed.
///
/// # Errors
///
/// Returns XPTY0004 if either sequence contains non-node items.
pub fn union_nodes<N: DomNavigator + Clone>(
    left: Vec<XmlItem<N>>,
    right: Vec<XmlItem<N>>,
) -> Result<Vec<XmlItem<N>>, XPathError> {
    let mut result: ItemSet<XmlItem<N>> = ItemSet::with_capacity(left.len() + right.len());
    let eq_comparer = XPathEqualityComparer::new();

    // Add all items from left, checking they are nodes
    for item in left {
        if !matches!(item, XmlItem::Node(_)) {
            return Err(XPathError::type_mismatch(
                "node()*".to_string(),
                "atomic value".to_string(),
            ));
        }
        // Check for duplicates using node identity
        let is_duplicate = result
            .iter()
            .any(|existing| eq_comparer.equals(existing, &item));
        if !is_duplicate {
            result.add(item);
        }
    }

    // Add items from right that aren't already in result
    for item in right {
        if !matches!(item, XmlItem::Node(_)) {
            return Err(XPathError::type_mismatch(
                "node()*".to_string(),
                "atomic value".to_string(),
            ));
        }
        let is_duplicate = result
            .iter()
            .any(|existing| eq_comparer.equals(existing, &item));
        if !is_duplicate {
            result.add(item);
        }
    }

    // Sort in document order
    let comparer = XPathComparer::new();
    result.sort_with(&comparer);

    Ok(result.into_iter().collect())
}

/// Compute the intersection of two node sequences.
///
/// Returns nodes that appear in both sequences, sorted in document order.
///
/// # XPath Semantics
///
/// The intersect operator returns all nodes that are in both operands,
/// in document order.
///
/// # Errors
///
/// Returns XPTY0004 if either sequence contains non-node items.
pub fn intersect_nodes<N: DomNavigator + Clone>(
    left: Vec<XmlItem<N>>,
    right: Vec<XmlItem<N>>,
) -> Result<Vec<XmlItem<N>>, XPathError> {
    // Validate that all items are nodes
    for item in &left {
        if !matches!(item, XmlItem::Node(_)) {
            return Err(XPathError::type_mismatch(
                "node()*".to_string(),
                "atomic value".to_string(),
            ));
        }
    }
    for item in &right {
        if !matches!(item, XmlItem::Node(_)) {
            return Err(XPathError::type_mismatch(
                "node()*".to_string(),
                "atomic value".to_string(),
            ));
        }
    }

    let eq_comparer = XPathEqualityComparer::new();
    let mut result: ItemSet<XmlItem<N>> = ItemSet::new();

    // Find nodes in left that also exist in right
    for left_item in left {
        let in_right = right.iter().any(|r| eq_comparer.equals(&left_item, r));
        if in_right {
            // Check we haven't already added this node
            let already_added = result
                .iter()
                .any(|existing| eq_comparer.equals(existing, &left_item));
            if !already_added {
                result.add(left_item);
            }
        }
    }

    // Sort in document order
    let comparer = XPathComparer::new();
    result.sort_with(&comparer);

    Ok(result.into_iter().collect())
}

/// Compute the difference of two node sequences (left except right).
///
/// Returns nodes that appear in left but not in right, sorted in document order.
///
/// # XPath Semantics
///
/// The except operator returns all nodes that are in the first operand
/// but not in the second operand, in document order.
///
/// # Errors
///
/// Returns XPTY0004 if either sequence contains non-node items.
pub fn except_nodes<N: DomNavigator + Clone>(
    left: Vec<XmlItem<N>>,
    right: Vec<XmlItem<N>>,
) -> Result<Vec<XmlItem<N>>, XPathError> {
    // Validate that all items are nodes
    for item in &left {
        if !matches!(item, XmlItem::Node(_)) {
            return Err(XPathError::type_mismatch(
                "node()*".to_string(),
                "atomic value".to_string(),
            ));
        }
    }
    for item in &right {
        if !matches!(item, XmlItem::Node(_)) {
            return Err(XPathError::type_mismatch(
                "node()*".to_string(),
                "atomic value".to_string(),
            ));
        }
    }

    let eq_comparer = XPathEqualityComparer::new();
    let mut result: ItemSet<XmlItem<N>> = ItemSet::new();

    // Find nodes in left that do NOT exist in right
    for left_item in left {
        let in_right = right.iter().any(|r| eq_comparer.equals(&left_item, r));
        if !in_right {
            // Check we haven't already added this node
            let already_added = result
                .iter()
                .any(|existing| eq_comparer.equals(existing, &left_item));
            if !already_added {
                result.add(left_item);
            }
        }
    }

    // Sort in document order
    let comparer = XPathComparer::new();
    result.sort_with(&comparer);

    Ok(result.into_iter().collect())
}

// ============================================================================
// Atomic value sequence operations (for fn:distinct-values, etc.)
// ============================================================================

/// Compute the union of two atomic value sequences (deduplicates by value equality).
///
/// Note: This is NOT the XPath `|` operator (which is node-only).
/// This is for internal use with atomic value sequences.
pub fn union_atomic_values(left: Vec<XmlValue>, right: Vec<XmlValue>) -> Vec<XmlValue> {
    let mut seen = HashSet::new();
    let mut result = Vec::with_capacity(left.len() + right.len());

    for item in left.into_iter().chain(right) {
        let key = item.to_string_value();
        if !seen.contains(&key) {
            seen.insert(key);
            result.push(item);
        }
    }

    result
}

/// Compute the intersection of two atomic value sequences.
///
/// Note: This is NOT the XPath `intersect` operator (which is node-only).
pub fn intersect_atomic_values(left: Vec<XmlValue>, right: Vec<XmlValue>) -> Vec<XmlValue> {
    let right_set: HashSet<String> = right.iter().map(|v| v.to_string_value()).collect();

    let mut seen = HashSet::new();
    let mut result = Vec::new();

    for item in left {
        let key = item.to_string_value();
        if right_set.contains(&key) && !seen.contains(&key) {
            seen.insert(key);
            result.push(item);
        }
    }

    result
}

/// Compute the difference of two atomic value sequences.
///
/// Note: This is NOT the XPath `except` operator (which is node-only).
pub fn except_atomic_values(left: Vec<XmlValue>, right: Vec<XmlValue>) -> Vec<XmlValue> {
    let right_set: HashSet<String> = right.iter().map(|v| v.to_string_value()).collect();

    let mut seen = HashSet::new();
    let mut result = Vec::new();

    for item in left {
        let key = item.to_string_value();
        if !right_set.contains(&key) && !seen.contains(&key) {
            seen.insert(key);
            result.push(item);
        }
    }

    result
}

// ============================================================================
// General sequence utilities
// ============================================================================

/// Check if a sequence is empty.
pub fn is_empty(values: &[XmlValue]) -> bool {
    values.is_empty()
}

/// Check if a sequence contains exactly one item.
pub fn is_singleton(values: &[XmlValue]) -> bool {
    values.len() == 1
}

/// Get the first item from a sequence, if any.
pub fn head(values: &[XmlValue]) -> Option<&XmlValue> {
    values.first()
}

/// Get all items except the first from a sequence.
pub fn tail(values: &[XmlValue]) -> &[XmlValue] {
    if values.is_empty() {
        &[]
    } else {
        &values[1..]
    }
}

/// Reverse a sequence.
pub fn reverse(values: Vec<XmlValue>) -> Vec<XmlValue> {
    let mut result = values;
    result.reverse();
    result
}

/// Get the count of items in a sequence.
pub fn count(values: &[XmlValue]) -> usize {
    values.len()
}

/// Check if a sequence contains a specific value (by value equality).
pub fn contains_value(values: &[XmlValue], target: &XmlValue) -> bool {
    let target_str = target.to_string_value();
    values.iter().any(|v| v.to_string_value() == target_str)
}

/// Insert an item at a specific position.
pub fn insert_before(values: Vec<XmlValue>, position: usize, item: XmlValue) -> Vec<XmlValue> {
    let mut result = values;
    let pos = position.min(result.len());
    result.insert(pos, item);
    result
}

/// Remove an item at a specific position.
pub fn remove_at(values: Vec<XmlValue>, position: usize) -> Vec<XmlValue> {
    let mut result = values;
    if position < result.len() {
        result.remove(position);
    }
    result
}

/// Subsequence (slice) of a sequence.
///
/// XPath uses 1-based indexing.
pub fn subsequence(values: &[XmlValue], start: usize, length: Option<usize>) -> Vec<XmlValue> {
    if start == 0 || start > values.len() {
        return Vec::new();
    }

    let start_idx = start - 1; // Convert to 0-based
    let end_idx = match length {
        Some(len) => (start_idx + len).min(values.len()),
        None => values.len(),
    };

    values[start_idx..end_idx].to_vec()
}

/// Get distinct values from a sequence (removes duplicates by value equality).
///
/// This implements fn:distinct-values which works on atomic values.
pub fn distinct_values(values: Vec<XmlValue>) -> Vec<XmlValue> {
    let mut seen = HashSet::new();
    let mut result = Vec::with_capacity(values.len());

    for item in values {
        let key = item.to_string_value();
        if !seen.contains(&key) {
            seen.insert(key);
            result.push(item);
        }
    }

    result
}

/// Find the index of a value in a sequence (1-based, XPath style).
///
/// Returns 0 if not found.
pub fn index_of(values: &[XmlValue], target: &XmlValue) -> usize {
    let target_str = target.to_string_value();
    for (i, v) in values.iter().enumerate() {
        if v.to_string_value() == target_str {
            return i + 1; // 1-based
        }
    }
    0
}

/// Deep equality check between two atomic value sequences.
pub fn deep_equal(left: &[XmlValue], right: &[XmlValue]) -> bool {
    if left.len() != right.len() {
        return false;
    }

    for (l, r) in left.iter().zip(right.iter()) {
        if l.to_string_value() != r.to_string_value() {
            return false;
        }
    }

    true
}

// ============================================================================
// Backwards compatibility aliases (deprecated)
// ============================================================================

/// Deprecated: Use `union_atomic_values` for atomic sequences or `union_nodes` for nodes.
#[deprecated(note = "Use union_atomic_values for atomic sequences or union_nodes for nodes")]
pub fn union_values(left: Vec<XmlValue>, right: Vec<XmlValue>) -> Vec<XmlValue> {
    union_atomic_values(left, right)
}

/// Deprecated: Use `intersect_atomic_values` for atomic sequences or `intersect_nodes` for nodes.
#[deprecated(
    note = "Use intersect_atomic_values for atomic sequences or intersect_nodes for nodes"
)]
pub fn intersect_values(left: Vec<XmlValue>, right: Vec<XmlValue>) -> Vec<XmlValue> {
    intersect_atomic_values(left, right)
}

/// Deprecated: Use `except_atomic_values` for atomic sequences or `except_nodes` for nodes.
#[deprecated(note = "Use except_atomic_values for atomic sequences or except_nodes for nodes")]
pub fn except_values(left: Vec<XmlValue>, right: Vec<XmlValue>) -> Vec<XmlValue> {
    except_atomic_values(left, right)
}

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

    fn int_values(nums: &[i32]) -> Vec<XmlValue> {
        nums.iter()
            .map(|&n| XmlValue::integer(BigInt::from(n)))
            .collect()
    }

    fn str_values(strs: &[&str]) -> Vec<XmlValue> {
        strs.iter().map(|&s| XmlValue::string(s)).collect()
    }

    #[test]
    fn test_union_atomic() {
        let left = int_values(&[1, 2, 3]);
        let right = int_values(&[2, 3, 4]);
        let result = union_atomic_values(left, right);
        assert_eq!(count(&result), 4);
    }

    #[test]
    fn test_intersect_atomic() {
        let left = int_values(&[1, 2, 3]);
        let right = int_values(&[2, 3, 4]);
        let result = intersect_atomic_values(left, right);
        assert_eq!(count(&result), 2);
    }

    #[test]
    fn test_except_atomic() {
        let left = int_values(&[1, 2, 3]);
        let right = int_values(&[2, 3, 4]);
        let result = except_atomic_values(left, right);
        assert_eq!(count(&result), 1);
    }

    #[test]
    fn test_is_empty() {
        assert!(is_empty(&[]));
        assert!(!is_empty(&int_values(&[1])));
    }

    #[test]
    fn test_is_singleton() {
        assert!(!is_singleton(&[]));
        assert!(is_singleton(&int_values(&[1])));
        assert!(!is_singleton(&int_values(&[1, 2])));
    }

    #[test]
    fn test_head_tail() {
        let values = int_values(&[1, 2, 3]);
        assert_eq!(head(&values).unwrap().to_string_value(), "1");
        assert_eq!(tail(&values).len(), 2);

        let empty: Vec<XmlValue> = Vec::new();
        assert!(head(&empty).is_none());
        assert!(tail(&empty).is_empty());
    }

    #[test]
    fn test_reverse() {
        let values = int_values(&[1, 2, 3]);
        let reversed = reverse(values);
        assert_eq!(reversed[0].to_string_value(), "3");
        assert_eq!(reversed[2].to_string_value(), "1");
    }

    #[test]
    fn test_subsequence() {
        let values = int_values(&[1, 2, 3, 4, 5]);

        // Start at 2, length 3 -> [2, 3, 4]
        let sub = subsequence(&values, 2, Some(3));
        assert_eq!(count(&sub), 3);

        // Start at 3, no length -> [3, 4, 5]
        let sub = subsequence(&values, 3, None);
        assert_eq!(count(&sub), 3);

        // Out of bounds
        let sub = subsequence(&values, 10, None);
        assert!(is_empty(&sub));
    }

    #[test]
    fn test_distinct_values() {
        let values = str_values(&["a", "b", "a", "c", "b"]);
        let distinct = distinct_values(values);
        assert_eq!(count(&distinct), 3);
    }

    #[test]
    fn test_index_of() {
        let values = str_values(&["a", "b", "c"]);
        assert_eq!(index_of(&values, &XmlValue::string("b")), 2);
        assert_eq!(index_of(&values, &XmlValue::string("z")), 0);
    }

    #[test]
    fn test_deep_equal() {
        let a = int_values(&[1, 2, 3]);
        let b = int_values(&[1, 2, 3]);
        let c = int_values(&[1, 2, 4]);
        let d = int_values(&[1, 2]);

        assert!(deep_equal(&a, &b));
        assert!(!deep_equal(&a, &c));
        assert!(!deep_equal(&a, &d));
    }

    #[test]
    fn test_insert_before() {
        let values = int_values(&[1, 3]);
        let result = insert_before(values, 1, XmlValue::integer(BigInt::from(2)));
        assert_eq!(count(&result), 3);
        assert_eq!(result[1].to_string_value(), "2");
    }

    #[test]
    fn test_remove_at() {
        let values = int_values(&[1, 2, 3]);
        let result = remove_at(values, 1);
        assert_eq!(count(&result), 2);
    }

    // Tests for node-only operations would require a DomNavigator implementation
    // which is available in integration tests with roxmltree
}