Skip to main content

einvoice_xsd/
validate.rs

1//! Validation of an instance document against a loaded [`Schema`].
2//!
3//! The document is read as a stream of events ([`einvoice_xml::Reader`]): no tree is
4//! built, so that the memory used does not grow with the document, but with the depth
5//! of its elements. The validation keeps one frame per open element whose content is
6//! examined, and skips the content of the others to the end of their element. Error
7//! recovery follows the model of libxml2, which makes error lists comparable with
8//! xmllint:
9//!
10//! * a document element without a declaration, an element matched by a strict
11//!   wildcard without a declaration, and an element whose type is abstract are
12//!   reported and their content is not examined;
13//! * within an element, the first child element that the content type does not
14//!   allow (unexpected in the content model, or any element in simple or empty
15//!   content) is reported and the remaining children of that element are not
16//!   examined; text errors before it are reported once per text node (the text
17//!   between two pieces of markup other than character data and CDATA sections);
18//! * an `xsi:type` that cannot be used is reported and the declared type is used.
19//!
20//! Nothing is copied out of the text but what an error spells out: the text of an
21//! element with simple content is a slice of the text (copied only when references
22//! were replaced in it or comments or processing instructions split it), values are
23//! checked on that slice (whitespace processing builds a new string only when a check
24//! needs the processed value and it differs from a slice of the text), and the
25//! `xs:ID` values seen are slices too. Errors record the byte offset of their
26//! element's start tag; lines and columns are computed at the end, in one pass over
27//! the text.
28//!
29//! The reader refuses documents with a document type declaration, whose internal
30//! subset may declare entities: [`validate`] reads those with `roxmltree` instead (the
31//! entities expanded, attribute defaults not applied), and gives the validation the
32//! same events from its tree.
33
34use std::borrow::Cow;
35use std::collections::{HashMap, HashSet};
36
37use einvoice_xml::{Event, StartElement};
38
39use crate::automaton::{Automaton, State, Term};
40use crate::datatypes::{self, Builtin, WhiteSpace};
41use crate::error::{DocumentError, ErrorKind, Report, ValidationError};
42use crate::model::{
43    ANY_TYPE, AttributeUse, ComplexType, ConstraintKind, Content, ElementId, ProcessContents,
44    Schema, TypeDef, TypeId, ValueConstraint, XSI, clark, facet_problem, namespace_name, quote,
45};
46
47/// How a child element is to be validated.
48#[derive(Clone, Copy)]
49enum Assignment {
50    /// The document element: looked up among the global declarations.
51    Root,
52    /// Against this element declaration.
53    Declared(ElementId),
54    /// Matched by a lax wildcard without a global declaration: `xs:anyType`.
55    Lax,
56}
57
58/// A value of the document: a slice of its text `'d`, or a value the parser built
59/// (references replaced, whitespace normalised), which lives only as long as the
60/// event it comes with.
61#[derive(Clone, Copy)]
62enum Value<'v, 'd> {
63    Document(&'d str),
64    Other(&'v str),
65}
66
67impl Value<'_, '_> {
68    #[expect(
69        clippy::match_same_arms,
70        reason = "the two slices have different lifetimes: one pattern cannot bind both"
71    )]
72    fn as_str(&self) -> &str {
73        match *self {
74            Self::Document(s) => s,
75            Self::Other(s) => s,
76        }
77    }
78}
79
80/// An attribute of an element (namespace declarations are not attributes).
81struct Attribute<'v, 'd> {
82    namespace: Option<&'v str>,
83    local: &'v str,
84    value: Value<'v, 'd>,
85}
86
87/// The start of an element, as the validation reads it: from the streaming reader,
88/// or from a `roxmltree` node.
89trait Start<'d> {
90    /// The namespace name, `None` (or empty) for none.
91    fn namespace(&self) -> Option<&str>;
92    /// The local name.
93    fn local(&self) -> &'d str;
94    /// The byte offset of the start tag in the text.
95    fn offset(&self) -> usize;
96    /// The value of the attribute `local` in the `xsi` namespace.
97    fn xsi(&self, local: &str) -> Option<&str>;
98    /// The namespace name bound to `prefix` (`None` for the default namespace) in the
99    /// scope of the element: as `roxmltree` resolves it, never for the `xml` and
100    /// `xmlns` prefixes, and empty or `None` when the default namespace is undeclared.
101    fn lookup_namespace(&self, prefix: Option<&str>) -> Option<&str>;
102    /// The attributes, in document order.
103    fn attributes(&self) -> impl Iterator<Item = Attribute<'_, 'd>>;
104}
105
106impl<'a> Start<'a> for StartElement<'_, 'a> {
107    fn namespace(&self) -> Option<&str> {
108        self.name().namespace
109    }
110
111    fn local(&self) -> &'a str {
112        self.name().local
113    }
114
115    fn offset(&self) -> usize {
116        self.range().start
117    }
118
119    fn xsi(&self, local: &str) -> Option<&str> {
120        self.attribute(Some(XSI), local).map(AsRef::as_ref)
121    }
122
123    fn lookup_namespace(&self, prefix: Option<&str>) -> Option<&str> {
124        match prefix {
125            Some("xml" | "xmlns") => None,
126            Some(prefix) => StartElement::lookup_namespace(self, prefix),
127            None => StartElement::lookup_namespace(self, ""),
128        }
129    }
130
131    fn attributes(&self) -> impl Iterator<Item = Attribute<'_, 'a>> {
132        StartElement::attributes(self).map(|attribute| Attribute {
133            namespace: attribute.name.namespace,
134            local: attribute.name.local,
135            value: match attribute.value {
136                Cow::Borrowed(value) => Value::Document(value),
137                Cow::Owned(value) => Value::Other(value),
138            },
139        })
140    }
141}
142
143impl<'d> Start<'d> for roxmltree::Node<'d, '_> {
144    fn namespace(&self) -> Option<&str> {
145        self.tag_name().namespace()
146    }
147
148    fn local(&self) -> &'d str {
149        self.tag_name().name()
150    }
151
152    fn offset(&self) -> usize {
153        self.range().start
154    }
155
156    fn xsi(&self, local: &str) -> Option<&str> {
157        self.attribute((XSI, local))
158    }
159
160    fn lookup_namespace(&self, prefix: Option<&str>) -> Option<&str> {
161        self.lookup_namespace_uri(prefix)
162    }
163
164    fn attributes(&self) -> impl Iterator<Item = Attribute<'_, 'd>> {
165        roxmltree::Node::attributes(self).map(|attribute| Attribute {
166            namespace: attribute.namespace(),
167            local: attribute.name(),
168            value: Value::Document(attribute.value()),
169        })
170    }
171}
172
173enum FrameContent<'s, 'd> {
174    Empty {
175        stopped: bool,
176    },
177    Simple {
178        type_id: TypeId,
179        /// The text so far: a slice of the document while there is one text node.
180        text: Cow<'d, str>,
181        /// The value constraint of the element's declaration, if any.
182        constraint: Option<&'s ValueConstraint>,
183        stopped: bool,
184    },
185    Children {
186        automaton: &'s Automaton,
187        mixed: bool,
188        state: State,
189        stopped: bool,
190    },
191}
192
193/// An open element whose content is examined.
194struct Frame<'s, 'd> {
195    /// The byte offset of its start tag.
196    offset: usize,
197    /// Its namespace name ([`Namespaces::id`]) and local name, for its errors.
198    namespace: Option<usize>,
199    local: &'d str,
200    content: FrameContent<'s, 'd>,
201}
202
203/// Up to this many distinct namespace names, one is looked up by a linear scan;
204/// beyond, through the index.
205const SCAN_LIMIT: usize = 16;
206
207/// The namespace names of the open elements, numbered, so that a frame can name its
208/// element in errors after the reader has moved on (the reader's names only live
209/// until its next event).
210#[derive(Default)]
211struct Namespaces {
212    names: Vec<Box<str>>,
213    index: HashMap<Box<str>, usize>,
214}
215
216impl Namespaces {
217    fn id(&mut self, namespace: Option<&str>) -> Option<usize> {
218        let namespace = namespace?;
219        let found = if self.names.len() <= SCAN_LIMIT {
220            self.names.iter().position(|n| **n == *namespace)
221        } else {
222            self.index.get(namespace).copied()
223        };
224        Some(found.unwrap_or_else(|| {
225            let id = self.names.len();
226            self.names.push(namespace.into());
227            self.index.insert(namespace.into(), id);
228            id
229        }))
230    }
231
232    fn name(&self, id: Option<usize>) -> Option<&str> {
233        id.and_then(|id| self.names.get(id)).map(AsRef::as_ref)
234    }
235}
236
237struct Validator<'s, 'd> {
238    schema: &'s Schema,
239    /// The text of the document.
240    text: &'d str,
241    /// Each error with the byte offset of its element; its line and column are
242    /// filled in by [`positions`].
243    errors: Vec<(usize, ValidationError)>,
244    /// The `xs:ID` values seen, whitespace-processed.
245    ids: HashSet<Cow<'d, str>>,
246    /// The `xs:IDREF` values seen, each to be the value of an `xs:ID` of the document
247    /// (checked once it is read).
248    idrefs: Vec<IdRef>,
249    /// Whether the document has a document type declaration (it is read with
250    /// `roxmltree`): it may declare unparsed entities.
251    dtd: bool,
252    namespaces: Namespaces,
253}
254
255/// An `xs:IDREF` value and where it is: the byte offset of its element, the element and
256/// the attribute (`None` for the element's content), in Clark notation.
257struct IdRef {
258    offset: usize,
259    element: String,
260    attribute: Option<String>,
261    value: String,
262}
263
264/// Lines and columns from byte offsets, walking forward through a text.
265struct Cursor<'t> {
266    text: &'t [u8],
267    offset: usize,
268    /// 1-based.
269    line: usize,
270    /// Characters since the start of the line.
271    column: usize,
272}
273
274impl<'t> Cursor<'t> {
275    fn new(text: &'t str) -> Self {
276        Self {
277            text: text.as_bytes(),
278            offset: 0,
279            line: 1,
280            column: 0,
281        }
282    }
283
284    /// The 1-based line and column of the character at byte `offset` (a character
285    /// boundary at or after the previous offset): the lines are counted by line
286    /// feeds, the columns in characters.
287    fn advance(&mut self, offset: usize) -> (u32, u32) {
288        let end = offset.min(self.text.len());
289        for &b in self.text.get(self.offset..end).unwrap_or(&[]) {
290            if b == b'\n' {
291                self.line += 1;
292                self.column = 0;
293            } else if b & 0xC0 != 0x80 {
294                // Not a UTF-8 continuation byte: a character starts here.
295                self.column += 1;
296            }
297        }
298        self.offset = self.offset.max(end);
299        (
300            u32::try_from(self.line).unwrap_or(u32::MAX),
301            u32::try_from(self.column + 1).unwrap_or(u32::MAX),
302        )
303    }
304}
305
306/// The errors in document order (by the position of their element, in the order
307/// they were found for the same element), with their lines and columns.
308fn positions(text: &str, mut errors: Vec<(usize, ValidationError)>) -> Vec<ValidationError> {
309    errors.sort_by_key(|(offset, _)| *offset);
310    let mut cursor = Cursor::new(text);
311    errors
312        .into_iter()
313        .map(|(offset, mut error)| {
314            (error.line, error.column) = cursor.advance(offset);
315            error
316        })
317        .collect()
318}
319
320/// Why a value is not valid.
321enum ValueProblem {
322    /// Not in the lexical space or not allowed by a facet.
323    Invalid(String),
324    /// A valid `xs:ID` that an earlier attribute or element of the document uses.
325    DuplicateId(String),
326    /// A value whose validity this crate does not decide: an `xs:ENTITY` in a document
327    /// with a document type declaration (which may declare unparsed entities).
328    Unsupported(String),
329}
330
331/// Whether a prefix is declared in the scope of a value (an `xs:QName` value is valid
332/// only when it is): the `xml` prefix always is, the `xmlns` prefix never.
333fn declared_prefix(prefix: &str, lookup: impl Fn(&str) -> Option<String>) -> bool {
334    match prefix {
335        "xml" => true,
336        "xmlns" => false,
337        _ => lookup(prefix).is_some_and(|ns| !ns.is_empty()),
338    }
339}
340
341fn element_name<'d>(element: &impl Start<'d>) -> String {
342    clark(namespace_name(element.namespace()), element.local())
343}
344
345/// The error of a text the reader refuses.
346fn malformed(e: &einvoice_xml::Error) -> DocumentError {
347    DocumentError::Malformed {
348        line: e.pos().row,
349        column: e.pos().col,
350        message: e.to_string(),
351    }
352}
353
354/// Validates the text of a document: read with the streaming reader, or, when it has
355/// a document type declaration, with `roxmltree`.
356pub(crate) fn validate(schema: &Schema, xml: &str) -> Result<Report, DocumentError> {
357    let mut reader = einvoice_xml::Reader::new(xml);
358    let mut validation = Validation::new(schema, xml);
359    loop {
360        match reader.next_event() {
361            Ok(Some(event)) => validation.event(event),
362            Ok(None) => return validation.finish(),
363            Err(einvoice_xml::Error::DtdDetected) => return validate_tree(schema, xml),
364            Err(e) => return Err(malformed(&e)),
365        }
366    }
367}
368
369/// [`validate`] on a document with a document type declaration, read with `roxmltree`
370/// (internal subset allowed for entities): the validation is given the events of its
371/// tree, in document order.
372fn validate_tree(schema: &Schema, xml: &str) -> Result<Report, DocumentError> {
373    let options = roxmltree::ParsingOptions {
374        allow_dtd: true,
375        ..roxmltree::ParsingOptions::default()
376    };
377    let doc = roxmltree::Document::parse_with_options(xml, options).map_err(|e| {
378        DocumentError::Malformed {
379            line: e.pos().row,
380            column: e.pos().col,
381            message: e.to_string(),
382        }
383    })?;
384    let mut walk = Walk::new(schema, xml);
385    walk.validator.dtd = true;
386    // The prefixes declared in the scope of an element of the tree.
387    let tree = &doc;
388    let lookup = |id: roxmltree::NodeId| {
389        move |prefix: &str| {
390            tree.get_node(id)
391                .and_then(|node| node.lookup_namespace_uri(Some(prefix)))
392                .map(str::to_owned)
393        }
394    };
395    // The elements open, innermost last: closed when the walk in document order
396    // reaches a node that is not inside them.
397    let mut open: Vec<roxmltree::NodeId> = Vec::new();
398    for node in doc.root().descendants().skip(1) {
399        let parent = node.parent().map(|p| p.id());
400        while let Some(&id) = open.last()
401            && Some(id) != parent
402        {
403            open.pop();
404            walk.end(&lookup(id));
405        }
406        match node.node_type() {
407            roxmltree::NodeType::Element => {
408                walk.start(&node);
409                open.push(node.id());
410            }
411            roxmltree::NodeType::Text => walk.text(Cow::Borrowed(node.text().unwrap_or(""))),
412            roxmltree::NodeType::Comment | roxmltree::NodeType::PI => walk.split_text(),
413            roxmltree::NodeType::Root => {}
414        }
415    }
416    while let Some(id) = open.pop() {
417        walk.end(&lookup(id));
418    }
419    walk.finish()
420}
421
422/// A validation in progress, given the events of a document one by one, in document
423/// order, as [`einvoice_xml::Reader`] reads them: [`Schema::validation`].
424///
425/// This is what [`Schema::validate`] does, for a caller that reads the document
426/// itself, so that one pass over the text checks it for well-formedness (and for
427/// anything else the caller wants to check) and validates it. The events must be
428/// those of a reader of the text given to [`Schema::validation`], every one of them,
429/// up to the end of the document: the validation does not check well-formedness, and
430/// the positions of its errors are byte offsets of that text. An event of a document
431/// the reader then refuses, or a validation finished early, gives a report that
432/// means nothing; it never panics.
433pub struct Validation<'s, 'a> {
434    walk: Walk<'s, 'a>,
435}
436
437impl std::fmt::Debug for Validation<'_, '_> {
438    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
439        f.debug_struct("Validation")
440            .field("errors", &self.walk.validator.errors.len())
441            .field("open", &self.walk.frames.len())
442            .finish_non_exhaustive()
443    }
444}
445
446impl<'s, 'a> Validation<'s, 'a> {
447    pub(crate) fn new(schema: &'s Schema, text: &'a str) -> Self {
448        Self {
449            walk: Walk::new(schema, text),
450        }
451    }
452
453    /// Takes the next event of the document.
454    pub fn event(&mut self, event: Event<'_, 'a>) {
455        match event {
456            Event::Start(start) => self.walk.start(&start),
457            Event::End(end) => self
458                .walk
459                .end(&|prefix: &str| end.lookup_namespace(prefix).map(str::to_owned)),
460            Event::Text(text) => self.walk.text(text.value),
461            Event::Comment(_) | Event::ProcessingInstruction(_) => self.walk.split_text(),
462        }
463    }
464
465    /// The report, once every event is given.
466    ///
467    /// # Errors
468    ///
469    /// [`DocumentError::Unsupported`] when the document needs a feature outside the
470    /// implemented subset (an `xs:ENTITY` value in a document with a document type declaration, whose
471    /// unparsed entities this crate does not read, or a value constraint of a
472    /// declaration taken as a value of a type valid only in a context): the first such element in document order.
473    pub fn finish(self) -> Result<Report, DocumentError> {
474        self.walk.finish()
475    }
476}
477
478/// The state of a validation between two events.
479struct Walk<'s, 'd> {
480    validator: Validator<'s, 'd>,
481    /// The open elements whose content is examined, innermost last.
482    frames: Vec<Frame<'s, 'd>>,
483    /// The number of open elements inside one whose content is not examined, that
484    /// one included; 0 when the innermost open element's content is examined.
485    skipped: usize,
486    /// The text node being read: character data and CDATA sections not separated by
487    /// other markup make one.
488    text: Option<Cow<'d, str>>,
489    /// The first construct outside the supported subset: the rest is not examined.
490    unsupported: Option<DocumentError>,
491}
492
493impl<'s, 'd> Walk<'s, 'd> {
494    fn new(schema: &'s Schema, text: &'d str) -> Self {
495        Self {
496            validator: Validator {
497                schema,
498                text,
499                errors: Vec::new(),
500                ids: HashSet::new(),
501                idrefs: Vec::new(),
502                dtd: false,
503                namespaces: Namespaces::default(),
504            },
505            frames: Vec::new(),
506            skipped: 0,
507            text: None,
508            unsupported: None,
509        }
510    }
511
512    fn start(&mut self, element: &impl Start<'d>) {
513        self.split_text();
514        if self.unsupported.is_some() {
515            return;
516        }
517        if self.skipped > 0 {
518            self.skipped += 1;
519            return;
520        }
521        let assignment = match self.frames.last_mut() {
522            None => Assignment::Root,
523            Some(top) => {
524                let Some(assignment) = self.validator.child(top, element) else {
525                    self.skipped = 1;
526                    return;
527                };
528                assignment
529            }
530        };
531        match self.validator.start(element, assignment) {
532            Ok(Some(frame)) => self.frames.push(frame),
533            Ok(None) => self.skipped = 1,
534            Err(e) => self.unsupported = Some(e),
535        }
536    }
537
538    /// The end of an element; `lookup` gives the namespace bound to a prefix in its
539    /// scope.
540    fn end(&mut self, lookup: &dyn Fn(&str) -> Option<String>) {
541        self.split_text();
542        if self.unsupported.is_some() {
543            return;
544        }
545        if self.skipped > 0 {
546            self.skipped -= 1;
547        } else if let Some(frame) = self.frames.pop()
548            && let Err(e) = self.validator.end(&frame, lookup)
549        {
550            self.unsupported = Some(e);
551        }
552    }
553
554    fn text(&mut self, value: Cow<'d, str>) {
555        if self.unsupported.is_some() || self.skipped > 0 || self.frames.is_empty() {
556            return;
557        }
558        match &mut self.text {
559            None => self.text = Some(value),
560            Some(text) => text.to_mut().push_str(&value),
561        }
562    }
563
564    /// Ends the text node being read, if any (markup other than character data and
565    /// CDATA sections, or the end of the element).
566    fn split_text(&mut self) {
567        if let Some(text) = self.text.take()
568            && let Some(top) = self.frames.last_mut()
569        {
570            self.validator.text(top, text);
571        }
572    }
573
574    fn finish(mut self) -> Result<Report, DocumentError> {
575        self.split_text();
576        if let Some(e) = self.unsupported {
577            return Err(e);
578        }
579        self.validator.resolve_idrefs();
580        Ok(Report {
581            errors: positions(self.validator.text, self.validator.errors),
582        })
583    }
584}
585
586impl<'s, 'd> Validator<'s, 'd> {
587    fn report(&mut self, offset: usize, element: String, kind: ErrorKind, message: String) {
588        self.report_attribute(offset, element, kind, None, message);
589    }
590
591    /// Reports every `xs:IDREF` value that is not the value of an `xs:ID` of the
592    /// document (Part 1, 3.3.4, Validation Root Valid (ID/IDREF Table): no ID/IDREF
593    /// binding may be empty).
594    fn resolve_idrefs(&mut self) {
595        for idref in std::mem::take(&mut self.idrefs) {
596            if !self.ids.contains(idref.value.as_str()) {
597                self.report_attribute(
598                    idref.offset,
599                    idref.element,
600                    ErrorKind::UnresolvedIdref,
601                    idref.attribute,
602                    format!(
603                        "the IDREF {} is not the value of an ID of the document",
604                        quote(&idref.value)
605                    ),
606                );
607            }
608        }
609    }
610
611    fn report_attribute(
612        &mut self,
613        offset: usize,
614        element: String,
615        kind: ErrorKind,
616        attribute: Option<String>,
617        message: String,
618    ) {
619        self.errors.push((
620            offset,
621            ValidationError {
622                kind,
623                line: 0,
624                column: 0,
625                element,
626                attribute,
627                message,
628            },
629        ));
630    }
631
632    /// The name of the element of a frame (its namespace and local name), in Clark
633    /// notation.
634    fn frame_name(&self, namespace: Option<usize>, local: &str) -> String {
635        clark(self.namespaces.name(namespace), local)
636    }
637
638    fn unsupported(&self, offset: usize, message: String) -> DocumentError {
639        let (line, column) = Cursor::new(self.text).advance(offset);
640        DocumentError::Unsupported {
641            line,
642            column,
643            message,
644        }
645    }
646
647    fn type_name(&self, type_id: TypeId) -> String {
648        self.schema.types[type_id]
649            .name()
650            .map_or_else(|| "an anonymous type".to_owned(), ToString::to_string)
651    }
652
653    /// Starts an element: finds its type, checks `xsi:nil`, `xsi:type` and the
654    /// attributes. `None` when its content is not to be examined.
655    fn start(
656        &mut self,
657        element: &impl Start<'d>,
658        assignment: Assignment,
659    ) -> Result<Option<Frame<'s, 'd>>, DocumentError> {
660        let schema = self.schema;
661        let namespace = namespace_name(element.namespace());
662        let local = element.local();
663        let offset = element.offset();
664        let declaration = match assignment {
665            Assignment::Root => {
666                let Some(id) = schema.global_element(namespace, local) else {
667                    self.report(
668                        offset,
669                        element_name(element),
670                        ErrorKind::UnknownRoot,
671                        "no global element declaration for the document element".to_owned(),
672                    );
673                    return Ok(None);
674                };
675                Some(id)
676            }
677            Assignment::Declared(id) => Some(id),
678            Assignment::Lax => None,
679        };
680        let declared_type = declaration.map_or(ANY_TYPE, |id| schema.elements[id].type_id);
681        if declaration.is_some()
682            && let Some(nil) = element.xsi("nil")
683        {
684            let value = datatypes::normalize(nil, WhiteSpace::Collapse);
685            let attribute = Some(clark(Some(XSI), "nil"));
686            if Builtin::Boolean.is_valid(&value) {
687                self.report_attribute(
688                    offset,
689                    element_name(element),
690                    ErrorKind::NotNillable,
691                    attribute,
692                    "xsi:nil on an element whose declaration is not nillable".to_owned(),
693                );
694            } else {
695                self.report_attribute(
696                    offset,
697                    element_name(element),
698                    ErrorKind::InvalidXsiNil,
699                    attribute,
700                    format!("xsi:nil {} is not a boolean", quote(nil)),
701                );
702            }
703        }
704        let mut type_id = declared_type;
705        if let Some(xsi_type) = element.xsi("type")
706            && let Some(local_type) = self.xsi_type(element, xsi_type, declared_type)
707        {
708            type_id = local_type;
709        }
710        if let TypeDef::Complex(ComplexType {
711            is_abstract: true, ..
712        }) = &schema.types[type_id]
713        {
714            let name = self.type_name(type_id);
715            self.report(
716                offset,
717                element_name(element),
718                ErrorKind::AbstractType,
719                format!("the type {name} is abstract"),
720            );
721            return Ok(None);
722        }
723        self.attributes(element, type_id)?;
724        let constraint = declaration.and_then(|id| schema.element_constraint(id));
725        let content = match &schema.types[type_id] {
726            TypeDef::Simple(_) => FrameContent::Simple {
727                type_id,
728                text: Cow::Borrowed(""),
729                constraint,
730                stopped: false,
731            },
732            TypeDef::Complex(complex) => match &complex.content {
733                Content::Empty => FrameContent::Empty { stopped: false },
734                Content::Simple(simple) => FrameContent::Simple {
735                    type_id: *simple,
736                    text: Cow::Borrowed(""),
737                    constraint,
738                    stopped: false,
739                },
740                Content::ElementOnly(automaton) => FrameContent::Children {
741                    automaton,
742                    mixed: false,
743                    state: None,
744                    stopped: false,
745                },
746                Content::Mixed(automaton) => FrameContent::Children {
747                    automaton,
748                    mixed: true,
749                    state: None,
750                    stopped: false,
751                },
752            },
753        };
754        Ok(Some(Frame {
755            offset,
756            namespace: self.namespaces.id(namespace),
757            local,
758            content,
759        }))
760    }
761
762    /// Resolves `xsi:type`: the type to use, or `None` (error reported) to keep the
763    /// declared type.
764    fn xsi_type(
765        &mut self,
766        element: &impl Start<'d>,
767        value: &str,
768        declared: TypeId,
769    ) -> Option<TypeId> {
770        let schema = self.schema;
771        let offset = element.offset();
772        let collapsed = datatypes::normalize(value, WhiteSpace::Collapse);
773        let Some((prefix, local)) = datatypes::split_qname(&collapsed) else {
774            self.report_attribute(
775                offset,
776                element_name(element),
777                ErrorKind::InvalidXsiType,
778                Some(clark(Some(XSI), "type")),
779                format!("xsi:type {} is not a QName", quote(value)),
780            );
781            return None;
782        };
783        let namespace = if let Some(p) = prefix {
784            let Some(ns) = element.lookup_namespace(Some(p)) else {
785                self.report_attribute(
786                    offset,
787                    element_name(element),
788                    ErrorKind::InvalidXsiType,
789                    Some(clark(Some(XSI), "type")),
790                    format!("xsi:type {}: prefix {p:?} is not declared", quote(value)),
791                );
792                return None;
793            };
794            Some(ns)
795        } else {
796            namespace_name(element.lookup_namespace(None))
797        };
798        let Some(type_id) = schema.global_type(namespace, local) else {
799            self.report_attribute(
800                offset,
801                element_name(element),
802                ErrorKind::InvalidXsiType,
803                Some(clark(Some(XSI), "type")),
804                format!(
805                    "xsi:type {} does not resolve to a type definition",
806                    quote(value)
807                ),
808            );
809            return None;
810        };
811        if !schema.is_derived_from(type_id, declared) {
812            let (name, declared_name) = (self.type_name(type_id), self.type_name(declared));
813            self.report_attribute(
814                offset,
815                element_name(element),
816                ErrorKind::InvalidXsiType,
817                Some(clark(Some(XSI), "type")),
818                format!("xsi:type {name} is not derived from the declared type {declared_name}"),
819            );
820            return None;
821        }
822        Some(type_id)
823    }
824
825    /// Checks a value, before whitespace processing, against a simple type; when
826    /// valid, registers `xs:ID` values, and returns the `xs:IDREF` values it holds,
827    /// which the caller records. `lookup` gives the namespace bound to a prefix where
828    /// the value is (for an `xs:QName`). The processed value is only built when an
829    /// `enumeration` facet, the `xs:ID` registry or a type valid in a context needs
830    /// it; a value that is a slice of the text is registered as a slice of it.
831    fn check_value(
832        &mut self,
833        type_id: TypeId,
834        raw: Value<'_, 'd>,
835        lookup: &dyn Fn(&str) -> Option<String>,
836    ) -> Result<Vec<String>, ValueProblem> {
837        let schema = self.schema;
838        let TypeDef::Simple(simple) = &schema.types[type_id] else {
839            return Err(ValueProblem::Invalid(format!(
840                "{} is not a simple type",
841                self.type_name(type_id)
842            )));
843        };
844        let builtin = simple.builtin;
845        if !builtin.is_valid_raw(raw.as_str()) {
846            return Err(ValueProblem::Invalid(format!(
847                "{} is not a valid value of {}",
848                quote(raw.as_str()),
849                self.type_name(type_id)
850            )));
851        }
852        let is_id = builtin == Builtin::Id;
853        if !is_id && !builtin.needs_context() && !schema.has_facets(type_id) {
854            return Ok(Vec::new());
855        }
856        let white_space = simple.builtin.white_space();
857        let value: Cow<'d, str> = match raw {
858            Value::Document(raw) => datatypes::normalize(raw, white_space),
859            Value::Other(raw) => Cow::Owned(datatypes::normalize(raw, white_space).into_owned()),
860        };
861        if let Some(problem) = facet_problem(&schema.types, type_id, &value) {
862            return Err(ValueProblem::Invalid(format!(
863                "{} is {}",
864                quote(raw.as_str()),
865                problem.describe(&self.type_name(type_id))
866            )));
867        }
868        let invalid = |why: &str| {
869            Err(ValueProblem::Invalid(format!(
870                "{} is not a valid value of {}: {why}",
871                quote(raw.as_str()),
872                self.type_name(type_id)
873            )))
874        };
875        match builtin {
876            Builtin::Id => {
877                if !self.ids.insert(value) {
878                    return Err(ValueProblem::DuplicateId(format!(
879                        "the ID {} is already used in the document",
880                        quote(raw.as_str())
881                    )));
882                }
883            }
884            Builtin::QName => {
885                // Valid lexically: an NCName, or a prefix and an NCName.
886                if let Some((Some(prefix), _)) = datatypes::split_qname(&value)
887                    && !declared_prefix(prefix, lookup)
888                {
889                    return invalid(&format!("the prefix {prefix:?} is not declared"));
890                }
891            }
892            // Part 2, 3.2.19: the value space is the notations declared in the schema,
893            // and the supported subset has no xs:notation.
894            Builtin::Notation => return invalid("the schema declares no notation"),
895            // Part 2, 3.3.11: the name of an unparsed entity of the document type
896            // declaration, which a document without one cannot have.
897            Builtin::Entity | Builtin::Entities if self.dtd => {
898                return Err(ValueProblem::Unsupported(format!(
899                    "{} names an unparsed entity of the document type declaration: not implemented",
900                    quote(raw.as_str())
901                )));
902            }
903            Builtin::Entity | Builtin::Entities => {
904                return invalid(
905                    "the document has no document type declaration, so no unparsed entity",
906                );
907            }
908            Builtin::IdRef | Builtin::IdRefs => {
909                return Ok(value.split(' ').map(str::to_owned).collect());
910            }
911            _ => {}
912        }
913        Ok(Vec::new())
914    }
915
916    /// Whether two valid values of a simple type, before whitespace processing,
917    /// are the same value (Part 2, 2.2.1): the test of a fixed value constraint.
918    fn same_value(&self, type_id: TypeId, a: &str, b: &str) -> bool {
919        let TypeDef::Simple(simple) = &self.schema.types[type_id] else {
920            return false;
921        };
922        let builtin = simple.builtin;
923        let white_space = builtin.white_space();
924        let a = datatypes::normalize(a, white_space);
925        let b = datatypes::normalize(b, white_space);
926        // The loader refuses fixed values on the types without a value key.
927        match (builtin.value_key(&a), builtin.value_key(&b)) {
928            (Some(a), Some(b)) => a == b,
929            _ => false,
930        }
931    }
932
933    /// Why a value constraint of an element's declaration is not a valid value of
934    /// the simple type that the element's actual type gives its content, if it is
935    /// not (it is valid for the declared type: the loader checks it).
936    ///
937    /// # Errors
938    ///
939    /// A type whose values are valid only in a context ([`Builtin::needs_context`]):
940    /// the value of a declaration is resolved in the schema, not where the element is.
941    fn constraint_problem(
942        &self,
943        offset: usize,
944        type_id: TypeId,
945        value: &str,
946    ) -> Result<Option<String>, DocumentError> {
947        let TypeDef::Simple(simple) = &self.schema.types[type_id] else {
948            return Ok(Some(format!(
949                "{} is not a simple type",
950                self.type_name(type_id)
951            )));
952        };
953        if simple.builtin.needs_context() {
954            return Err(self.unsupported(
955                offset,
956                format!(
957                    "the value constraint of the declaration taken as a value of {}, whose values are valid only in a context",
958                    self.type_name(type_id)
959                ),
960            ));
961        }
962        if !simple.builtin.is_valid_raw(value) {
963            return Ok(Some(format!(
964                "not a valid value of {}",
965                self.type_name(type_id)
966            )));
967        }
968        let processed = datatypes::normalize(value, simple.builtin.white_space());
969        Ok(facet_problem(&self.schema.types, type_id, &processed)
970            .map(|problem| problem.describe(&self.type_name(type_id))))
971    }
972
973    fn attributes(
974        &mut self,
975        element: &impl Start<'d>,
976        type_id: TypeId,
977    ) -> Result<(), DocumentError> {
978        let schema = self.schema;
979        let offset = element.offset();
980        let lookup = |prefix: &str| element.lookup_namespace(Some(prefix)).map(str::to_owned);
981        let (uses, wildcard) = match &schema.types[type_id] {
982            TypeDef::Simple(_) => (&[][..], None),
983            TypeDef::Complex(complex) => {
984                (&complex.attributes[..], complex.attribute_wildcard.as_ref())
985            }
986        };
987        for attribute in element.attributes() {
988            let namespace = namespace_name(attribute.namespace);
989            let local = attribute.local;
990            if namespace == Some(XSI)
991                && matches!(
992                    local,
993                    "type" | "nil" | "schemaLocation" | "noNamespaceSchemaLocation"
994                )
995            {
996                continue;
997            }
998            // Spelt out only for an error.
999            let name = || Some(clark(namespace, local));
1000            if let Some(attribute_use) = uses.iter().find(|u| u.name.matches(namespace, local)) {
1001                self.attribute_value(
1002                    element,
1003                    attribute_use,
1004                    (namespace, local),
1005                    attribute.value,
1006                    &lookup,
1007                )?;
1008                continue;
1009            }
1010            match wildcard {
1011                Some(w) if w.allows(namespace) => {
1012                    // No global attribute declarations exist in the supported
1013                    // subset: lax and skip accept, strict cannot be satisfied.
1014                    if w.process == ProcessContents::Strict {
1015                        self.report_attribute(
1016                            offset,
1017                            element_name(element),
1018                            ErrorKind::UndeclaredAttribute,
1019                            name(),
1020                            "no global attribute declaration, required by a strict wildcard"
1021                                .to_owned(),
1022                        );
1023                    }
1024                }
1025                _ => self.report_attribute(
1026                    offset,
1027                    element_name(element),
1028                    ErrorKind::AttributeNotAllowed,
1029                    name(),
1030                    "the attribute is not allowed".to_owned(),
1031                ),
1032            }
1033        }
1034        for attribute_use in uses.iter().filter(|u| u.required) {
1035            let present = element.attributes().any(|a| {
1036                attribute_use
1037                    .name
1038                    .matches(namespace_name(a.namespace), a.local)
1039            });
1040            if !present {
1041                let name = attribute_use.name.to_string();
1042                self.report_attribute(
1043                    offset,
1044                    element_name(element),
1045                    ErrorKind::MissingAttribute,
1046                    Some(name),
1047                    "the required attribute is missing".to_owned(),
1048                );
1049            }
1050        }
1051        Ok(())
1052    }
1053
1054    /// Checks the value of an attribute the type declares (`attribute_use`); `lookup`
1055    /// gives the namespace bound to a prefix in the scope of the element.
1056    fn attribute_value(
1057        &mut self,
1058        element: &impl Start<'d>,
1059        attribute_use: &AttributeUse,
1060        (namespace, local): (Option<&str>, &str),
1061        value: Value<'_, 'd>,
1062        lookup: &dyn Fn(&str) -> Option<String>,
1063    ) -> Result<(), DocumentError> {
1064        let schema = self.schema;
1065        let offset = element.offset();
1066        // Spelt out only for an error.
1067        let name = || Some(clark(namespace, local));
1068        match self.check_value(attribute_use.type_id, value, lookup) {
1069            Ok(idrefs) => {
1070                for value in idrefs {
1071                    self.idrefs.push(IdRef {
1072                        offset,
1073                        element: element_name(element),
1074                        attribute: name(),
1075                        value,
1076                    });
1077                }
1078                let value = value.as_str();
1079                if let Some(fixed) = attribute_use.fixed.map(|f| schema.fixed_value(f))
1080                    && !self.same_value(attribute_use.type_id, value, fixed)
1081                {
1082                    self.report_attribute(
1083                        offset,
1084                        element_name(element),
1085                        ErrorKind::InvalidAttributeValue,
1086                        name(),
1087                        format!(
1088                            "{} is not the fixed value {} of the attribute",
1089                            quote(value),
1090                            quote(fixed)
1091                        ),
1092                    );
1093                }
1094            }
1095            Err(ValueProblem::Invalid(problem)) => {
1096                self.report_attribute(
1097                    offset,
1098                    element_name(element),
1099                    ErrorKind::InvalidAttributeValue,
1100                    name(),
1101                    problem,
1102                );
1103            }
1104            Err(ValueProblem::DuplicateId(problem)) => {
1105                self.report_attribute(
1106                    offset,
1107                    element_name(element),
1108                    ErrorKind::DuplicateId,
1109                    name(),
1110                    problem,
1111                );
1112            }
1113            Err(ValueProblem::Unsupported(problem)) => {
1114                return Err(self.unsupported(offset, problem));
1115            }
1116        }
1117        Ok(())
1118    }
1119
1120    /// A text node of the element of `frame`.
1121    fn text(&mut self, frame: &mut Frame<'s, 'd>, text: Cow<'d, str>) {
1122        let (offset, namespace, local) = (frame.offset, frame.namespace, frame.local);
1123        match &mut frame.content {
1124            FrameContent::Empty { stopped: false } => {
1125                let element = self.frame_name(namespace, local);
1126                self.report(
1127                    offset,
1128                    element,
1129                    ErrorKind::ContentNotEmpty,
1130                    format!("text {} in empty content", quote(&text)),
1131                );
1132            }
1133            FrameContent::Simple {
1134                text: value,
1135                stopped: false,
1136                ..
1137            } => {
1138                if value.is_empty() {
1139                    *value = text;
1140                } else {
1141                    value.to_mut().push_str(&text);
1142                }
1143            }
1144            FrameContent::Children {
1145                mixed: false,
1146                stopped: false,
1147                ..
1148            } if !text.chars().all(datatypes::is_xml_space) => {
1149                let element = self.frame_name(namespace, local);
1150                self.report(
1151                    offset,
1152                    element,
1153                    ErrorKind::TextNotAllowed,
1154                    format!("text {} in element-only content", quote(text.trim())),
1155                );
1156            }
1157            _ => {}
1158        }
1159    }
1160
1161    /// Matches a child element against its parent's content; `None` when the child
1162    /// is not to be validated (error reported, or skipped by a wildcard).
1163    fn child(&mut self, frame: &mut Frame<'s, 'd>, child: &impl Start<'d>) -> Option<Assignment> {
1164        let schema = self.schema;
1165        let (offset, namespace, local) = (frame.offset, frame.namespace, frame.local);
1166        match &mut frame.content {
1167            FrameContent::Empty { stopped } => {
1168                if !*stopped {
1169                    *stopped = true;
1170                    let parent = self.frame_name(namespace, local);
1171                    self.report(
1172                        offset,
1173                        parent,
1174                        ErrorKind::ContentNotEmpty,
1175                        format!("child element {} in empty content", element_name(child)),
1176                    );
1177                }
1178                None
1179            }
1180            FrameContent::Simple { stopped, .. } => {
1181                if !*stopped {
1182                    *stopped = true;
1183                    let parent = self.frame_name(namespace, local);
1184                    self.report(
1185                        offset,
1186                        parent,
1187                        ErrorKind::ElementInSimpleContent,
1188                        format!("child element {} in simple content", element_name(child)),
1189                    );
1190                }
1191                None
1192            }
1193            FrameContent::Children {
1194                automaton,
1195                state,
1196                stopped,
1197                ..
1198            } => {
1199                if *stopped {
1200                    return None;
1201                }
1202                let (namespace, local) = (namespace_name(child.namespace()), child.local());
1203                let Some((position, term)) =
1204                    automaton.step(*state, namespace, local, &schema.elements)
1205                else {
1206                    *stopped = true;
1207                    let expected = automaton.expected(*state, &schema.elements);
1208                    let message = if expected.is_empty() {
1209                        "not expected: no more child elements are allowed".to_owned()
1210                    } else {
1211                        format!("not expected; expected: {}", expected.join(", "))
1212                    };
1213                    self.report(
1214                        child.offset(),
1215                        element_name(child),
1216                        ErrorKind::UnexpectedElement,
1217                        message,
1218                    );
1219                    return None;
1220                };
1221                *state = Some(position);
1222                match term {
1223                    Term::Element(id) => Some(Assignment::Declared(*id)),
1224                    Term::Wildcard(wildcard) => {
1225                        match (wildcard.process, schema.global_element(namespace, local)) {
1226                            (ProcessContents::Skip, _) => None,
1227                            (_, Some(id)) => Some(Assignment::Declared(id)),
1228                            (ProcessContents::Lax, None) => Some(Assignment::Lax),
1229                            (ProcessContents::Strict, None) => {
1230                                self.report(
1231                                    child.offset(),
1232                                    element_name(child),
1233                                    ErrorKind::UndeclaredElement,
1234                                    "no global element declaration, required by a strict wildcard"
1235                                        .to_owned(),
1236                                );
1237                                None
1238                            }
1239                        }
1240                    }
1241                }
1242            }
1243        }
1244    }
1245
1246    /// The end of the element of `frame`; `lookup` gives the namespace bound to a
1247    /// prefix in its scope.
1248    fn end(
1249        &mut self,
1250        frame: &Frame<'s, 'd>,
1251        lookup: &dyn Fn(&str) -> Option<String>,
1252    ) -> Result<(), DocumentError> {
1253        let element = |v: &Self| v.frame_name(frame.namespace, frame.local);
1254        match &frame.content {
1255            FrameContent::Simple {
1256                type_id,
1257                text,
1258                constraint,
1259                stopped: false,
1260            } => {
1261                let type_id = *type_id;
1262                if let Some(constraint) = constraint
1263                    && text.is_empty()
1264                {
1265                    // cvc-elt.5.1: an element without any character or element
1266                    // children takes the default or fixed value, which must be
1267                    // valid for the actual type (an xsi:type may change it).
1268                    if let Some(problem) =
1269                        self.constraint_problem(frame.offset, type_id, &constraint.value)?
1270                    {
1271                        let element = element(self);
1272                        self.report(
1273                            frame.offset,
1274                            element,
1275                            ErrorKind::InvalidValue,
1276                            format!(
1277                                "the {} value {} of the declaration is {problem}",
1278                                constraint.kind.as_str(),
1279                                quote(&constraint.value)
1280                            ),
1281                        );
1282                    }
1283                    return Ok(());
1284                }
1285                let value = match text {
1286                    Cow::Borrowed(text) => Value::Document(text),
1287                    Cow::Owned(text) => Value::Other(text.as_str()),
1288                };
1289                match self.check_value(type_id, value, lookup) {
1290                    Ok(idrefs) => {
1291                        for value in idrefs {
1292                            let element = element(self);
1293                            self.idrefs.push(IdRef {
1294                                offset: frame.offset,
1295                                element,
1296                                attribute: None,
1297                                value,
1298                            });
1299                        }
1300                        // cvc-elt.5.2.2.2.2: a fixed value is compared in the value
1301                        // space.
1302                        if let Some(constraint) = constraint
1303                            && constraint.kind == ConstraintKind::Fixed
1304                            && !self.same_value(type_id, text, &constraint.value)
1305                        {
1306                            let element = element(self);
1307                            self.report(
1308                                frame.offset,
1309                                element,
1310                                ErrorKind::InvalidValue,
1311                                format!(
1312                                    "{} is not the fixed value {} of the declaration",
1313                                    quote(text),
1314                                    quote(&constraint.value)
1315                                ),
1316                            );
1317                        }
1318                    }
1319                    Err(ValueProblem::Invalid(problem)) => {
1320                        let element = element(self);
1321                        self.report(frame.offset, element, ErrorKind::InvalidValue, problem);
1322                    }
1323                    Err(ValueProblem::DuplicateId(problem)) => {
1324                        let element = element(self);
1325                        self.report(frame.offset, element, ErrorKind::DuplicateId, problem);
1326                    }
1327                    Err(ValueProblem::Unsupported(problem)) => {
1328                        return Err(self.unsupported(frame.offset, problem));
1329                    }
1330                }
1331            }
1332            FrameContent::Children {
1333                automaton,
1334                state,
1335                stopped: false,
1336                ..
1337            } if !automaton.accepts(*state) => {
1338                let expected = automaton.expected(*state, &self.schema.elements);
1339                let element = element(self);
1340                self.report(
1341                    frame.offset,
1342                    element,
1343                    ErrorKind::MissingElement,
1344                    format!("content incomplete; expected: {}", expected.join(", ")),
1345                );
1346            }
1347            _ => {}
1348        }
1349        Ok(())
1350    }
1351}
1352
1353#[cfg(test)]
1354mod tests {
1355    use super::*;
1356
1357    /// Line and column as a table of line starts gives them: the line is the number
1358    /// of line starts at or before the offset, the column one more than the number
1359    /// of characters between the start of that line and the offset.
1360    fn reference_position(text: &str, offset: usize) -> (u32, u32) {
1361        let starts: Vec<usize> = std::iter::once(0)
1362            .chain(text.match_indices('\n').map(|(i, _)| i + 1))
1363            .collect();
1364        let line = starts.partition_point(|&s| s <= offset);
1365        let start = starts[line - 1];
1366        let column = text[start..offset].chars().count() + 1;
1367        (u32::try_from(line).unwrap(), u32::try_from(column).unwrap())
1368    }
1369
1370    proptest::proptest! {
1371        #[test]
1372        fn cursor_positions(
1373            text in "[a\n\ré€😀<]{0,40}",
1374            picks in proptest::collection::vec(proptest::prelude::any::<proptest::sample::Index>(), 0..8),
1375        ) {
1376            let boundaries: Vec<usize> = text
1377                .char_indices()
1378                .map(|(i, _)| i)
1379                .chain(std::iter::once(text.len()))
1380                .collect();
1381            let mut offsets: Vec<usize> = picks.iter().map(|i| boundaries[i.index(boundaries.len())]).collect();
1382            offsets.sort_unstable();
1383            let mut cursor = Cursor::new(&text);
1384            for offset in offsets {
1385                proptest::prop_assert_eq!(cursor.advance(offset), reference_position(&text, offset));
1386            }
1387        }
1388    }
1389}