1use std::fmt;
4
5use einvoice_xpath::QName;
6use einvoice_xslt_exec::{CompactOutput, ResultObserver};
7
8pub use einvoice_xsd::{ErrorKind as SchemaErrorKind, ValidationError as SchemaError};
9
10use crate::Error;
11
12const SVRL_NS: &str = "http://purl.oclc.org/dsdl/svrl";
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub enum Verdict {
18 Valid,
21 Invalid,
25}
26
27impl Verdict {
28 #[must_use]
30 pub const fn as_str(self) -> &'static str {
31 match self {
32 Self::Valid => "valid",
33 Self::Invalid => "invalid",
34 }
35 }
36}
37
38impl fmt::Display for Verdict {
39 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40 f.write_str(self.as_str())
41 }
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
51pub enum Severity {
52 Fatal,
55 Warning,
57 Other,
60}
61
62impl Severity {
63 #[must_use]
65 pub fn from_flag(flag: Option<&str>) -> Self {
66 match flag {
67 Some("fatal") => Self::Fatal,
68 Some("warning") => Self::Warning,
69 _ => Self::Other,
70 }
71 }
72
73 #[must_use]
76 pub fn from_flag_fail_closed(flag: Option<&str>) -> Self {
77 match Self::from_flag(flag) {
78 Self::Other => Self::Fatal,
79 severity => severity,
80 }
81 }
82
83 #[must_use]
85 pub const fn as_str(self) -> &'static str {
86 match self {
87 Self::Fatal => "fatal",
88 Self::Warning => "warning",
89 Self::Other => "other",
90 }
91 }
92}
93
94impl fmt::Display for Severity {
95 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96 f.write_str(self.as_str())
97 }
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
102pub enum FindingKind {
103 FailedAssert,
105 SuccessfulReport,
107}
108
109impl FindingKind {
110 #[must_use]
112 pub const fn as_str(self) -> &'static str {
113 match self {
114 Self::FailedAssert => "failed-assert",
115 Self::SuccessfulReport => "successful-report",
116 }
117 }
118}
119
120impl fmt::Display for FindingKind {
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 f.write_str(self.as_str())
123 }
124}
125
126#[derive(Debug, Clone, PartialEq, Eq)]
128#[non_exhaustive]
129pub struct Finding {
130 pub kind: FindingKind,
132 pub id: Option<String>,
134 pub flag: Option<String>,
136 pub severity: Severity,
139 pub role: Option<String>,
141 pub location: String,
143 pub context: Option<String>,
145 pub pattern: Option<String>,
147 pub test: String,
149 pub text: String,
151}
152
153#[derive(Debug, Clone, PartialEq, Eq)]
155#[non_exhaustive]
156pub struct StylesheetReport {
157 pub name: String,
159 pub version: String,
161 pub sha256: String,
163 svrl: CompactOutput,
166 pub findings: Vec<Finding>,
168 pub fired_rules: usize,
171 pub warnings: Vec<String>,
175 pub failure: Option<StylesheetFailure>,
180 pub(crate) document_uri: Option<String>,
181}
182
183#[derive(Debug, Clone, PartialEq, Eq)]
186#[non_exhaustive]
187pub struct StylesheetFailure {
188 pub code: String,
190 pub line: Option<u32>,
192 pub message: String,
194}
195
196impl StylesheetReport {
197 #[must_use]
205 pub const fn svrl(&self) -> &CompactOutput {
206 &self.svrl
207 }
208
209 pub fn canonical_svrl(&self) -> Result<String, Error> {
220 if let Some(failure) = &self.failure {
221 return Err(Error::Transform {
222 stylesheet: self.name.clone(),
223 code: failure.code.clone(),
224 line: failure.line,
225 message: failure.message.clone(),
226 });
227 }
228 let uri = self.document_uri.as_deref();
229 einvoice_svrl::canonicalize(&self.svrl.to_text(), &|u| Some(u) == uri)
230 .map_err(|e| Error::internal(format!("stylesheet {}: {e}", self.name)))
231 }
232
233 pub(crate) fn new(
236 entry: &crate::StylesheetEntry,
237 svrl: CompactOutput,
238 reader: SvrlReader,
239 warnings: Vec<String>,
240 document_uri: Option<&str>,
241 ) -> Result<Self, Error> {
242 let (findings, fired_rules) = reader.finish(&svrl).map_err(|m| {
245 Error::bundle(format!(
246 "stylesheet {}: its result is not an SVRL report: {m}",
247 entry.name()
248 ))
249 })?;
250 Ok(Self {
251 name: entry.name().to_owned(),
252 version: entry.version().to_owned(),
253 sha256: entry.sha256().to_owned(),
254 svrl,
255 findings,
256 fired_rules,
257 warnings,
258 failure: None,
259 document_uri: document_uri.map(str::to_owned),
260 })
261 }
262
263 pub(crate) fn failed(
264 entry: &crate::StylesheetEntry,
265 failure: StylesheetFailure,
266 document_uri: Option<&str>,
267 ) -> Self {
268 Self {
269 name: entry.name().to_owned(),
270 version: entry.version().to_owned(),
271 sha256: entry.sha256().to_owned(),
272 svrl: CompactOutput::default(),
273 findings: Vec::new(),
274 fired_rules: 0,
275 warnings: Vec::new(),
276 failure: Some(failure),
277 document_uri: document_uri.map(str::to_owned),
278 }
279 }
280}
281
282#[derive(Debug, Clone, PartialEq, Eq)]
284#[non_exhaustive]
285pub struct RuleSetVersion {
286 pub name: String,
288 pub title: String,
290 pub version: String,
292 pub schema: Option<crate::SchemaId>,
294 pub unchecked_schema: Option<String>,
299}
300
301#[derive(Debug, Clone, PartialEq, Eq)]
306#[non_exhaustive]
307pub enum NoScenario {
308 NoneMatches,
310 SeveralMatch(Vec<String>),
312}
313
314impl fmt::Display for NoScenario {
315 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316 match self {
317 Self::NoneMatches => f.write_str("no scenario of the rule set matches the document"),
318 Self::SeveralMatch(names) => write!(
319 f,
320 "{} scenarios of the rule set match the document, one is required: {}",
321 names.len(),
322 names.join(", ")
323 ),
324 }
325 }
326}
327
328#[derive(Debug, Clone, PartialEq, Eq)]
331#[non_exhaustive]
332pub struct Report {
333 pub rule_set: RuleSetVersion,
335 pub document_uri: Option<String>,
337 pub scenario: Option<String>,
341 pub no_scenario: Option<NoScenario>,
345 pub schema_errors: Vec<SchemaError>,
348 pub stylesheets: Vec<StylesheetReport>,
352}
353
354impl Report {
355 #[must_use]
358 pub fn verdict(&self) -> Verdict {
359 if self.no_scenario.is_none()
360 && self.schema_errors.is_empty()
361 && self.count(Severity::Fatal) == 0
362 {
363 Verdict::Valid
364 } else {
365 Verdict::Invalid
366 }
367 }
368
369 #[must_use]
371 pub fn is_complete(&self) -> bool {
372 self.stylesheets.iter().all(|s| s.failure.is_none())
373 }
374
375 #[must_use]
377 pub fn is_valid(&self) -> bool {
378 self.verdict() == Verdict::Valid
379 }
380
381 pub fn findings(&self) -> impl Iterator<Item = &Finding> {
383 self.stylesheets.iter().flat_map(|s| s.findings.iter())
384 }
385
386 #[must_use]
388 pub fn count(&self, severity: Severity) -> usize {
389 self.findings().filter(|f| f.severity == severity).count()
390 }
391}
392
393#[derive(Debug, Clone, Copy)]
397pub(crate) struct Severities<'a> {
398 pub(crate) fail_closed: bool,
400 pub(crate) unflagged_assert: Severity,
402 pub(crate) scenario: Option<&'a crate::Scenario>,
404}
405
406impl Default for Severities<'_> {
407 fn default() -> Self {
408 Self {
409 fail_closed: false,
410 unflagged_assert: Severity::Other,
411 scenario: None,
412 }
413 }
414}
415
416impl Severities<'_> {
417 pub(crate) fn of(self, kind: FindingKind, flag: Option<&str>, id: Option<&str>) -> Severity {
422 let severity = id
423 .and_then(|id| self.scenario.and_then(|s| s.level(id)))
424 .unwrap_or_else(|| match (kind, flag) {
425 (FindingKind::FailedAssert, None) => self.unflagged_assert,
426 _ => Severity::from_flag(flag),
427 });
428 if self.fail_closed && severity == Severity::Other {
429 Severity::Fatal
430 } else {
431 severity
432 }
433 }
434}
435
436#[derive(Debug, Default)]
441pub(crate) struct SvrlReader<'a> {
442 severities: Severities<'a>,
444 depth: usize,
446 roots: usize,
448 root_is_svrl: bool,
450 bad_comment: bool,
452 findings: Vec<Finding>,
453 fired_rules: usize,
454 pattern: Option<String>,
455 context: Option<String>,
456 finding: Option<Reading>,
458}
459
460#[derive(Debug)]
462struct Reading {
463 finding: Finding,
464 text: String,
466 in_text: bool,
468}
469
470impl<'a> SvrlReader<'a> {
471 pub(crate) fn new(severities: Severities<'a>) -> Self {
472 Self {
473 severities,
474 ..Self::default()
475 }
476 }
477
478 fn finish(self, svrl: &CompactOutput) -> Result<(Vec<Finding>, usize), String> {
481 if self.roots != 1 || self.bad_comment {
482 einvoice_xml::check(&svrl.to_text()).map_err(|e| e.to_string())?;
484 if self.roots != 1 {
485 return Err(format!(
486 "{} elements at the top of the document, instead of one",
487 self.roots
488 ));
489 }
490 }
491 if !self.root_is_svrl {
492 return Err("the root is not svrl:schematron-output".to_owned());
493 }
494 Ok((self.findings, self.fired_rules))
495 }
496}
497
498fn is_svrl(name: &QName, local: &str) -> bool {
500 name.namespace.as_deref() == Some(SVRL_NS) && name.local == local
501}
502
503fn attribute(attributes: &[(QName, String)], local: &str) -> Option<String> {
505 attributes
506 .iter()
507 .find(|(name, _)| {
508 name.namespace.as_deref().is_none_or(str::is_empty) && name.local == local
509 })
510 .map(|(_, value)| value.clone())
511}
512
513impl ResultObserver for SvrlReader<'_> {
514 fn start_element(&mut self, name: &QName, attributes: &[(QName, String)]) {
515 self.depth += 1;
516 match self.depth {
517 1 => {
518 self.roots += 1;
519 if self.roots == 1 {
520 self.root_is_svrl = is_svrl(name, "schematron-output");
521 }
522 }
523 2 if self.roots == 1 && name.namespace.as_deref() == Some(SVRL_NS) => {
525 let kind = match name.local.as_str() {
526 "active-pattern" => {
527 self.pattern =
528 attribute(attributes, "id").or_else(|| attribute(attributes, "name"));
529 self.context = None;
530 return;
531 }
532 "fired-rule" => {
533 self.fired_rules += 1;
534 self.context = attribute(attributes, "context");
535 return;
536 }
537 "failed-assert" => FindingKind::FailedAssert,
538 "successful-report" => FindingKind::SuccessfulReport,
539 _ => return,
540 };
541 let flag = attribute(attributes, "flag");
542 let id = attribute(attributes, "id");
543 let severity = self.severities.of(kind, flag.as_deref(), id.as_deref());
544 let finding = Finding {
545 kind,
546 id,
547 severity,
548 flag,
549 role: attribute(attributes, "role"),
550 location: attribute(attributes, "location").unwrap_or_default(),
551 context: self.context.clone(),
552 pattern: self.pattern.clone(),
553 test: attribute(attributes, "test").unwrap_or_default(),
554 text: String::new(),
555 };
556 self.finding = Some(Reading {
557 finding,
558 text: String::new(),
559 in_text: false,
560 });
561 }
562 3 if is_svrl(name, "text") => {
564 if let Some(reading) = &mut self.finding {
565 reading.in_text = true;
566 }
567 }
568 _ => {}
569 }
570 }
571
572 fn end_element(&mut self) {
573 match self.depth {
574 2 => {
575 if let Some(Reading {
576 mut finding, text, ..
577 }) = self.finding.take()
578 {
579 finding.text = einvoice_svrl::normalize_space(&text);
580 self.findings.push(finding);
581 }
582 }
583 3 => {
584 if let Some(reading) = &mut self.finding {
585 reading.in_text = false;
586 }
587 }
588 _ => {}
589 }
590 self.depth = self.depth.saturating_sub(1);
591 }
592
593 fn text(&mut self, text: &str) {
594 if let Some(reading) = &mut self.finding
595 && reading.in_text
596 {
597 reading.text.push_str(text);
598 }
599 }
600
601 fn comment(&mut self, text: &str) {
602 if text.contains("--") || text.ends_with('-') {
603 self.bad_comment = true;
604 }
605 }
606}
607
608#[cfg(test)]
609mod tests {
610 use super::*;
611
612 fn findings(svrl: &str, fail_closed: bool) -> Result<(Vec<Finding>, usize), String> {
615 let qname = |name: einvoice_xml::Name<'_, '_>| QName {
616 prefix: (!name.prefix.is_empty()).then(|| name.prefix.to_owned()),
617 namespace: name.namespace.map(str::to_owned),
618 local: name.local.to_owned(),
619 };
620 let mut reader = SvrlReader::new(Severities {
621 fail_closed,
622 ..Severities::default()
623 });
624 let mut parser = einvoice_xml::Reader::new(svrl);
625 let mut depth = 0;
626 while let Ok(Some(event)) = parser.next_event() {
627 match event {
628 einvoice_xml::Event::Start(start) => {
629 let attributes: Vec<(QName, String)> = start
630 .attributes()
631 .map(|a| (qname(a.name), a.value.to_string()))
632 .collect();
633 reader.start_element(&qname(start.name()), &attributes);
634 depth += 1;
635 }
636 einvoice_xml::Event::End(_) => {
637 reader.end_element();
638 depth -= 1;
639 }
640 einvoice_xml::Event::Text(text) if depth > 0 => reader.text(&text.value),
641 einvoice_xml::Event::Comment(comment) => reader.comment(&comment.value),
642 _ => {}
643 }
644 }
645 reader.finish(&CompactOutput::from(svrl))
646 }
647
648 #[test]
649 fn reads_findings_with_their_rule_and_pattern() {
650 let svrl = r#"<svrl:schematron-output xmlns:svrl="http://purl.oclc.org/dsdl/svrl">
651 <svrl:active-pattern id="P1"/>
652 <svrl:fired-rule context="/a"/>
653 <svrl:failed-assert id="R-1" flag="fatal" location="/a[1]" test="b">
654 <svrl:text> [R-1] two
655 lines </svrl:text>
656 </svrl:failed-assert>
657 <svrl:active-pattern name="P2"/>
658 <svrl:successful-report id="R-2" flag="warning" role="r" location="/" test="c"><svrl:text/></svrl:successful-report>
659 <svrl:fired-rule context="/z"/>
660 <svrl:failed-assert location="/" test="d"/>
661</svrl:schematron-output>"#;
662 let (f, fired_rules) = findings(svrl, false).unwrap();
663 assert_eq!(fired_rules, 2);
664 assert_eq!(f.len(), 3);
665 assert_eq!(f[0].kind, FindingKind::FailedAssert);
666 assert_eq!(f[0].id.as_deref(), Some("R-1"));
667 assert_eq!(f[0].severity, Severity::Fatal);
668 assert_eq!(f[0].context.as_deref(), Some("/a"));
669 assert_eq!(f[0].pattern.as_deref(), Some("P1"));
670 assert_eq!(f[0].text, "[R-1] two lines");
671 assert_eq!(f[1].kind, FindingKind::SuccessfulReport);
672 assert_eq!(f[1].severity, Severity::Warning);
673 assert_eq!(f[1].role.as_deref(), Some("r"));
674 assert_eq!(f[1].context, None);
675 assert_eq!(f[1].pattern.as_deref(), Some("P2"));
676 assert_eq!(f[2].severity, Severity::Other);
677 assert_eq!(f[2].id, None);
678 assert_eq!(f[2].context.as_deref(), Some("/z"));
679 let (closed, _) = findings(svrl, true).unwrap();
680 let severities: Vec<Severity> = closed.iter().map(|f| f.severity).collect();
681 assert_eq!(
682 severities,
683 [Severity::Fatal, Severity::Warning, Severity::Fatal]
684 );
685 }
686
687 fn parser_error(text: &str) -> String {
690 let options = roxmltree::ParsingOptions {
691 allow_dtd: false,
692 nodes_limit: u32::MAX,
693 ..roxmltree::ParsingOptions::default()
694 };
695 let roxmltree = roxmltree::Document::parse_with_options(text, options)
696 .unwrap_err()
697 .to_string();
698 assert_eq!(
699 einvoice_xml::check(text).unwrap_err().to_string(),
700 roxmltree
701 );
702 roxmltree
703 }
704
705 fn svrl_name(local: &str) -> QName {
706 QName {
707 prefix: Some("svrl".to_owned()),
708 namespace: Some(SVRL_NS.to_owned()),
709 local: local.to_owned(),
710 }
711 }
712
713 #[test]
714 fn refuses_what_is_not_svrl() {
715 assert_eq!(
716 findings("<a/>", false).unwrap_err(),
717 "the root is not svrl:schematron-output"
718 );
719 for text in ["<a", ""] {
721 assert_eq!(
722 findings(text, false).unwrap_err(),
723 parser_error(text),
724 "{text}"
725 );
726 }
727 let root = svrl_name("schematron-output");
730 let mut reader = SvrlReader::default();
731 for _ in 0..2 {
732 reader.start_element(&root, &[]);
733 reader.end_element();
734 }
735 let text = format!("<svrl:schematron-output xmlns:svrl=\"{SVRL_NS}\"/><a/>");
736 assert_eq!(
737 reader.finish(&CompactOutput::from(text.as_str())),
738 Err(parser_error(&text))
739 );
740 for comment in ["x -- y", "x-"] {
741 let mut reader = SvrlReader::default();
742 reader.start_element(&root, &[]);
743 reader.comment(comment);
744 reader.end_element();
745 let text = format!(
746 "<svrl:schematron-output xmlns:svrl=\"{SVRL_NS}\"><!--{comment}--></svrl:schematron-output>"
747 );
748 assert_eq!(
749 reader.finish(&CompactOutput::from(text.as_str())),
750 Err(parser_error(&text)),
751 "{comment}"
752 );
753 }
754 let mut reader = SvrlReader::default();
756 for _ in 0..2 {
757 reader.start_element(&root, &[]);
758 reader.end_element();
759 }
760 assert_eq!(
761 reader.finish(&CompactOutput::from("<a/>")).unwrap_err(),
762 "2 elements at the top of the document, instead of one"
763 );
764 }
765
766 #[test]
767 fn severities() {
768 assert_eq!(Severity::from_flag(Some("fatal")), Severity::Fatal);
769 assert_eq!(Severity::from_flag(Some("warning")), Severity::Warning);
770 assert_eq!(Severity::from_flag(Some("information")), Severity::Other);
771 assert_eq!(Severity::from_flag(None), Severity::Other);
772 assert_eq!(
773 Severity::from_flag_fail_closed(Some("fatal")),
774 Severity::Fatal
775 );
776 assert_eq!(
777 Severity::from_flag_fail_closed(Some("warning")),
778 Severity::Warning
779 );
780 assert_eq!(
781 Severity::from_flag_fail_closed(Some("information")),
782 Severity::Fatal
783 );
784 assert_eq!(Severity::from_flag_fail_closed(None), Severity::Fatal);
785 }
786
787 #[test]
790 fn severities_of_a_stylesheet() {
791 use FindingKind::{FailedAssert as A, SuccessfulReport as R};
792 let manifest = "format = 2\nname = \"n\"\ntitle = \"t\"\nversion = \"1\"\n\n[[stylesheet]]\nname = \"s\"\npath = \"s.xsl\"\nsha256 = \"0000000000000000000000000000000000000000000000000000000000000000\"\n\n[[scenario]]\nname = \"x\"\nnamespace = \"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2\"\nroot = \"Invoice\"\nidentifier = \"urn:x\"\nfatal = \"UP\"\nother = \"DOWN\"\n";
793 let rule_set = crate::RuleSet::parse(manifest).unwrap();
794 let scenario = rule_set.scenarios().first();
795 let findings = [
796 (A, Some("fatal"), Some("R")),
797 (A, Some("warning"), Some("R")),
798 (A, Some("information"), Some("R")),
799 (A, None, Some("R")),
800 (A, None, None),
801 (R, None, Some("R")),
802 (R, Some("fatal"), None),
803 (A, Some("warning"), Some("UP")),
804 (R, None, Some("UP")),
805 (A, Some("fatal"), Some("DOWN")),
806 (A, None, Some("DOWN")),
807 ];
808 let severities = |severities: Severities<'_>| -> Vec<&str> {
809 findings
810 .iter()
811 .map(|(kind, flag, id)| severities.of(*kind, *flag, *id).as_str())
812 .collect()
813 };
814 let base = Severities::default();
815 assert_eq!(
816 severities(base),
817 [
818 "fatal", "warning", "other", "other", "other", "other", "fatal", "warning",
819 "other", "fatal", "other"
820 ]
821 );
822 let unflagged = Severities {
824 unflagged_assert: Severity::Fatal,
825 ..base
826 };
827 assert_eq!(
828 severities(unflagged),
829 [
830 "fatal", "warning", "other", "fatal", "fatal", "other", "fatal", "warning",
831 "other", "fatal", "fatal"
832 ]
833 );
834 let with_scenario = Severities {
836 scenario,
837 ..unflagged
838 };
839 assert_eq!(
840 severities(with_scenario),
841 [
842 "fatal", "warning", "other", "fatal", "fatal", "other", "fatal", "fatal", "fatal",
843 "other", "other"
844 ]
845 );
846 let closed = Severities {
848 fail_closed: true,
849 ..with_scenario
850 };
851 assert_eq!(
852 severities(closed),
853 [
854 "fatal", "warning", "fatal", "fatal", "fatal", "fatal", "fatal", "fatal", "fatal",
855 "fatal", "fatal"
856 ]
857 );
858 }
859}