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
//! Validation state management during streaming.
use std::sync::Arc;
use smallvec::SmallVec;
use crate::namespace::Namespace;
use crate::schema::types::{ContentModelType, FlattenedChildren, NsName};
/// One lexical scope of namespace declarations: `(prefix, uri)` pairs, the
/// prefix `""` denoting the default namespace.
type NsScope = SmallVec<[(String, Arc<str>); 4]>;
/// Validation state during streaming.
#[derive(Debug, Default)]
pub(crate) struct ValidationState {
/// Current element stack (qname, namespace, occurrence count)
pub element_stack: Vec<ElementContext>,
/// Current depth
pub depth: usize,
/// Namespace bindings at each depth - stores only the diff for each scope
/// This avoids cloning the entire HashMap on each push
pub namespace_stack: Vec<NsScope>,
/// Memoized prefix -> namespace-URI resolutions for the *current* scope
/// chain. Namespace declarations are rare (typically only on the root),
/// so this avoids walking `namespace_stack` on every element start; it
/// is cleared whenever a scope that actually declares bindings is pushed
/// or popped. `None` caches a negative result (unbound / xmlns="").
ns_resolution_cache: SmallVec<[(String, Option<Arc<str>>); 8]>,
}
/// Context for an element being validated.
#[derive(Debug, Clone)]
pub(crate) struct ElementContext {
/// Element name (local name) - stored as Arc<str> to avoid allocation
pub name: Arc<str>,
/// Interned symbol id of the element's qualified name (streaming
/// validator only; the DOM path leaves it at 0). Kept so per-element
/// resolution can be memoized by integer symbol rather than by string.
pub name_sym: u32,
/// Element namespace URI (for future use)
#[allow(dead_code)]
pub namespace: Option<Arc<str>>,
/// Child element occurrence counts - SmallVec for inline storage (most elements have <8 children)
pub child_counts: SmallVec<[(Arc<str>, u32); 8]>,
/// Text content collected
pub text_content: String,
/// Whether this element has been validated against schema
pub schema_validated: bool,
/// Type reference for this element (if known from schema). Shared as an
/// `Arc<str>` so per-element assignment is a refcount bump, not a `String`
/// allocation.
pub type_ref: Option<Arc<str>>,
/// Interned symbol of the element's resolved type identity (streaming
/// validator only). Used as the cache key for resolving this element's
/// children when it is a parent. It is derived from the resolved
/// `(namespace, local)` type identity when available (see
/// `type_identity_sym`), so same-local-name types in different namespaces
/// key distinctly — the string `type_ref` alone would collide.
pub type_sym: Option<u32>,
/// Compile-time resolved `(namespace, local)` of this element's declared
/// type, when known. This is the authoritative type identity (mirrors
/// `ElementDef::type_ns`); resolution prefers it over the namespace-blind
/// `type_ref` string, which is retained only as a fallback.
pub type_ns: Option<NsName>,
/// Pre-computed flattened children constraints from schema cache.
/// Using Arc to avoid cloning for every element - this is a reference to
/// the pre-computed cache in CompiledSchema.
pub flattened_children: Option<Arc<FlattenedChildren>>,
/// Current position in expected sequence for sequence order validation.
pub sequence_index: usize,
/// Content-model automaton cursor (when the type has an automaton).
pub automaton_state: crate::schema::xsd::content_automaton::AutomatonState,
/// Whether the element's declaration is `nillable="true"`. When true and the
/// element is empty, primitive lexical/value-space checks are skipped so an
/// `xsi:nil` element (e.g. an empty `xs:int`) is not rejected as invalid.
pub nillable: bool,
/// Whether the instance element carries `xsi:nil="true"`.
pub nilled: bool,
/// Default value from the element declaration (applies when empty).
pub default_value: Option<String>,
/// Fixed value from the element declaration.
pub fixed_value: Option<String>,
/// Inline (anonymous) type from the element declaration, used when the
/// declaration carries no named type reference.
pub inline_type: Option<crate::schema::types::TypeDef>,
/// Set when this element was admitted by a lax/skip wildcard; its
/// subtree inherits that processing mode.
pub wildcard_mode: Option<crate::schema::types::ProcessContents>,
/// Number of child elements whose namespace matched this element's
/// content-model wildcard (counted only when the wildcard is the sole
/// particle, where the occurrence bound is decidable without an
/// automaton). Children that do NOT match the wildcard's namespace set
/// must not count toward its minOccurs/maxOccurs (DOM parity).
pub wildcard_matched: u32,
}
impl ElementContext {
/// Creates a new ElementContext with an Arc<str> name (zero-copy from parser).
pub fn new(name: Arc<str>, namespace: Option<Arc<str>>) -> Self {
Self {
name,
name_sym: 0,
namespace,
child_counts: SmallVec::new(),
text_content: String::new(),
schema_validated: false,
type_ref: None,
type_sym: None,
type_ns: None,
flattened_children: None,
sequence_index: 0,
automaton_state: Default::default(),
nillable: false,
nilled: false,
default_value: None,
fixed_value: None,
inline_type: None,
wildcard_mode: None,
wildcard_matched: 0,
}
}
/// Creates a new ElementContext from string references (allocates new strings).
/// Used for tests and backward compatibility.
#[allow(dead_code)]
pub fn from_str(name: &str, namespace: Option<&str>) -> Self {
Self::new(Arc::from(name), namespace.map(Arc::from))
}
/// Increments child count using Arc<str> (zero-copy if already tracked).
pub fn increment_child_arc(&mut self, child_name: &Arc<str>) -> u32 {
// Linear search is fast for small N (typically <8 children)
for (name, count) in &mut self.child_counts {
if Arc::ptr_eq(name, child_name) || name.as_ref() == child_name.as_ref() {
*count += 1;
return *count;
}
}
self.child_counts.push((Arc::clone(child_name), 1));
1
}
/// Increments child count from string reference (may allocate if new).
#[allow(dead_code)]
pub fn increment_child(&mut self, child_name: &str) -> u32 {
// Linear search is fast for small N (typically <8 children)
for (name, count) in &mut self.child_counts {
if name.as_ref() == child_name {
*count += 1;
return *count;
}
}
self.child_counts.push((Arc::from(child_name), 1));
1
}
pub fn get_child_count(&self, child_name: &str) -> u32 {
let mut total = 0;
// Check if child_name has a prefix
let has_prefix = child_name.contains(':');
for (name, count) in &self.child_counts {
if name.as_ref() == child_name {
// Exact match
total += count;
} else if !has_prefix {
// child_name is local name only - also match prefixed variants
// e.g., child_name="LinearRing" should match "gml:LinearRing"
if let Some((_prefix, local)) = name.split_once(':') {
if local == child_name {
total += count;
}
}
}
}
total
}
/// Returns the content model type from the flattened children, or Empty if not set.
#[allow(dead_code)]
pub fn content_model_type(&self) -> ContentModelType {
self.flattened_children
.as_ref()
.map(|f| f.content_model_type)
.unwrap_or(ContentModelType::Empty)
}
/// Checks if a child element is expected by this element.
pub fn expects_child(&self, child_name: &str) -> bool {
self.flattened_children
.as_ref()
.map(|f| f.constraints.contains_key(child_name))
.unwrap_or(false)
}
/// Gets the constraint for a child element, if any.
pub fn get_child_constraint(&self, child_name: &str) -> Option<(u32, Option<u32>)> {
self.flattened_children
.as_ref()
.and_then(|f| f.constraints.get(child_name).copied())
}
/// Iterates over expected child constraints.
#[allow(dead_code)]
pub fn expected_children(&self) -> impl Iterator<Item = (&String, &(u32, Option<u32>))> {
self.flattened_children
.iter()
.flat_map(|f| f.constraints.iter())
}
}
impl ValidationState {
pub fn new() -> Self {
Self {
element_stack: Vec::with_capacity(64),
depth: 0,
namespace_stack: vec![SmallVec::new()],
ns_resolution_cache: SmallVec::new(),
}
}
/// Pushes a new element using Arc<str> name (zero-copy from parser).
pub fn push_element(&mut self, name: Arc<str>, namespace: Option<Arc<str>>) {
// Increment child count in parent using Arc<str> for zero-copy
if let Some(parent) = self.element_stack.last_mut() {
parent.increment_child_arc(&name);
}
self.element_stack
.push(ElementContext::new(name, namespace));
self.depth += 1;
}
/// Pushes a new element, recording its interned name symbol (streaming
/// validator hot path).
pub fn push_element_sym(&mut self, name: Arc<str>, namespace: Option<Arc<str>>, name_sym: u32) {
if let Some(parent) = self.element_stack.last_mut() {
parent.increment_child_arc(&name);
}
let mut ctx = ElementContext::new(name, namespace);
ctx.name_sym = name_sym;
self.element_stack.push(ctx);
self.depth += 1;
}
/// Pushes a new element from string references (allocates).
/// Used for tests and backward compatibility.
#[allow(dead_code)]
pub fn push_element_str(&mut self, name: &str, namespace: Option<&str>) {
self.push_element(Arc::from(name), namespace.map(Arc::from));
}
pub fn pop_element(&mut self) -> Option<ElementContext> {
self.depth = self.depth.saturating_sub(1);
self.element_stack.pop()
}
#[allow(dead_code)]
pub fn current_element(&self) -> Option<&ElementContext> {
self.element_stack.last()
}
pub fn current_element_mut(&mut self) -> Option<&mut ElementContext> {
self.element_stack.last_mut()
}
/// Pushes namespace declarations for the current scope.
/// Only stores the diff (new bindings) instead of cloning the entire map.
pub fn push_namespaces(&mut self, decls: &[Namespace]) {
let bindings: NsScope = decls
.iter()
.map(|ns| (ns.prefix().to_string(), Arc::from(ns.uri())))
.collect();
if !bindings.is_empty() {
self.ns_resolution_cache.clear();
}
self.namespace_stack.push(bindings);
}
pub fn pop_namespaces(&mut self) {
if self.namespace_stack.len() > 1
&& let Some(popped) = self.namespace_stack.pop()
&& !popped.is_empty()
{
self.ns_resolution_cache.clear();
}
}
/// Resolves a namespace prefix by searching from innermost to outermost scope.
pub fn resolve_prefix(&self, prefix: &str) -> Option<&str> {
// Search from innermost to outermost scope
for scope in self.namespace_stack.iter().rev() {
for (p, uri) in scope {
if p == prefix {
return Some(uri.as_ref());
}
}
}
None
}
/// Resolves the namespace URI of an element from its prefix (or the
/// in-scope default namespace when it has none). Returns `None` for
/// no-namespace elements: an unbound prefix, no default declaration, or
/// an empty-URI binding (`xmlns=""` un-declares the default namespace).
///
/// Resolutions are memoized until the scope chain changes, so the hot
/// path costs one scan of a handful of cached prefixes.
pub fn resolve_element_namespace(&mut self, prefix: Option<&str>) -> Option<Arc<str>> {
let key = match prefix {
Some(p) if !p.is_empty() => p,
_ => "",
};
if let Some((_, cached)) = self.ns_resolution_cache.iter().find(|(p, _)| p == key) {
return cached.clone();
}
let mut resolved: Option<Arc<str>> = None;
'outer: for scope in self.namespace_stack.iter().rev() {
for (p, uri) in scope {
if p == key {
if !uri.is_empty() {
resolved = Some(Arc::clone(uri));
}
break 'outer;
}
}
}
self.ns_resolution_cache
.push((key.to_string(), resolved.clone()));
resolved
}
/// Returns XPath-like path to current element.
pub fn element_path(&self) -> String {
if self.element_stack.is_empty() {
return "/".to_string();
}
let mut path = String::new();
for ctx in &self.element_stack {
path.push('/');
path.push_str(&ctx.name);
}
path
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_element_context_new() {
let ctx = ElementContext::from_str("test", Some("http://example.com"));
assert_eq!(ctx.name.as_ref(), "test");
assert_eq!(ctx.namespace.as_deref(), Some("http://example.com"));
assert!(ctx.child_counts.is_empty());
assert!(ctx.text_content.is_empty());
assert!(!ctx.schema_validated);
assert!(ctx.type_ref.is_none());
assert!(ctx.flattened_children.is_none());
}
#[test]
fn test_element_context_new_without_namespace() {
let ctx = ElementContext::from_str("test", None);
assert_eq!(ctx.name.as_ref(), "test");
assert!(ctx.namespace.is_none());
}
#[test]
fn test_element_context_increment_child() {
let mut ctx = ElementContext::from_str("parent", None);
assert_eq!(ctx.increment_child("child"), 1);
assert_eq!(ctx.increment_child("child"), 2);
assert_eq!(ctx.increment_child("other"), 1);
assert_eq!(ctx.increment_child("child"), 3);
}
#[test]
fn test_element_context_get_child_count() {
let mut ctx = ElementContext::from_str("parent", None);
assert_eq!(ctx.get_child_count("child"), 0);
ctx.increment_child("child");
assert_eq!(ctx.get_child_count("child"), 1);
ctx.increment_child("child");
assert_eq!(ctx.get_child_count("child"), 2);
assert_eq!(ctx.get_child_count("other"), 0);
}
#[test]
fn test_validation_state_new() {
let state = ValidationState::new();
assert!(state.element_stack.is_empty());
assert_eq!(state.depth, 0);
assert_eq!(state.namespace_stack.len(), 1);
}
#[test]
fn test_validation_state_push_pop_element() {
let mut state = ValidationState::new();
state.push_element_str("root", None);
assert_eq!(state.depth, 1);
assert_eq!(state.element_stack.len(), 1);
state.push_element_str("child", Some("http://ns"));
assert_eq!(state.depth, 2);
assert_eq!(state.element_stack.len(), 2);
let popped = state.pop_element();
assert!(popped.is_some());
assert_eq!(popped.unwrap().name.as_ref(), "child");
assert_eq!(state.depth, 1);
let popped = state.pop_element();
assert!(popped.is_some());
assert_eq!(popped.unwrap().name.as_ref(), "root");
assert_eq!(state.depth, 0);
}
#[test]
fn test_validation_state_child_count_increment() {
let mut state = ValidationState::new();
state.push_element_str("parent", None);
state.push_element_str("child1", None);
state.pop_element();
state.push_element_str("child1", None);
state.pop_element();
state.push_element_str("child2", None);
state.pop_element();
// Parent should have counts: child1=2, child2=1
let parent = state.pop_element().unwrap();
assert_eq!(parent.get_child_count("child1"), 2);
assert_eq!(parent.get_child_count("child2"), 1);
}
#[test]
fn test_validation_state_current_element() {
let mut state = ValidationState::new();
assert!(state.current_element().is_none());
state.push_element_str("root", None);
assert!(state.current_element().is_some());
assert_eq!(state.current_element().unwrap().name.as_ref(), "root");
}
#[test]
fn test_validation_state_current_element_mut() {
let mut state = ValidationState::new();
state.push_element_str("root", None);
if let Some(ctx) = state.current_element_mut() {
ctx.text_content.push_str("hello");
}
assert_eq!(state.current_element().unwrap().text_content, "hello");
}
#[test]
fn test_validation_state_push_pop_namespaces() {
let mut state = ValidationState::new();
assert_eq!(state.namespace_stack.len(), 1);
let decls = vec![Namespace::new(
"ns".to_string(),
"http://example.com".to_string(),
)];
state.push_namespaces(&decls);
assert_eq!(state.namespace_stack.len(), 2);
assert_eq!(state.resolve_prefix("ns"), Some("http://example.com"));
state.pop_namespaces();
assert_eq!(state.namespace_stack.len(), 1);
}
#[test]
fn test_validation_state_resolve_prefix() {
let mut state = ValidationState::new();
assert!(state.resolve_prefix("ns").is_none());
let decls = vec![Namespace::new(
"ns".to_string(),
"http://example.com".to_string(),
)];
state.push_namespaces(&decls);
assert_eq!(state.resolve_prefix("ns"), Some("http://example.com"));
assert!(state.resolve_prefix("other").is_none());
}
#[test]
fn test_validation_state_element_path_empty() {
let state = ValidationState::new();
assert_eq!(state.element_path(), "/");
}
#[test]
fn test_validation_state_element_path() {
let mut state = ValidationState::new();
state.push_element_str("root", None);
assert_eq!(state.element_path(), "/root");
state.push_element_str("child", None);
assert_eq!(state.element_path(), "/root/child");
state.push_element_str("grandchild", None);
assert_eq!(state.element_path(), "/root/child/grandchild");
}
#[test]
fn test_validation_state_pop_empty() {
let mut state = ValidationState::new();
assert!(state.pop_element().is_none());
assert_eq!(state.depth, 0);
}
#[test]
fn test_namespace_stack_pop_minimum() {
let mut state = ValidationState::new();
assert_eq!(state.namespace_stack.len(), 1);
state.pop_namespaces();
// Should not pop below 1
assert_eq!(state.namespace_stack.len(), 1);
state.pop_namespaces();
assert_eq!(state.namespace_stack.len(), 1);
}
/// Test that get_child_count matches local name even when stored with prefix.
/// This is important for substitution group validation where we have:
/// - XML element: `gml:LinearRing` (stored with prefix)
/// - Schema substitution member: `LinearRing` (local name only)
#[test]
fn test_get_child_count_matches_local_name_with_prefix() {
let mut ctx = ElementContext::from_str("parent", None);
// Store child with prefix (as it comes from XML parser)
ctx.increment_child("gml:LinearRing");
// Should find it with exact match
assert_eq!(ctx.get_child_count("gml:LinearRing"), 1);
// Should also find it with local name only (for substitution group lookup)
assert_eq!(
ctx.get_child_count("LinearRing"),
1,
"get_child_count should match local name 'LinearRing' for prefixed child 'gml:LinearRing'"
);
}
#[test]
fn test_get_child_count_matches_local_name_multiple_prefixes() {
let mut ctx = ElementContext::from_str("parent", None);
// Store children with different prefixes but same local name
ctx.increment_child("gml:Ring");
ctx.increment_child("ns:Ring");
// Exact match should find individual counts
assert_eq!(ctx.get_child_count("gml:Ring"), 1);
assert_eq!(ctx.get_child_count("ns:Ring"), 1);
// Local name should find the sum of all prefixed versions
assert_eq!(
ctx.get_child_count("Ring"),
2,
"get_child_count with local name should sum all prefixed variants"
);
}
}