use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use einvoice_xml::{Event, StartElement};
use crate::automaton::{Automaton, State, Term};
use crate::datatypes::{self, Builtin, WhiteSpace};
use crate::error::{DocumentError, ErrorKind, Report, ValidationError};
use crate::model::{
ANY_TYPE, AttributeUse, ComplexType, ConstraintKind, Content, ElementId, ProcessContents,
Schema, TypeDef, TypeId, ValueConstraint, XSI, clark, facet_problem, namespace_name, quote,
};
#[derive(Clone, Copy)]
enum Assignment {
Root,
Declared(ElementId),
Lax,
}
#[derive(Clone, Copy)]
enum Value<'v, 'd> {
Document(&'d str),
Other(&'v str),
}
impl Value<'_, '_> {
#[expect(
clippy::match_same_arms,
reason = "the two slices have different lifetimes: one pattern cannot bind both"
)]
fn as_str(&self) -> &str {
match *self {
Self::Document(s) => s,
Self::Other(s) => s,
}
}
}
struct Attribute<'v, 'd> {
namespace: Option<&'v str>,
local: &'v str,
value: Value<'v, 'd>,
}
trait Start<'d> {
fn namespace(&self) -> Option<&str>;
fn local(&self) -> &'d str;
fn offset(&self) -> usize;
fn xsi(&self, local: &str) -> Option<&str>;
fn lookup_namespace(&self, prefix: Option<&str>) -> Option<&str>;
fn attributes(&self) -> impl Iterator<Item = Attribute<'_, 'd>>;
}
impl<'a> Start<'a> for StartElement<'_, 'a> {
fn namespace(&self) -> Option<&str> {
self.name().namespace
}
fn local(&self) -> &'a str {
self.name().local
}
fn offset(&self) -> usize {
self.range().start
}
fn xsi(&self, local: &str) -> Option<&str> {
self.attribute(Some(XSI), local).map(AsRef::as_ref)
}
fn lookup_namespace(&self, prefix: Option<&str>) -> Option<&str> {
match prefix {
Some("xml" | "xmlns") => None,
Some(prefix) => StartElement::lookup_namespace(self, prefix),
None => StartElement::lookup_namespace(self, ""),
}
}
fn attributes(&self) -> impl Iterator<Item = Attribute<'_, 'a>> {
StartElement::attributes(self).map(|attribute| Attribute {
namespace: attribute.name.namespace,
local: attribute.name.local,
value: match attribute.value {
Cow::Borrowed(value) => Value::Document(value),
Cow::Owned(value) => Value::Other(value),
},
})
}
}
impl<'d> Start<'d> for roxmltree::Node<'d, '_> {
fn namespace(&self) -> Option<&str> {
self.tag_name().namespace()
}
fn local(&self) -> &'d str {
self.tag_name().name()
}
fn offset(&self) -> usize {
self.range().start
}
fn xsi(&self, local: &str) -> Option<&str> {
self.attribute((XSI, local))
}
fn lookup_namespace(&self, prefix: Option<&str>) -> Option<&str> {
self.lookup_namespace_uri(prefix)
}
fn attributes(&self) -> impl Iterator<Item = Attribute<'_, 'd>> {
roxmltree::Node::attributes(self).map(|attribute| Attribute {
namespace: attribute.namespace(),
local: attribute.name(),
value: Value::Document(attribute.value()),
})
}
}
enum FrameContent<'s, 'd> {
Empty {
stopped: bool,
},
Simple {
type_id: TypeId,
text: Cow<'d, str>,
constraint: Option<&'s ValueConstraint>,
stopped: bool,
},
Children {
automaton: &'s Automaton,
mixed: bool,
state: State,
stopped: bool,
},
}
struct Frame<'s, 'd> {
offset: usize,
namespace: Option<usize>,
local: &'d str,
content: FrameContent<'s, 'd>,
}
const SCAN_LIMIT: usize = 16;
#[derive(Default)]
struct Namespaces {
names: Vec<Box<str>>,
index: HashMap<Box<str>, usize>,
}
impl Namespaces {
fn id(&mut self, namespace: Option<&str>) -> Option<usize> {
let namespace = namespace?;
let found = if self.names.len() <= SCAN_LIMIT {
self.names.iter().position(|n| **n == *namespace)
} else {
self.index.get(namespace).copied()
};
Some(found.unwrap_or_else(|| {
let id = self.names.len();
self.names.push(namespace.into());
self.index.insert(namespace.into(), id);
id
}))
}
fn name(&self, id: Option<usize>) -> Option<&str> {
id.and_then(|id| self.names.get(id)).map(AsRef::as_ref)
}
}
struct Validator<'s, 'd> {
schema: &'s Schema,
text: &'d str,
errors: Vec<(usize, ValidationError)>,
ids: HashSet<Cow<'d, str>>,
idrefs: Vec<IdRef>,
dtd: bool,
namespaces: Namespaces,
}
struct IdRef {
offset: usize,
element: String,
attribute: Option<String>,
value: String,
}
struct Cursor<'t> {
text: &'t [u8],
offset: usize,
line: usize,
column: usize,
}
impl<'t> Cursor<'t> {
fn new(text: &'t str) -> Self {
Self {
text: text.as_bytes(),
offset: 0,
line: 1,
column: 0,
}
}
fn advance(&mut self, offset: usize) -> (u32, u32) {
let end = offset.min(self.text.len());
for &b in self.text.get(self.offset..end).unwrap_or(&[]) {
if b == b'\n' {
self.line += 1;
self.column = 0;
} else if b & 0xC0 != 0x80 {
self.column += 1;
}
}
self.offset = self.offset.max(end);
(
u32::try_from(self.line).unwrap_or(u32::MAX),
u32::try_from(self.column + 1).unwrap_or(u32::MAX),
)
}
}
fn positions(text: &str, mut errors: Vec<(usize, ValidationError)>) -> Vec<ValidationError> {
errors.sort_by_key(|(offset, _)| *offset);
let mut cursor = Cursor::new(text);
errors
.into_iter()
.map(|(offset, mut error)| {
(error.line, error.column) = cursor.advance(offset);
error
})
.collect()
}
enum ValueProblem {
Invalid(String),
DuplicateId(String),
Unsupported(String),
}
fn declared_prefix(prefix: &str, lookup: impl Fn(&str) -> Option<String>) -> bool {
match prefix {
"xml" => true,
"xmlns" => false,
_ => lookup(prefix).is_some_and(|ns| !ns.is_empty()),
}
}
fn element_name<'d>(element: &impl Start<'d>) -> String {
clark(namespace_name(element.namespace()), element.local())
}
fn malformed(e: &einvoice_xml::Error) -> DocumentError {
DocumentError::Malformed {
line: e.pos().row,
column: e.pos().col,
message: e.to_string(),
}
}
pub(crate) fn validate(schema: &Schema, xml: &str) -> Result<Report, DocumentError> {
let mut reader = einvoice_xml::Reader::new(xml);
let mut validation = Validation::new(schema, xml);
loop {
match reader.next_event() {
Ok(Some(event)) => validation.event(event),
Ok(None) => return validation.finish(),
Err(einvoice_xml::Error::DtdDetected) => return validate_tree(schema, xml),
Err(e) => return Err(malformed(&e)),
}
}
}
fn validate_tree(schema: &Schema, xml: &str) -> Result<Report, DocumentError> {
let options = roxmltree::ParsingOptions {
allow_dtd: true,
..roxmltree::ParsingOptions::default()
};
let doc = roxmltree::Document::parse_with_options(xml, options).map_err(|e| {
DocumentError::Malformed {
line: e.pos().row,
column: e.pos().col,
message: e.to_string(),
}
})?;
let mut walk = Walk::new(schema, xml);
walk.validator.dtd = true;
let tree = &doc;
let lookup = |id: roxmltree::NodeId| {
move |prefix: &str| {
tree.get_node(id)
.and_then(|node| node.lookup_namespace_uri(Some(prefix)))
.map(str::to_owned)
}
};
let mut open: Vec<roxmltree::NodeId> = Vec::new();
for node in doc.root().descendants().skip(1) {
let parent = node.parent().map(|p| p.id());
while let Some(&id) = open.last()
&& Some(id) != parent
{
open.pop();
walk.end(&lookup(id));
}
match node.node_type() {
roxmltree::NodeType::Element => {
walk.start(&node);
open.push(node.id());
}
roxmltree::NodeType::Text => walk.text(Cow::Borrowed(node.text().unwrap_or(""))),
roxmltree::NodeType::Comment | roxmltree::NodeType::PI => walk.split_text(),
roxmltree::NodeType::Root => {}
}
}
while let Some(id) = open.pop() {
walk.end(&lookup(id));
}
walk.finish()
}
pub struct Validation<'s, 'a> {
walk: Walk<'s, 'a>,
}
impl std::fmt::Debug for Validation<'_, '_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Validation")
.field("errors", &self.walk.validator.errors.len())
.field("open", &self.walk.frames.len())
.finish_non_exhaustive()
}
}
impl<'s, 'a> Validation<'s, 'a> {
pub(crate) fn new(schema: &'s Schema, text: &'a str) -> Self {
Self {
walk: Walk::new(schema, text),
}
}
pub fn event(&mut self, event: Event<'_, 'a>) {
match event {
Event::Start(start) => self.walk.start(&start),
Event::End(end) => self
.walk
.end(&|prefix: &str| end.lookup_namespace(prefix).map(str::to_owned)),
Event::Text(text) => self.walk.text(text.value),
Event::Comment(_) | Event::ProcessingInstruction(_) => self.walk.split_text(),
}
}
pub fn finish(self) -> Result<Report, DocumentError> {
self.walk.finish()
}
}
struct Walk<'s, 'd> {
validator: Validator<'s, 'd>,
frames: Vec<Frame<'s, 'd>>,
skipped: usize,
text: Option<Cow<'d, str>>,
unsupported: Option<DocumentError>,
}
impl<'s, 'd> Walk<'s, 'd> {
fn new(schema: &'s Schema, text: &'d str) -> Self {
Self {
validator: Validator {
schema,
text,
errors: Vec::new(),
ids: HashSet::new(),
idrefs: Vec::new(),
dtd: false,
namespaces: Namespaces::default(),
},
frames: Vec::new(),
skipped: 0,
text: None,
unsupported: None,
}
}
fn start(&mut self, element: &impl Start<'d>) {
self.split_text();
if self.unsupported.is_some() {
return;
}
if self.skipped > 0 {
self.skipped += 1;
return;
}
let assignment = match self.frames.last_mut() {
None => Assignment::Root,
Some(top) => {
let Some(assignment) = self.validator.child(top, element) else {
self.skipped = 1;
return;
};
assignment
}
};
match self.validator.start(element, assignment) {
Ok(Some(frame)) => self.frames.push(frame),
Ok(None) => self.skipped = 1,
Err(e) => self.unsupported = Some(e),
}
}
fn end(&mut self, lookup: &dyn Fn(&str) -> Option<String>) {
self.split_text();
if self.unsupported.is_some() {
return;
}
if self.skipped > 0 {
self.skipped -= 1;
} else if let Some(frame) = self.frames.pop()
&& let Err(e) = self.validator.end(&frame, lookup)
{
self.unsupported = Some(e);
}
}
fn text(&mut self, value: Cow<'d, str>) {
if self.unsupported.is_some() || self.skipped > 0 || self.frames.is_empty() {
return;
}
match &mut self.text {
None => self.text = Some(value),
Some(text) => text.to_mut().push_str(&value),
}
}
fn split_text(&mut self) {
if let Some(text) = self.text.take()
&& let Some(top) = self.frames.last_mut()
{
self.validator.text(top, text);
}
}
fn finish(mut self) -> Result<Report, DocumentError> {
self.split_text();
if let Some(e) = self.unsupported {
return Err(e);
}
self.validator.resolve_idrefs();
Ok(Report {
errors: positions(self.validator.text, self.validator.errors),
})
}
}
impl<'s, 'd> Validator<'s, 'd> {
fn report(&mut self, offset: usize, element: String, kind: ErrorKind, message: String) {
self.report_attribute(offset, element, kind, None, message);
}
fn resolve_idrefs(&mut self) {
for idref in std::mem::take(&mut self.idrefs) {
if !self.ids.contains(idref.value.as_str()) {
self.report_attribute(
idref.offset,
idref.element,
ErrorKind::UnresolvedIdref,
idref.attribute,
format!(
"the IDREF {} is not the value of an ID of the document",
quote(&idref.value)
),
);
}
}
}
fn report_attribute(
&mut self,
offset: usize,
element: String,
kind: ErrorKind,
attribute: Option<String>,
message: String,
) {
self.errors.push((
offset,
ValidationError {
kind,
line: 0,
column: 0,
element,
attribute,
message,
},
));
}
fn frame_name(&self, namespace: Option<usize>, local: &str) -> String {
clark(self.namespaces.name(namespace), local)
}
fn unsupported(&self, offset: usize, message: String) -> DocumentError {
let (line, column) = Cursor::new(self.text).advance(offset);
DocumentError::Unsupported {
line,
column,
message,
}
}
fn type_name(&self, type_id: TypeId) -> String {
self.schema.types[type_id]
.name()
.map_or_else(|| "an anonymous type".to_owned(), ToString::to_string)
}
fn start(
&mut self,
element: &impl Start<'d>,
assignment: Assignment,
) -> Result<Option<Frame<'s, 'd>>, DocumentError> {
let schema = self.schema;
let namespace = namespace_name(element.namespace());
let local = element.local();
let offset = element.offset();
let declaration = match assignment {
Assignment::Root => {
let Some(id) = schema.global_element(namespace, local) else {
self.report(
offset,
element_name(element),
ErrorKind::UnknownRoot,
"no global element declaration for the document element".to_owned(),
);
return Ok(None);
};
Some(id)
}
Assignment::Declared(id) => Some(id),
Assignment::Lax => None,
};
let declared_type = declaration.map_or(ANY_TYPE, |id| schema.elements[id].type_id);
if declaration.is_some()
&& let Some(nil) = element.xsi("nil")
{
let value = datatypes::normalize(nil, WhiteSpace::Collapse);
let attribute = Some(clark(Some(XSI), "nil"));
if Builtin::Boolean.is_valid(&value) {
self.report_attribute(
offset,
element_name(element),
ErrorKind::NotNillable,
attribute,
"xsi:nil on an element whose declaration is not nillable".to_owned(),
);
} else {
self.report_attribute(
offset,
element_name(element),
ErrorKind::InvalidXsiNil,
attribute,
format!("xsi:nil {} is not a boolean", quote(nil)),
);
}
}
let mut type_id = declared_type;
if let Some(xsi_type) = element.xsi("type")
&& let Some(local_type) = self.xsi_type(element, xsi_type, declared_type)
{
type_id = local_type;
}
if let TypeDef::Complex(ComplexType {
is_abstract: true, ..
}) = &schema.types[type_id]
{
let name = self.type_name(type_id);
self.report(
offset,
element_name(element),
ErrorKind::AbstractType,
format!("the type {name} is abstract"),
);
return Ok(None);
}
self.attributes(element, type_id)?;
let constraint = declaration.and_then(|id| schema.element_constraint(id));
let content = match &schema.types[type_id] {
TypeDef::Simple(_) => FrameContent::Simple {
type_id,
text: Cow::Borrowed(""),
constraint,
stopped: false,
},
TypeDef::Complex(complex) => match &complex.content {
Content::Empty => FrameContent::Empty { stopped: false },
Content::Simple(simple) => FrameContent::Simple {
type_id: *simple,
text: Cow::Borrowed(""),
constraint,
stopped: false,
},
Content::ElementOnly(automaton) => FrameContent::Children {
automaton,
mixed: false,
state: None,
stopped: false,
},
Content::Mixed(automaton) => FrameContent::Children {
automaton,
mixed: true,
state: None,
stopped: false,
},
},
};
Ok(Some(Frame {
offset,
namespace: self.namespaces.id(namespace),
local,
content,
}))
}
fn xsi_type(
&mut self,
element: &impl Start<'d>,
value: &str,
declared: TypeId,
) -> Option<TypeId> {
let schema = self.schema;
let offset = element.offset();
let collapsed = datatypes::normalize(value, WhiteSpace::Collapse);
let Some((prefix, local)) = datatypes::split_qname(&collapsed) else {
self.report_attribute(
offset,
element_name(element),
ErrorKind::InvalidXsiType,
Some(clark(Some(XSI), "type")),
format!("xsi:type {} is not a QName", quote(value)),
);
return None;
};
let namespace = if let Some(p) = prefix {
let Some(ns) = element.lookup_namespace(Some(p)) else {
self.report_attribute(
offset,
element_name(element),
ErrorKind::InvalidXsiType,
Some(clark(Some(XSI), "type")),
format!("xsi:type {}: prefix {p:?} is not declared", quote(value)),
);
return None;
};
Some(ns)
} else {
namespace_name(element.lookup_namespace(None))
};
let Some(type_id) = schema.global_type(namespace, local) else {
self.report_attribute(
offset,
element_name(element),
ErrorKind::InvalidXsiType,
Some(clark(Some(XSI), "type")),
format!(
"xsi:type {} does not resolve to a type definition",
quote(value)
),
);
return None;
};
if !schema.is_derived_from(type_id, declared) {
let (name, declared_name) = (self.type_name(type_id), self.type_name(declared));
self.report_attribute(
offset,
element_name(element),
ErrorKind::InvalidXsiType,
Some(clark(Some(XSI), "type")),
format!("xsi:type {name} is not derived from the declared type {declared_name}"),
);
return None;
}
Some(type_id)
}
fn check_value(
&mut self,
type_id: TypeId,
raw: Value<'_, 'd>,
lookup: &dyn Fn(&str) -> Option<String>,
) -> Result<Vec<String>, ValueProblem> {
let schema = self.schema;
let TypeDef::Simple(simple) = &schema.types[type_id] else {
return Err(ValueProblem::Invalid(format!(
"{} is not a simple type",
self.type_name(type_id)
)));
};
let builtin = simple.builtin;
if !builtin.is_valid_raw(raw.as_str()) {
return Err(ValueProblem::Invalid(format!(
"{} is not a valid value of {}",
quote(raw.as_str()),
self.type_name(type_id)
)));
}
let is_id = builtin == Builtin::Id;
if !is_id && !builtin.needs_context() && !schema.has_facets(type_id) {
return Ok(Vec::new());
}
let white_space = simple.builtin.white_space();
let value: Cow<'d, str> = match raw {
Value::Document(raw) => datatypes::normalize(raw, white_space),
Value::Other(raw) => Cow::Owned(datatypes::normalize(raw, white_space).into_owned()),
};
if let Some(problem) = facet_problem(&schema.types, type_id, &value) {
return Err(ValueProblem::Invalid(format!(
"{} is {}",
quote(raw.as_str()),
problem.describe(&self.type_name(type_id))
)));
}
let invalid = |why: &str| {
Err(ValueProblem::Invalid(format!(
"{} is not a valid value of {}: {why}",
quote(raw.as_str()),
self.type_name(type_id)
)))
};
match builtin {
Builtin::Id => {
if !self.ids.insert(value) {
return Err(ValueProblem::DuplicateId(format!(
"the ID {} is already used in the document",
quote(raw.as_str())
)));
}
}
Builtin::QName => {
if let Some((Some(prefix), _)) = datatypes::split_qname(&value)
&& !declared_prefix(prefix, lookup)
{
return invalid(&format!("the prefix {prefix:?} is not declared"));
}
}
Builtin::Notation => return invalid("the schema declares no notation"),
Builtin::Entity | Builtin::Entities if self.dtd => {
return Err(ValueProblem::Unsupported(format!(
"{} names an unparsed entity of the document type declaration: not implemented",
quote(raw.as_str())
)));
}
Builtin::Entity | Builtin::Entities => {
return invalid(
"the document has no document type declaration, so no unparsed entity",
);
}
Builtin::IdRef | Builtin::IdRefs => {
return Ok(value.split(' ').map(str::to_owned).collect());
}
_ => {}
}
Ok(Vec::new())
}
fn same_value(&self, type_id: TypeId, a: &str, b: &str) -> bool {
let TypeDef::Simple(simple) = &self.schema.types[type_id] else {
return false;
};
let builtin = simple.builtin;
let white_space = builtin.white_space();
let a = datatypes::normalize(a, white_space);
let b = datatypes::normalize(b, white_space);
match (builtin.value_key(&a), builtin.value_key(&b)) {
(Some(a), Some(b)) => a == b,
_ => false,
}
}
fn constraint_problem(
&self,
offset: usize,
type_id: TypeId,
value: &str,
) -> Result<Option<String>, DocumentError> {
let TypeDef::Simple(simple) = &self.schema.types[type_id] else {
return Ok(Some(format!(
"{} is not a simple type",
self.type_name(type_id)
)));
};
if simple.builtin.needs_context() {
return Err(self.unsupported(
offset,
format!(
"the value constraint of the declaration taken as a value of {}, whose values are valid only in a context",
self.type_name(type_id)
),
));
}
if !simple.builtin.is_valid_raw(value) {
return Ok(Some(format!(
"not a valid value of {}",
self.type_name(type_id)
)));
}
let processed = datatypes::normalize(value, simple.builtin.white_space());
Ok(facet_problem(&self.schema.types, type_id, &processed)
.map(|problem| problem.describe(&self.type_name(type_id))))
}
fn attributes(
&mut self,
element: &impl Start<'d>,
type_id: TypeId,
) -> Result<(), DocumentError> {
let schema = self.schema;
let offset = element.offset();
let lookup = |prefix: &str| element.lookup_namespace(Some(prefix)).map(str::to_owned);
let (uses, wildcard) = match &schema.types[type_id] {
TypeDef::Simple(_) => (&[][..], None),
TypeDef::Complex(complex) => {
(&complex.attributes[..], complex.attribute_wildcard.as_ref())
}
};
for attribute in element.attributes() {
let namespace = namespace_name(attribute.namespace);
let local = attribute.local;
if namespace == Some(XSI)
&& matches!(
local,
"type" | "nil" | "schemaLocation" | "noNamespaceSchemaLocation"
)
{
continue;
}
let name = || Some(clark(namespace, local));
if let Some(attribute_use) = uses.iter().find(|u| u.name.matches(namespace, local)) {
self.attribute_value(
element,
attribute_use,
(namespace, local),
attribute.value,
&lookup,
)?;
continue;
}
match wildcard {
Some(w) if w.allows(namespace) => {
if w.process == ProcessContents::Strict {
self.report_attribute(
offset,
element_name(element),
ErrorKind::UndeclaredAttribute,
name(),
"no global attribute declaration, required by a strict wildcard"
.to_owned(),
);
}
}
_ => self.report_attribute(
offset,
element_name(element),
ErrorKind::AttributeNotAllowed,
name(),
"the attribute is not allowed".to_owned(),
),
}
}
for attribute_use in uses.iter().filter(|u| u.required) {
let present = element.attributes().any(|a| {
attribute_use
.name
.matches(namespace_name(a.namespace), a.local)
});
if !present {
let name = attribute_use.name.to_string();
self.report_attribute(
offset,
element_name(element),
ErrorKind::MissingAttribute,
Some(name),
"the required attribute is missing".to_owned(),
);
}
}
Ok(())
}
fn attribute_value(
&mut self,
element: &impl Start<'d>,
attribute_use: &AttributeUse,
(namespace, local): (Option<&str>, &str),
value: Value<'_, 'd>,
lookup: &dyn Fn(&str) -> Option<String>,
) -> Result<(), DocumentError> {
let schema = self.schema;
let offset = element.offset();
let name = || Some(clark(namespace, local));
match self.check_value(attribute_use.type_id, value, lookup) {
Ok(idrefs) => {
for value in idrefs {
self.idrefs.push(IdRef {
offset,
element: element_name(element),
attribute: name(),
value,
});
}
let value = value.as_str();
if let Some(fixed) = attribute_use.fixed.map(|f| schema.fixed_value(f))
&& !self.same_value(attribute_use.type_id, value, fixed)
{
self.report_attribute(
offset,
element_name(element),
ErrorKind::InvalidAttributeValue,
name(),
format!(
"{} is not the fixed value {} of the attribute",
quote(value),
quote(fixed)
),
);
}
}
Err(ValueProblem::Invalid(problem)) => {
self.report_attribute(
offset,
element_name(element),
ErrorKind::InvalidAttributeValue,
name(),
problem,
);
}
Err(ValueProblem::DuplicateId(problem)) => {
self.report_attribute(
offset,
element_name(element),
ErrorKind::DuplicateId,
name(),
problem,
);
}
Err(ValueProblem::Unsupported(problem)) => {
return Err(self.unsupported(offset, problem));
}
}
Ok(())
}
fn text(&mut self, frame: &mut Frame<'s, 'd>, text: Cow<'d, str>) {
let (offset, namespace, local) = (frame.offset, frame.namespace, frame.local);
match &mut frame.content {
FrameContent::Empty { stopped: false } => {
let element = self.frame_name(namespace, local);
self.report(
offset,
element,
ErrorKind::ContentNotEmpty,
format!("text {} in empty content", quote(&text)),
);
}
FrameContent::Simple {
text: value,
stopped: false,
..
} => {
if value.is_empty() {
*value = text;
} else {
value.to_mut().push_str(&text);
}
}
FrameContent::Children {
mixed: false,
stopped: false,
..
} if !text.chars().all(datatypes::is_xml_space) => {
let element = self.frame_name(namespace, local);
self.report(
offset,
element,
ErrorKind::TextNotAllowed,
format!("text {} in element-only content", quote(text.trim())),
);
}
_ => {}
}
}
fn child(&mut self, frame: &mut Frame<'s, 'd>, child: &impl Start<'d>) -> Option<Assignment> {
let schema = self.schema;
let (offset, namespace, local) = (frame.offset, frame.namespace, frame.local);
match &mut frame.content {
FrameContent::Empty { stopped } => {
if !*stopped {
*stopped = true;
let parent = self.frame_name(namespace, local);
self.report(
offset,
parent,
ErrorKind::ContentNotEmpty,
format!("child element {} in empty content", element_name(child)),
);
}
None
}
FrameContent::Simple { stopped, .. } => {
if !*stopped {
*stopped = true;
let parent = self.frame_name(namespace, local);
self.report(
offset,
parent,
ErrorKind::ElementInSimpleContent,
format!("child element {} in simple content", element_name(child)),
);
}
None
}
FrameContent::Children {
automaton,
state,
stopped,
..
} => {
if *stopped {
return None;
}
let (namespace, local) = (namespace_name(child.namespace()), child.local());
let Some((position, term)) =
automaton.step(*state, namespace, local, &schema.elements)
else {
*stopped = true;
let expected = automaton.expected(*state, &schema.elements);
let message = if expected.is_empty() {
"not expected: no more child elements are allowed".to_owned()
} else {
format!("not expected; expected: {}", expected.join(", "))
};
self.report(
child.offset(),
element_name(child),
ErrorKind::UnexpectedElement,
message,
);
return None;
};
*state = Some(position);
match term {
Term::Element(id) => Some(Assignment::Declared(*id)),
Term::Wildcard(wildcard) => {
match (wildcard.process, schema.global_element(namespace, local)) {
(ProcessContents::Skip, _) => None,
(_, Some(id)) => Some(Assignment::Declared(id)),
(ProcessContents::Lax, None) => Some(Assignment::Lax),
(ProcessContents::Strict, None) => {
self.report(
child.offset(),
element_name(child),
ErrorKind::UndeclaredElement,
"no global element declaration, required by a strict wildcard"
.to_owned(),
);
None
}
}
}
}
}
}
}
fn end(
&mut self,
frame: &Frame<'s, 'd>,
lookup: &dyn Fn(&str) -> Option<String>,
) -> Result<(), DocumentError> {
let element = |v: &Self| v.frame_name(frame.namespace, frame.local);
match &frame.content {
FrameContent::Simple {
type_id,
text,
constraint,
stopped: false,
} => {
let type_id = *type_id;
if let Some(constraint) = constraint
&& text.is_empty()
{
if let Some(problem) =
self.constraint_problem(frame.offset, type_id, &constraint.value)?
{
let element = element(self);
self.report(
frame.offset,
element,
ErrorKind::InvalidValue,
format!(
"the {} value {} of the declaration is {problem}",
constraint.kind.as_str(),
quote(&constraint.value)
),
);
}
return Ok(());
}
let value = match text {
Cow::Borrowed(text) => Value::Document(text),
Cow::Owned(text) => Value::Other(text.as_str()),
};
match self.check_value(type_id, value, lookup) {
Ok(idrefs) => {
for value in idrefs {
let element = element(self);
self.idrefs.push(IdRef {
offset: frame.offset,
element,
attribute: None,
value,
});
}
if let Some(constraint) = constraint
&& constraint.kind == ConstraintKind::Fixed
&& !self.same_value(type_id, text, &constraint.value)
{
let element = element(self);
self.report(
frame.offset,
element,
ErrorKind::InvalidValue,
format!(
"{} is not the fixed value {} of the declaration",
quote(text),
quote(&constraint.value)
),
);
}
}
Err(ValueProblem::Invalid(problem)) => {
let element = element(self);
self.report(frame.offset, element, ErrorKind::InvalidValue, problem);
}
Err(ValueProblem::DuplicateId(problem)) => {
let element = element(self);
self.report(frame.offset, element, ErrorKind::DuplicateId, problem);
}
Err(ValueProblem::Unsupported(problem)) => {
return Err(self.unsupported(frame.offset, problem));
}
}
}
FrameContent::Children {
automaton,
state,
stopped: false,
..
} if !automaton.accepts(*state) => {
let expected = automaton.expected(*state, &self.schema.elements);
let element = element(self);
self.report(
frame.offset,
element,
ErrorKind::MissingElement,
format!("content incomplete; expected: {}", expected.join(", ")),
);
}
_ => {}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn reference_position(text: &str, offset: usize) -> (u32, u32) {
let starts: Vec<usize> = std::iter::once(0)
.chain(text.match_indices('\n').map(|(i, _)| i + 1))
.collect();
let line = starts.partition_point(|&s| s <= offset);
let start = starts[line - 1];
let column = text[start..offset].chars().count() + 1;
(u32::try_from(line).unwrap(), u32::try_from(column).unwrap())
}
proptest::proptest! {
#[test]
fn cursor_positions(
text in "[a\n\ré€😀<]{0,40}",
picks in proptest::collection::vec(proptest::prelude::any::<proptest::sample::Index>(), 0..8),
) {
let boundaries: Vec<usize> = text
.char_indices()
.map(|(i, _)| i)
.chain(std::iter::once(text.len()))
.collect();
let mut offsets: Vec<usize> = picks.iter().map(|i| boundaries[i.index(boundaries.len())]).collect();
offsets.sort_unstable();
let mut cursor = Cursor::new(&text);
for offset in offsets {
proptest::prop_assert_eq!(cursor.advance(offset), reference_position(&text, offset));
}
}
}
}