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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
//! Content validation (element validation, text content, facets).
use std::sync::Arc;
use crate::error::{ErrorLevel, ValidationErrorType};
use crate::schema::types::{ComplexType, NsName, TypeDef};
use crate::schema::xsd::primitive::PrimitiveKind;
use super::super::ValidationMode;
use super::super::state::ElementContext;
use super::OnePassSchemaValidator;
impl OnePassSchemaValidator {
/// Main element validation logic.
pub(crate) fn validate_element(
&mut self,
name: &Arc<str>,
prefix: Option<&str>,
qualified_name: &Arc<str>,
namespace: Option<&str>,
attributes: &[(&str, &str)],
) {
// Anti-regression guardrail: count every element unconditionally,
// before any lookup or early return.
self.counters.elements_validated += 1;
// C1: the interned qualified name is built once at the tag boundary and
// threaded here, so neither the lookup nor the error paths re-`format!`
// it. `qualified_name` equals `name` when there is no prefix.
let qname: &str = qualified_name.as_ref();
// C3: hold a local clone of the schema Arc so the looked-up ElementDef
// is decoupled from `self` and stays borrowable across the &mut self
// calls below. This lets identity constraints be passed as a slice
// instead of cloning the constraint Vec on every element.
let schema = Arc::clone(&self.schema);
// Optimization: Try local name lookup first (most common case)
// Also try namespace URI lookup if prefix lookup fails (handles prefix mismatch)
let elem_def = self.lookup_element_optimized(&schema, name, prefix, qname, namespace);
// Value constraints and nillability come from the governing element
// declaration. For a child matched inline in the parent's content
// model, the local declaration governs; these are merged in below.
let mut elem_nillable = elem_def.map(|e| e.nillable).unwrap_or(false);
let elem_abstract = elem_def.map(|e| e.is_abstract).unwrap_or(false);
let mut elem_default = elem_def.and_then(|e| e.default.clone());
let mut elem_fixed = elem_def.and_then(|e| e.fixed.clone());
let elem_known = elem_def.is_some();
let elem_constraints: &[crate::schema::types::CompiledConstraint] =
elem_def.map(|e| e.constraints.as_slice()).unwrap_or(&[]);
let nilled = attributes
.iter()
.any(|&(n, v)| n == "xsi:nil" && v.trim() == "true");
// Check if this element is expected by the parent (inline element definition)
let is_expected_by_parent = self.is_element_expected_by_parent(name);
// Count this child toward the parent's wildcard occurrence bound when
// its namespace matches the wildcard's namespace set. The bound check
// at element end (only decidable when the wildcard is the sole
// particle) must not count non-matching children (DOM parity).
{
let len = self.state.element_stack.len();
if len >= 2 {
let matches = self
.state
.element_stack
.get(len - 2)
.and_then(|parent| parent.flattened_children.as_ref())
.and_then(|fc| {
fc.wildcard
.as_ref()
.filter(|_| fc.constraints.is_empty())
.map(|w| w.matches(namespace))
})
.unwrap_or(false);
if matches && let Some(parent) = self.state.element_stack.get_mut(len - 2) {
parent.wildcard_matched += 1;
}
}
}
// Wildcard handling: a skip wildcard admits this whole subtree
// without validation; a lax wildcard admits undeclared elements.
let wildcard_mode = self.parent_wildcard_mode(name, namespace, is_expected_by_parent);
if wildcard_mode == Some(crate::schema::types::ProcessContents::Skip) {
// The skipped child still consumes a slot in the parent's
// content model.
self.step_parent_automaton(qname, name, namespace, false);
if let Some(ctx) = self.state.current_element_mut() {
ctx.schema_validated = true;
ctx.wildcard_mode = Some(crate::schema::types::ProcessContents::Skip);
}
return;
}
let schema_has_elements = !self.schema.elements_ns.is_empty();
// Priority: inline element definition > global element definition
// This is important when the same element name exists both as a global element
// and as an inline element in the parent's content model with different types.
// For example, gml:exterior in Solid (SurfacePropertyType) vs Polygon (AbstractRingPropertyType)
if is_expected_by_parent {
// Try the inline element (declared in the parent's type) first.
// The global-element fallback is computed only when the inline
// lookup finds nothing, so the hot path (inline hit) no longer
// pays for a redundant per-element type resolution. `elem_def`
// borrows the locally-cloned schema Arc, so it stays valid across
// the &mut self inline lookup.
let child_local_sym = self.current_local_sym();
let info = self.get_inline_element_info(child_local_sym, name);
// When the child matches a local declaration in the parent's
// content model, that declaration's value constraints govern.
// Merge monotonically (prefer a present local constraint, else keep
// the global one) so a `ref=` to a global element with a fixed
// value is not lost.
if info.found {
if let Some(positional) = info.positional.as_ref() {
// Same name declared at multiple positions with differing
// value constraints: pick by occurrence index. The parent
// counted this child at push time, so occurrence N (1-based)
// maps to declaration N-1, clamped to the last (excess
// occurrences are content-model errors reported elsewhere).
let len = self.state.element_stack.len();
let occurrence = if len >= 2 {
self.state.element_stack[len - 2].get_child_count(name)
} else {
1
};
let idx = (occurrence.max(1) as usize - 1).min(positional.len() - 1);
let vc = &positional[idx];
if vc.default.is_some() {
elem_default = vc.default.clone();
}
if vc.fixed.is_some() {
elem_fixed = vc.fixed.clone();
}
elem_nillable = elem_nillable || vc.nillable;
} else {
if info.default.is_some() {
elem_default = info.default.clone();
}
if info.fixed.is_some() {
elem_fixed = info.fixed.clone();
}
elem_nillable = elem_nillable || info.nillable;
}
}
// Use inline type if available, otherwise fall back to global element
let (type_ref, type_ns, flattened_children, anon_type) = if info.type_ref.is_some()
|| info.flattened.is_some()
|| info.inline_type.is_some()
{
(
info.type_ref.clone(),
info.type_ns.clone(),
info.flattened.clone(),
info.inline_type.clone(),
)
} else if let Some(elem) = elem_def {
(
elem.type_ref.as_deref().map(Arc::from),
elem.type_ns.clone(),
self.get_flattened_children_for_element(elem),
elem.inline_type.clone(),
)
} else {
(None, None, None, None)
};
// Content-model automaton replaces the count-based occurrence
// and order checks when the parent's type has one.
if !self.step_parent_automaton(qname, name, namespace, true) {
// Check max_occurs against parent's expected constraints
self.validate_max_occurs(name);
// Check sequence order against parent's expected constraints
self.validate_sequence_order(name);
}
// Update current element context with type info. The type symbol
// encodes the resolved (namespace, local) identity so child
// resolution keyed on it is collision-free across namespaces.
let type_sym = self.type_identity_sym(type_ns.as_ref(), type_ref.as_deref());
if let Some(ctx) = self.state.current_element_mut() {
ctx.schema_validated = true;
ctx.type_ref = type_ref;
ctx.type_sym = type_sym;
ctx.type_ns = type_ns;
ctx.flattened_children = flattened_children;
ctx.inline_type = anon_type;
ctx.nillable = elem_nillable;
}
} else if let Some(elem) = elem_def {
// Global element found - get type information from cache
let type_ref: Option<Arc<str>> = elem.type_ref.as_deref().map(Arc::from);
let type_ns = elem.type_ns.clone();
let flattened_children = self.get_flattened_children_for_element(elem);
let anon_type = elem.inline_type.clone();
if !self.step_parent_automaton(qname, name, namespace, true) {
// Check max_occurs against parent's expected constraints
self.validate_max_occurs(name);
// Check sequence order against parent's expected constraints
self.validate_sequence_order(name);
}
// Update current element context with type info. The type symbol
// encodes the resolved (namespace, local) identity so child
// resolution keyed on it is collision-free across namespaces.
let type_sym = self.type_identity_sym(type_ns.as_ref(), type_ref.as_deref());
if let Some(ctx) = self.state.current_element_mut() {
ctx.schema_validated = true;
ctx.type_ref = type_ref;
ctx.type_sym = type_sym;
ctx.type_ns = type_ns;
ctx.flattened_children = flattened_children;
ctx.inline_type = anon_type;
ctx.nillable = elem_nillable;
}
} else if wildcard_mode == Some(crate::schema::types::ProcessContents::Lax) {
// Undeclared element admitted by a lax wildcard; its subtree
// keeps lax processing. It still consumes a content-model slot.
self.step_parent_automaton(qname, name, namespace, false);
if let Some(ctx) = self.state.current_element_mut() {
ctx.schema_validated = true;
ctx.wildcard_mode = Some(crate::schema::types::ProcessContents::Lax);
}
} else {
// Element not found in schema
if self.mode == ValidationMode::Strict && schema_has_elements {
let error = self
.make_error(
ValidationErrorType::UnknownElement,
format!("element '{}' is not declared in schema", qname),
)
.with_node_name(qname)
.with_level(ErrorLevel::Error);
self.add_error(error);
}
}
// xsi:type substitution: validate the element against the named type
// instead of the declared one (when the substitution is allowed).
if let Some(xsi_type) = attributes
.iter()
.find(|&&(n, _)| n == "xsi:type")
.map(|&(_, v)| v)
{
let declared = self
.state
.current_element()
.and_then(|ctx| ctx.type_ref.clone());
// C4: the xsi:type QName is interpreted against the instance
// document's in-scope namespace declarations.
match super::super::xsi_type::resolve_xsi_type(
&schema,
declared.as_deref(),
xsi_type,
|p| self.state.resolve_prefix(p).map(str::to_string),
) {
Ok(substituted) => {
let flattened = match self.schema.get_type(&substituted) {
Some(TypeDef::Complex(complex)) => {
Some(Arc::new(self.compute_flattened_children(complex)))
}
_ => None,
};
let substituted_sym = self.symbols.intern(&substituted).0;
let substituted: Arc<str> = Arc::from(substituted);
if let Some(ctx) = self.state.current_element_mut() {
ctx.type_ref = Some(substituted);
ctx.type_sym = Some(substituted_sym);
// The substituted type is resolved through the string
// key (`resolve_xsi_type` returns a bare/qualified key),
// so clear any resolved `type_ns` from the declared type
// — leaving it set would misdirect the ns-first
// resolution to the declared (pre-substitution) type.
ctx.type_ns = None;
if flattened.is_some() {
ctx.flattened_children = flattened;
}
}
}
Err(message) => {
let error = self
.make_error(
ValidationErrorType::InvalidAttributeValue,
format!("element '{}': {}", qname, message),
)
.with_node_name(qname)
.with_level(ErrorLevel::Error);
self.add_error(error);
}
}
}
// An abstract element may not appear in the instance directly.
if elem_abstract {
let error = self
.make_error(
ValidationErrorType::InvalidContent,
format!(
"element '{}' is abstract and cannot be used directly",
qname
),
)
.with_node_name(qname)
.with_level(ErrorLevel::Error);
self.add_error(error);
}
// xsi:nil handling: only nillable declarations may carry it.
if nilled && elem_known && !elem_nillable {
let error = self
.make_error(
ValidationErrorType::InvalidAttributeValue,
format!(
"element '{}' is not nillable but has xsi:nil=\"true\"",
qname
),
)
.with_node_name(qname)
.with_level(ErrorLevel::Error);
self.add_error(error);
}
if let Some(ctx) = self.state.current_element_mut() {
ctx.nilled = nilled;
ctx.default_value = elem_default;
ctx.fixed_value = elem_fixed;
}
// Identity constraints: open scopes declared on this element, and
// match this element against the selectors of enclosing scopes.
self.identity_element_start(elem_constraints, attributes);
// Validate attributes
self.validate_attributes(name, attributes);
}
/// The namespace-safe cache-key symbol for an element's resolved type.
/// When the compile-time `(namespace, local)` identity is known it is
/// interned as an integer pair — so same-local-name types in different
/// namespaces (e.g. two `ct-A` types) get distinct symbols — otherwise the
/// bare `type_ref` string is interned as a namespace-blind fallback. No
/// per-element allocation: interning is idempotent and pair keys are
/// integers.
fn type_identity_sym(
&mut self,
type_ns: Option<&NsName>,
type_ref: Option<&str>,
) -> Option<u32> {
match (type_ns, type_ref) {
(Some(ns), _) => {
let ns_sym = self.symbols.intern(&ns.namespace_uri);
let local_sym = self.symbols.intern(&ns.local_name);
Some(self.symbols.intern_pair(ns_sym, local_sym).0)
}
(None, Some(tr)) => Some(self.symbols.intern(tr).0),
(None, None) => None,
}
}
/// The local-name symbol of the current (most recently started) element,
/// used to key per-parent-type child resolution memoization.
fn current_local_sym(&self) -> u32 {
self.state
.current_element()
.map(|c| self.symbols.local(super::symbols::SymbolId(c.name_sym)).0)
.unwrap_or(0)
}
/// Handles identity-constraint bookkeeping at element start.
/// The complex type governing the current (most recently started)
/// element, when one is resolvable from its declared or inline type.
/// Used to resolve attribute value-space kinds for identity constraints.
fn current_element_complex_type(&self) -> Option<&ComplexType> {
let ctx = self.state.current_element()?;
let type_def = match ctx.type_ref.as_deref() {
// C4: ns-first (compile-time resolved), string fallback.
Some(tr) => self.schema.type_by_ref(ctx.type_ns.as_ref(), tr),
None => ctx.inline_type.as_ref(),
};
match type_def {
Some(TypeDef::Complex(c)) => Some(c),
_ => None,
}
}
fn identity_element_start(
&mut self,
elem_constraints: &[crate::schema::types::CompiledConstraint],
attributes: &[(&str, &str)],
) {
// C8 (lazy): with no identity scopes open and no constraints declared
// on this element, there is nothing to match and nothing to open —
// skip building the per-element attr_kinds / local_names vectors.
if self.identity_scopes.is_empty() && elem_constraints.is_empty() {
return;
}
let depth = self.state.element_stack.len();
// Resolve the value-space kind of each present attribute once, so the
// identity-constraint field values captured below can be canonicalized
// (e.g. the xs:integer attributes "1" and "01" denote the same key).
let attr_kinds: Vec<Option<PrimitiveKind>> = {
let complex = self.current_element_complex_type();
attributes
.iter()
.map(|&(name, _)| {
let local = name.rsplit(':').next().unwrap_or(name);
complex.and_then(|c| {
super::super::attributes::attribute_primitive_kind(&self.schema, c, local)
})
})
.collect()
};
// Path of local names for elements on the stack (depth 1..=depth).
let local_names: Vec<&str> = self
.state
.element_stack
.iter()
.map(|ctx| ctx.name.rsplit(':').next().unwrap_or(ctx.name.as_ref()))
.collect();
for scope in &mut self.identity_scopes {
// Selector match: relative path from just below the scope.
if depth > scope.depth {
let rel = &local_names[scope.depth..depth];
if super::identity::selector_matches(&scope.selector, rel) {
let mut fields = vec![super::identity::FieldState::Unset; scope.fields.len()];
// Attribute fields on the selected node resolve now.
for (i, field) in scope.fields.iter().enumerate() {
if field.steps.is_empty()
&& let Some(ref attr) = field.attr
{
let mut matched: Option<(usize, &str)> = None;
let mut multiple = false;
for (ai, &(n, v)) in attributes.iter().enumerate() {
if super::identity::attr_matches(n, attr) {
if matched.is_some() {
multiple = true;
} else {
matched = Some((ai, v));
}
}
}
if multiple {
fields[i] = super::identity::FieldState::Multiple;
} else if let Some((ai, v)) = matched {
let canon = crate::schema::xsd::value_compare::identity_key(
attr_kinds[ai],
v,
);
fields[i] = super::identity::FieldState::Set(canon);
}
}
}
scope
.selected
.push(super::identity::SelectedState { depth, fields });
}
}
// Attribute fields on elements below a selected node.
for selected in &mut scope.selected {
if depth > selected.depth {
let rel = &local_names[selected.depth..depth];
for (i, field) in scope.fields.iter().enumerate() {
if let Some(ref attr) = field.attr
&& super::identity::field_steps_match(field, rel)
{
let mut matched: Option<(usize, &str)> = None;
let mut multiple_here = false;
for (ai, &(n, v)) in attributes.iter().enumerate() {
if super::identity::attr_matches(n, attr) {
if matched.is_some() {
multiple_here = true;
} else {
matched = Some((ai, v));
}
}
}
if multiple_here {
selected.fields[i] = super::identity::FieldState::Multiple;
} else if let Some((ai, v)) = matched {
let canon = crate::schema::xsd::value_compare::identity_key(
attr_kinds[ai],
v,
);
selected.fields[i] = match selected.fields[i] {
super::identity::FieldState::Unset => {
super::identity::FieldState::Set(canon)
}
_ => super::identity::FieldState::Multiple,
};
}
}
}
}
}
}
// Open new scopes for constraints declared on this element.
for constraint in elem_constraints {
if let Some(scope) = super::identity::ScopeState::new(constraint, depth) {
self.identity_scopes.push(scope);
}
}
}
/// Handles identity-constraint bookkeeping at element end. `ended_depth`
/// is the stack depth the element had; `ctx` is its popped context.
fn identity_element_end(&mut self, ended_depth: usize, ctx: &ElementContext) {
use crate::schema::types::CompiledConstraintType;
use crate::schema::xsd::constraints::{ConstraintType, IdentityConstraint, KeyValue};
// Canonicalize the ending element's text in its value space so a `.`
// or descendant-text field key compares correctly (e.g. xs:integer
// "01" and "1" denote the same key).
let text_kind: Option<PrimitiveKind> = if let Some(tr) = ctx.type_ref.as_deref() {
// C4: ns-first (compile-time resolved), string fallback.
self.schema
.type_by_ref(ctx.type_ns.as_ref(), tr)
.and_then(|td| {
super::super::attributes::element_text_primitive_kind(&self.schema, td)
})
} else if let Some(ref it) = ctx.inline_type {
super::super::attributes::element_text_primitive_kind(&self.schema, it)
} else {
None
};
let text =
crate::schema::xsd::value_compare::identity_key(text_kind, ctx.text_content.trim());
let ended_local = ctx
.name
.rsplit(':')
.next()
.unwrap_or(ctx.name.as_ref())
.to_string();
// Local names of the still-open ancestors (depth 1..ended_depth).
let local_names: Vec<String> = self
.state
.element_stack
.iter()
.map(|c| {
c.name
.rsplit(':')
.next()
.unwrap_or(c.name.as_ref())
.to_string()
})
.collect();
let mut errors: Vec<String> = Vec::new();
for scope in &mut self.identity_scopes {
// Element-text fields below a selected node.
for selected in &mut scope.selected {
if ended_depth > selected.depth {
let mut rel: Vec<&str> = local_names[selected.depth..ended_depth - 1]
.iter()
.map(|s| s.as_str())
.collect();
rel.push(&ended_local);
for (i, field) in scope.fields.iter().enumerate() {
if field.attr.is_none()
&& !field.steps.is_empty()
&& super::identity::field_steps_match(field, &rel)
{
selected.fields[i] = match selected.fields[i] {
super::identity::FieldState::Unset => {
super::identity::FieldState::Set(text.clone())
}
_ => super::identity::FieldState::Multiple,
};
}
}
}
}
// Finalize selected nodes that end here.
let mut finished = Vec::new();
scope.selected.retain(|selected| {
if selected.depth == ended_depth {
finished.push(selected.fields.clone());
false
} else {
true
}
});
for mut fields in finished {
// A `.` field takes the selected node's own text content.
for (i, field) in scope.fields.iter().enumerate() {
if field.attr.is_none() && field.steps.is_empty() {
fields[i] = super::identity::FieldState::Set(text.clone());
}
}
if fields
.iter()
.any(|f| matches!(f, super::identity::FieldState::Multiple))
{
errors.push(format!(
"{} '{}': a field matches more than one node",
match scope.constraint.constraint_type {
CompiledConstraintType::Key => "key",
CompiledConstraintType::Unique => "unique",
CompiledConstraintType::KeyRef => "keyref",
},
scope.constraint.name
));
continue;
}
let values: Vec<String> = fields
.into_iter()
.map(|f| match f {
super::identity::FieldState::Set(v) => v,
_ => String::new(), // unset = null (empty per KeyValue)
})
.collect();
let value = KeyValue::new(values);
let ic = IdentityConstraint {
name: scope.constraint.name.clone(),
constraint_type: match scope.constraint.constraint_type {
CompiledConstraintType::Unique => ConstraintType::Unique,
CompiledConstraintType::Key => ConstraintType::Key,
CompiledConstraintType::KeyRef => ConstraintType::KeyRef,
},
selector: scope.constraint.selector_xpath.clone(),
fields: scope.constraint.field_xpaths.clone(),
refer: scope.constraint.refer.clone(),
};
if scope.is_keyref() {
self.constraint_validator.add_keyref_value(&ic, value);
} else if value.has_null() {
// A key requires every field present; a unique tuple with a
// null/absent field simply does not participate in the
// uniqueness check (and is not recorded for keyrefs).
if scope.constraint.constraint_type == CompiledConstraintType::Key {
if let Some(idx) = value.values.iter().position(|v| v.is_empty()) {
errors.push(format!(
"null value in key field {} of constraint '{}'",
idx, scope.constraint.name
));
}
}
} else {
// Uniqueness is per scoping-element instance: check against
// this scope's own `seen` set, not the shared name-keyed
// table (that table exists only for cross-scope keyref
// resolution, into which the value is unioned).
if !scope.seen.insert(value.clone()) {
errors.push(format!(
"duplicate value {:?} in constraint '{}'",
value.values, scope.constraint.name
));
}
self.constraint_validator.record_key_value(&ic, value);
}
}
}
// Close scopes whose scoping element ends here.
self.identity_scopes
.retain(|scope| scope.depth != ended_depth);
for message in errors {
let error = self
.make_error(ValidationErrorType::IdentityConstraint, message)
.with_level(ErrorLevel::Error);
self.add_error(error);
}
}
/// Returns the (memoized when named) collected attribute picture of the
/// current element's complex type, or `None` when it has no complex type.
///
/// Resolution mirrors the previous inline logic: explicit `type_ref`
/// first, then an inline (anonymous) type on the context, then the
/// element's inline type from the parent content model. Named types are
/// cached by type name (C7); anonymous types build fresh.
fn collected_element_attrs(
&mut self,
element_name: &Arc<str>,
) -> Option<Arc<super::super::attributes::CollectedAttrs>> {
use super::super::attributes::CollectedAttrs;
// Named type via the context's resolved type identity. The cache keys
// on the ns-safe type symbol so same-local-name types in different
// namespaces do not share collected-attribute sets; resolution prefers
// the resolved `type_ns` over the namespace-blind `type_ref` string.
if let Some((type_ref, type_ns, type_sym)) = self.state.current_element().and_then(|ctx| {
ctx.type_ref
.clone()
.map(|tr| (tr, ctx.type_ns.clone(), ctx.type_sym))
}) {
if let Some(sym) = type_sym
&& let Some(cached) = self.attr_cache.get(&sym)
{
return Some(Arc::clone(cached));
}
let schema = Arc::clone(&self.schema);
let TypeDef::Complex(complex) = schema.type_by_ref(type_ns.as_ref(), &type_ref)? else {
return None;
};
let built = Arc::new(CollectedAttrs::collect(&schema, complex));
if let Some(sym) = type_sym {
self.attr_cache.insert(sym, Arc::clone(&built));
}
return Some(built);
}
// Inline (anonymous) type captured on the context at element start.
if let Some(ctx) = self.state.current_element()
&& let Some(TypeDef::Complex(complex)) = ctx.inline_type.as_ref()
{
return Some(Arc::new(CollectedAttrs::collect(&self.schema, complex)));
}
// Fallback: the element's inline type from the parent content model.
let inline_owned = self.get_element_inline_type(element_name);
if let Some(TypeDef::Complex(complex)) = inline_owned.as_ref() {
return Some(Arc::new(CollectedAttrs::collect(&self.schema, complex)));
}
None
}
/// Validates attributes on an element against the attribute
/// declarations of its complex type.
pub(crate) fn validate_attributes(
&mut self,
element_name: &Arc<str>,
attributes: &[(&str, &str)],
) {
// C7: resolve the (memoized) collected attribute picture of the
// element's complex type. Returns None when the element has no complex
// type, i.e. no attributes to validate.
let Some(collected) = self.collected_element_attrs(element_name) else {
return;
};
let result = {
// Resolve each attribute's namespace from its prefix using the
// in-scope namespace declarations (unprefixed attributes are in
// no namespace).
let with_ns: Vec<(&str, Option<&str>, &str)> = attributes
.iter()
.map(|&(name, value)| {
let ns = name
.split_once(':')
.and_then(|(prefix, _)| self.state.resolve_prefix(prefix));
(name, ns, value)
})
.collect();
super::super::attributes::validate_element_attributes(
&self.schema,
&collected,
with_ns.iter().copied(),
&mut self.facet_cache,
)
};
for message in result.errors {
let error = self
.make_error(
ValidationErrorType::InvalidAttributeValue,
format!("element '{}': {}", element_name, message),
)
.with_node_name(element_name.as_ref())
.with_level(ErrorLevel::Error);
self.add_error(error);
}
self.record_ids(result.ids, result.idrefs);
}
/// Records `xs:ID` values (checking document-wide uniqueness) and
/// `xs:IDREF` values (resolved at the end of the document).
pub(crate) fn record_ids(&mut self, ids: Vec<String>, idrefs: Vec<String>) {
for id in ids {
if !self.seen_ids.insert(id.clone()) {
let error = self
.make_error(
ValidationErrorType::IdentityConstraint,
format!("duplicate ID value '{}'", id),
)
.with_level(ErrorLevel::Error);
self.add_error(error);
}
}
for idref in idrefs {
self.pending_idrefs
.push((idref, self.current_line, self.current_column));
}
}
/// Accumulates text content for the current element.
pub(crate) fn validate_text_content(&mut self, text: &str) {
if let Some(ctx) = self.state.current_element_mut() {
ctx.text_content.push_str(text);
}
}
/// Returns the wildcard processing mode the parent applies to this
/// element: a propagated lax/skip subtree mode, or the parent content
/// model's wildcard when the element is not declared there.
fn parent_wildcard_mode(
&self,
name: &Arc<str>,
namespace: Option<&str>,
is_expected_by_parent: bool,
) -> Option<crate::schema::types::ProcessContents> {
let len = self.state.element_stack.len();
if len < 2 {
return None;
}
let parent = self.state.element_stack.get(len - 2)?;
if let Some(mode) = parent.wildcard_mode {
// Inside a skipped subtree everything is skipped; inside a lax
// subtree undeclared elements stay lax.
match mode {
crate::schema::types::ProcessContents::Skip => return Some(mode),
crate::schema::types::ProcessContents::Lax if !is_expected_by_parent => {
return Some(mode);
}
_ => {}
}
}
if is_expected_by_parent {
return None;
}
let fc = parent.flattened_children.as_ref()?;
let w = fc.wildcard.as_ref()?;
if !fc.constraints.contains_key(name.as_ref()) && w.matches(namespace) {
Some(w.process_contents)
} else {
None
}
}
/// Validates an element when it closes.
/// Enforces an element's `fixed` value constraint on non-empty content,
/// comparing in the value space of the element's simple type (e.g. fixed
/// `1.0` matches content `1.00`). Empty content takes the fixed value as
/// its effective content and is trivially satisfied. Mirrors the DOM
/// engine's fixed-value check and is deliberately type-independent so it
/// covers untyped (anyType) and mixed content too.
fn validate_fixed_value(&mut self, ctx: &ElementContext) {
let Some(fixed) = ctx.fixed_value.clone() else {
return;
};
if ctx.text_content.is_empty() {
return;
}
// Resolve the primitive kind from the element's simple type only
// (None for complex or untyped content → lexical comparison), matching
// the DOM engine.
let kind = if let Some(tr) = ctx.type_ref.as_deref() {
// C4: ns-first (compile-time resolved), string fallback.
match self.schema.type_by_ref(ctx.type_ns.as_ref(), tr) {
Some(TypeDef::Simple(s)) => PrimitiveKind::resolve(&self.schema, s),
_ => None,
}
} else if let Some(TypeDef::Simple(s)) = ctx.inline_type.as_ref() {
PrimitiveKind::resolve(&self.schema, s)
} else {
None
};
let text = ctx.text_content.trim();
if text != fixed.trim()
&& crate::schema::xsd::value_compare::compare_values(kind, text, &fixed)
!= Some(std::cmp::Ordering::Equal)
{
let error = self
.make_error(
ValidationErrorType::InvalidContent,
format!(
"element '{}' must have the fixed value '{}', found '{}'",
ctx.name, fixed, text
),
)
.with_node_name(ctx.name.as_ref())
.with_level(ErrorLevel::Error);
self.add_error(error);
}
}
pub(crate) fn validate_element_end(&mut self) {
// Get the element context being closed
if let Some(ctx) = self.state.pop_element() {
// Identity constraint bookkeeping (works on the popped depth)
if !self.identity_scopes.is_empty() {
let ended_depth = self.state.element_stack.len() + 1;
self.identity_element_end(ended_depth, &ctx);
}
// A subtree admitted by a skip wildcard is not validated.
if ctx.wildcard_mode == Some(crate::schema::types::ProcessContents::Skip) {
return;
}
// Wildcard occurrence bounds, decidable only when the wildcard
// is the sole particle of the content model.
if let Some(fc) = &ctx.flattened_children
&& let Some(w) = &fc.wildcard
&& fc.constraints.is_empty()
{
// Only children whose namespace matched the wildcard's
// namespace set participate in the occurrence bound; the
// count is maintained at element start (DOM parity —
// non-matching children previously slipped through).
let matched: u32 = ctx.wildcard_matched;
if matched < w.min_occurs {
let error = self
.make_error(
ValidationErrorType::TooFewOccurrences,
format!(
"element '{}' requires at least {} wildcard-matched child element(s), found {}",
ctx.name, w.min_occurs, matched
),
)
.with_node_name(ctx.name.as_ref())
.with_level(ErrorLevel::Error);
self.add_error(error);
}
if let Some(max) = w.max_occurs
&& matched > max
{
let error = self
.make_error(
ValidationErrorType::TooManyOccurrences,
format!(
"element '{}' allows at most {} wildcard-matched child element(s), found {}",
ctx.name, max, matched
),
)
.with_node_name(ctx.name.as_ref())
.with_level(ErrorLevel::Error);
self.add_error(error);
}
}
// A nilled element must be empty.
if ctx.nilled && (!ctx.text_content.trim().is_empty() || !ctx.child_counts.is_empty()) {
let error = self
.make_error(
ValidationErrorType::InvalidContent,
format!(
"element '{}' has xsi:nil=\"true\" but is not empty",
ctx.name
),
)
.with_node_name(ctx.name.as_ref())
.with_level(ErrorLevel::Error);
self.add_error(error);
}
// Element fixed-value constraint, checked independently of the
// element's type (like the DOM engine) so it also covers untyped
// (anyType) and mixed content that the type-driven text path skips.
self.validate_fixed_value(&ctx);
// Always run type validation — primitive types (e.g., xs:integer)
// need to reject empty content, while types whose lexical space
// allows empty (xs:string and derivatives) pass through cheaply.
self.validate_text_content_against_type(&ctx);
// Validate required children were present: the content-model
// automaton's acceptance check when available, count-based
// minOccurs otherwise.
if !self.finish_automaton(&ctx) {
self.validate_min_occurs(&ctx);
}
}
}
}