1use std::fmt;
8
9use crate::{Error, Severity};
10
11pub const MANIFEST_FILE: &str = "bundle.toml";
13
14pub const MANIFEST_FORMAT: u32 = 2;
19
20#[derive(Debug, Clone, PartialEq, Eq, Hash)]
23#[non_exhaustive]
24pub enum SchemaId {
25 Ubl21,
28 CiiD16b,
31 Bundle(String),
36}
37
38impl SchemaId {
39 #[must_use]
42 pub fn as_str(&self) -> &str {
43 match self {
44 Self::Ubl21 => "ubl-2.1",
45 Self::CiiD16b => "cii-d16b",
46 Self::Bundle(entry_point) => entry_point,
47 }
48 }
49
50 #[must_use]
52 pub fn from_name(name: &str) -> Option<Self> {
53 match name {
54 "ubl-2.1" => Some(Self::Ubl21),
55 "cii-d16b" => Some(Self::CiiD16b),
56 _ => None,
57 }
58 }
59}
60
61impl fmt::Display for SchemaId {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 f.write_str(self.as_str())
64 }
65}
66
67#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct StylesheetEntry {
70 name: String,
71 version: String,
72 path: String,
73 sha256: String,
74 unflagged_assert: Severity,
75}
76
77impl StylesheetEntry {
78 #[must_use]
80 pub fn name(&self) -> &str {
81 &self.name
82 }
83
84 #[must_use]
87 pub fn version(&self) -> &str {
88 &self.version
89 }
90
91 #[must_use]
93 pub fn path(&self) -> &str {
94 &self.path
95 }
96
97 #[must_use]
99 pub fn sha256(&self) -> &str {
100 &self.sha256
101 }
102
103 #[must_use]
108 pub const fn unflagged_assert(&self) -> Severity {
109 self.unflagged_assert
110 }
111}
112
113#[derive(Debug, Clone, PartialEq, Eq)]
139pub struct Scenario {
140 name: String,
141 selector: Selector,
142 stylesheets: Option<Vec<String>>,
143 levels: Vec<(String, Severity)>,
144}
145
146#[derive(Debug, Clone, PartialEq, Eq)]
148enum Selector {
149 Identifier {
151 namespace: String,
152 root: String,
153 identifier: String,
154 },
155 Match {
157 namespaces: Vec<(String, String)>,
158 expression: String,
159 },
160}
161
162impl Scenario {
163 #[must_use]
165 pub fn name(&self) -> &str {
166 &self.name
167 }
168
169 #[must_use]
172 pub fn match_expression(&self) -> Option<&str> {
173 match &self.selector {
174 Selector::Match { expression, .. } => Some(expression),
175 Selector::Identifier { .. } => None,
176 }
177 }
178
179 #[must_use]
182 pub fn namespaces(&self) -> &[(String, String)] {
183 match &self.selector {
184 Selector::Match { namespaces, .. } => namespaces,
185 Selector::Identifier { .. } => &[],
186 }
187 }
188
189 #[must_use]
193 pub fn stylesheets(&self) -> Option<&[String]> {
194 self.stylesheets.as_deref()
195 }
196
197 #[must_use]
200 pub fn namespace(&self) -> Option<&str> {
201 match &self.selector {
202 Selector::Identifier { namespace, .. } => Some(namespace),
203 Selector::Match { .. } => None,
204 }
205 }
206
207 #[must_use]
210 pub fn root(&self) -> Option<&str> {
211 match &self.selector {
212 Selector::Identifier { root, .. } => Some(root),
213 Selector::Match { .. } => None,
214 }
215 }
216
217 #[must_use]
220 pub fn identifier(&self) -> Option<&str> {
221 match &self.selector {
222 Selector::Identifier { identifier, .. } => Some(identifier),
223 Selector::Match { .. } => None,
224 }
225 }
226
227 #[must_use]
230 pub fn levels(&self) -> &[(String, Severity)] {
231 &self.levels
232 }
233
234 #[must_use]
236 pub fn level(&self, id: &str) -> Option<Severity> {
237 self.levels
238 .iter()
239 .find(|(rule, _)| rule == id)
240 .map(|(_, severity)| *severity)
241 }
242}
243
244pub(crate) const UBL_INVOICE: &str = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2";
246pub(crate) const UBL_CREDIT_NOTE: &str =
248 "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2";
249pub(crate) const CII: &str = "urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100";
252
253const IDENTIFIED_ROOTS: [(&str, &str); 3] = [
256 (UBL_INVOICE, "Invoice"),
257 (UBL_CREDIT_NOTE, "CreditNote"),
258 (CII, "CrossIndustryInvoice"),
259];
260
261#[derive(Debug, Clone, PartialEq, Eq)]
264pub struct ResourceEntry {
265 path: String,
266 sha256: String,
267}
268
269impl ResourceEntry {
270 #[must_use]
273 pub fn path(&self) -> &str {
274 &self.path
275 }
276
277 #[must_use]
279 pub fn sha256(&self) -> &str {
280 &self.sha256
281 }
282}
283
284#[derive(Debug, Clone, PartialEq, Eq)]
288pub struct SchemaDocumentEntry {
289 path: String,
290 sha256: String,
291}
292
293impl SchemaDocumentEntry {
294 #[must_use]
298 pub fn path(&self) -> &str {
299 &self.path
300 }
301
302 #[must_use]
304 pub fn sha256(&self) -> &str {
305 &self.sha256
306 }
307}
308
309#[derive(Debug, Clone, PartialEq, Eq)]
313pub struct RuleSet {
314 name: String,
315 title: String,
316 version: String,
317 schema: Option<SchemaId>,
318 unchecked_schema: Option<String>,
319 stylesheets: Vec<StylesheetEntry>,
320 resources: Vec<ResourceEntry>,
321 schema_documents: Vec<SchemaDocumentEntry>,
322 scenarios: Vec<Scenario>,
323}
324
325impl RuleSet {
326 pub fn parse(manifest: &str) -> Result<Self, Error> {
344 let tables = parse_tables(manifest)?;
345 let mut tables = tables.into_iter();
346 let Some(top) = tables.next() else {
347 return Err(Error::bundle(format!("{MANIFEST_FILE}: empty")));
348 };
349 let mut top = Table::new(top);
350 let format_line = top.line_of("format");
351 top.allow(&[
352 "format",
353 "name",
354 "title",
355 "version",
356 "schema",
357 "unchecked-schema",
358 ])?;
359 let format = match top.take("format") {
360 Some(Value::Integer(f)) if (1..=u64::from(MANIFEST_FORMAT)).contains(&f) => f,
361 Some(Value::Integer(f)) => {
362 return Err(Error::bundle(format!(
363 "{MANIFEST_FILE}:{format_line}: format {f}: only formats 1 and {MANIFEST_FORMAT} are supported"
364 )));
365 }
366 Some(Value::String(_)) => {
367 return Err(Error::bundle(format!(
368 "{MANIFEST_FILE}:{format_line}: `format` must be an integer"
369 )));
370 }
371 None => {
372 return Err(Error::bundle(format!(
373 "{MANIFEST_FILE}: the `format` key is missing (format = {MANIFEST_FORMAT})"
374 )));
375 }
376 };
377 let name = top.required_string("name")?;
378 check_name(&name).map_err(|m| top.error("name", &m))?;
379 let title = top.required_string("title")?;
380 if title.trim().is_empty() || title.chars().any(char::is_control) {
381 return Err(top.error("title", "must be non-empty text on one line"));
382 }
383 let version = top.required_string("version")?;
384 check_version(&version).map_err(|m| top.error("version", &m))?;
385 let schema_line = top.line_of("schema");
388 let schema_name = top.optional_string("schema")?;
389 let unchecked_schema = match top.optional_string("unchecked-schema")? {
390 None => None,
391 Some(_) if format < 2 => {
392 return Err(top.error("unchecked-schema", "needs format = 2"));
393 }
394 Some(s) if s.trim().is_empty() || s.chars().any(char::is_control) => {
395 return Err(top.error("unchecked-schema", "must be non-empty text on one line"));
396 }
397 Some(s) => Some(s),
398 };
399 top.finish()?;
400
401 let tables = Tables::read(tables, format, &version)?;
402 if tables.stylesheets.is_empty() {
403 return Err(Error::bundle(format!(
404 "{MANIFEST_FILE}: no [[stylesheet]]: a rule set runs at least one"
405 )));
406 }
407 let schema = resolve_schema(
408 schema_name,
409 schema_line,
410 &tables.schema_documents,
411 tables.schema_document_line,
412 )?;
413 check_scenarios(
414 &tables.scenarios,
415 &tables.scenario_lines,
416 &tables.stylesheets,
417 )?;
418 Ok(Self {
419 name,
420 title,
421 version,
422 schema,
423 unchecked_schema,
424 stylesheets: tables.stylesheets,
425 resources: tables.resources,
426 schema_documents: tables.schema_documents,
427 scenarios: tables.scenarios,
428 })
429 }
430
431 pub fn builtin(name: &str) -> Result<Self, Error> {
438 Self::parse(crate::builtin::get(name)?.0)
439 }
440
441 #[must_use]
443 pub fn name(&self) -> &str {
444 &self.name
445 }
446
447 #[must_use]
449 pub fn title(&self) -> &str {
450 &self.title
451 }
452
453 #[must_use]
455 pub fn version(&self) -> &str {
456 &self.version
457 }
458
459 #[must_use]
461 pub const fn schema(&self) -> Option<&SchemaId> {
462 self.schema.as_ref()
463 }
464
465 #[must_use]
469 pub fn schema_documents(&self) -> &[SchemaDocumentEntry] {
470 &self.schema_documents
471 }
472
473 #[must_use]
477 pub fn unchecked_schema(&self) -> Option<&str> {
478 self.unchecked_schema.as_deref()
479 }
480
481 #[must_use]
484 pub fn stylesheets(&self) -> &[StylesheetEntry] {
485 &self.stylesheets
486 }
487
488 #[must_use]
491 pub fn resources(&self) -> &[ResourceEntry] {
492 &self.resources
493 }
494
495 #[must_use]
498 pub fn scenarios(&self) -> &[Scenario] {
499 &self.scenarios
500 }
501
502 #[must_use]
507 pub fn selects_by_scenario(&self) -> bool {
508 self.scenarios
509 .first()
510 .is_some_and(|s| s.match_expression().is_some())
511 }
512}
513
514struct Tables {
516 stylesheets: Vec<StylesheetEntry>,
517 resources: Vec<ResourceEntry>,
518 schema_documents: Vec<SchemaDocumentEntry>,
519 scenarios: Vec<Scenario>,
520 scenario_lines: Vec<u32>,
522 schema_document_line: Option<u32>,
524}
525
526impl Tables {
527 fn read(
530 raw: impl Iterator<Item = RawTable>,
531 format: u64,
532 version: &str,
533 ) -> Result<Self, Error> {
534 let mut tables = Self {
535 stylesheets: Vec::new(),
536 resources: Vec::new(),
537 schema_documents: Vec::new(),
538 scenarios: Vec::new(),
539 scenario_lines: Vec::new(),
540 schema_document_line: None,
541 };
542 let mut paths: Vec<String> = Vec::new();
544 for raw in raw {
545 let kind = raw.kind;
546 let table = Table::new(raw);
547 match kind {
548 TableKind::Resource => {
549 let resource = resource(table, format, &paths)?;
550 paths.push(resource.path.clone());
551 tables.resources.push(resource);
552 }
553 TableKind::SchemaDocument => {
554 tables.schema_document_line.get_or_insert(table.header_line);
555 let document = schema_document(table, format, &paths)?;
556 paths.push(document.path.clone());
557 tables.schema_documents.push(document);
558 }
559 TableKind::Scenario => {
560 tables.scenario_lines.push(table.header_line);
561 let scenario = scenario(table, format, &tables.scenarios)?;
562 tables.scenarios.push(scenario);
563 }
564 TableKind::Stylesheet | TableKind::Top => {
565 let entry = stylesheet(table, format, version, &tables.stylesheets, &paths)?;
566 paths.push(entry.path.clone());
567 tables.stylesheets.push(entry);
568 }
569 }
570 }
571 Ok(tables)
572 }
573}
574
575fn resolve_schema(
579 name: Option<String>,
580 line: u32,
581 documents: &[SchemaDocumentEntry],
582 documents_line: Option<u32>,
583) -> Result<Option<SchemaId>, Error> {
584 let schema = match name {
585 None => None,
586 Some(s) => match SchemaId::from_name(&s) {
587 Some(id) => Some(id),
588 None if documents.iter().any(|d| d.path == s) => Some(SchemaId::Bundle(s)),
589 None => {
590 return Err(Error::bundle(format!(
591 "{MANIFEST_FILE}:{line}: `schema`: unknown schema {s:?} (known: ubl-2.1, cii-d16b, or the path of a [[schema-document]] of the bundle, its entry point)"
592 )));
593 }
594 },
595 };
596 if let Some(documents_line) = documents_line
597 && !matches!(schema, Some(SchemaId::Bundle(_)))
598 {
599 return Err(Error::bundle(format!(
600 "{MANIFEST_FILE}: [[schema-document]] of line {documents_line}: the schema documents of a bundle need `schema`, the path of their entry point"
601 )));
602 }
603 Ok(schema)
604}
605
606fn stylesheet(
609 mut table: Table,
610 format: u64,
611 version: &str,
612 stylesheets: &[StylesheetEntry],
613 paths: &[String],
614) -> Result<StylesheetEntry, Error> {
615 table.allow(&["name", "version", "path", "sha256", "unflagged-assert"])?;
616 let name = table.required_string("name")?;
617 check_name(&name).map_err(|m| table.error("name", &m))?;
618 if stylesheets.iter().any(|s| s.name == name) {
619 return Err(table.error("name", &format!("stylesheet {name:?} twice")));
620 }
621 let version = match table.optional_string("version")? {
622 Some(v) => {
623 check_version(&v).map_err(|m| table.error("version", &m))?;
624 v
625 }
626 None => version.to_owned(),
627 };
628 let path = table.required_string("path")?;
629 check_path(&path).map_err(|m| table.error("path", &m))?;
630 if paths.contains(&path) {
631 return Err(table.error("path", &format!("{path:?} twice in the bundle")));
632 }
633 let sha256 = table.sha256()?;
634 let unflagged_assert = match table.optional_string("unflagged-assert")? {
635 None => Severity::Other,
636 Some(_) if format < 2 => {
637 return Err(table.error("unflagged-assert", "needs format = 2"));
638 }
639 Some(s) => severity(&s).map_err(|m| table.error("unflagged-assert", &m))?,
640 };
641 table.finish()?;
642 Ok(StylesheetEntry {
643 name,
644 version,
645 path,
646 sha256,
647 unflagged_assert,
648 })
649}
650
651fn severity(name: &str) -> Result<Severity, String> {
653 match name {
654 "fatal" => Ok(Severity::Fatal),
655 "warning" => Ok(Severity::Warning),
656 "other" => Ok(Severity::Other),
657 _ => Err(format!("{name:?}: expected fatal, warning or other")),
658 }
659}
660
661fn scenario(mut table: Table, format: u64, scenarios: &[Scenario]) -> Result<Scenario, Error> {
663 if format < 2 {
664 return Err(Error::bundle(format!(
665 "{MANIFEST_FILE}:{}: [[scenario]] needs format = 2",
666 table.header_line
667 )));
668 }
669 table.allow(&[
670 "name",
671 "namespaces",
672 "match",
673 "stylesheets",
674 "namespace",
675 "root",
676 "identifier",
677 "fatal",
678 "warning",
679 "other",
680 ])?;
681 let name = table.required_string("name")?;
682 if name.trim().is_empty() || name.chars().any(char::is_control) {
683 return Err(table.error("name", "must be non-empty text on one line"));
684 }
685 if scenarios.iter().any(|s| s.name == name) {
686 return Err(table.error("name", &format!("scenario {name:?} twice")));
687 }
688 let selector = selector(&mut table)?;
689 let stylesheets = match table.optional_string("stylesheets")? {
690 None => None,
691 Some(names) => {
692 let names: Vec<String> = names
693 .split([' ', '\t'])
694 .filter(|n| !n.is_empty())
695 .map(str::to_owned)
696 .collect();
697 if names.is_empty() {
698 return Err(table.error(
699 "stylesheets",
700 "no stylesheet name (names separated by spaces)",
701 ));
702 }
703 Some(names)
704 }
705 };
706 let mut levels: Vec<(String, Severity)> = Vec::new();
707 for key in ["fatal", "warning", "other"] {
708 let Some(ids) = table.optional_string(key)? else {
709 continue;
710 };
711 let level = severity(key).map_err(|m| table.error(key, &m))?;
712 let before = levels.len();
713 for id in ids.split([' ', '\t']).filter(|id| !id.is_empty()) {
714 if levels.iter().any(|(rule, _)| rule == id) {
715 return Err(table.error(key, &format!("rule id {id:?} given twice")));
716 }
717 levels.push((id.to_owned(), level));
718 }
719 if levels.len() == before {
720 return Err(table.error(key, "no rule id (rule ids separated by spaces)"));
721 }
722 }
723 if levels.is_empty() && matches!(selector, Selector::Identifier { .. }) {
725 return Err(Error::bundle(format!(
726 "{}: no rule id (the keys fatal, warning and other)",
727 table.where_()
728 )));
729 }
730 table.finish()?;
731 Ok(Scenario {
732 name,
733 selector,
734 stylesheets,
735 levels,
736 })
737}
738
739fn selector(table: &mut Table) -> Result<Selector, Error> {
742 if let Some(expression) = table.optional_string("match")? {
743 for key in ["namespace", "root", "identifier"] {
744 if table.optional_string(key)?.is_some() {
745 return Err(table.error(key, "not with `match`, which says what matches"));
746 }
747 }
748 let namespaces = match table.optional_string("namespaces")? {
749 None => Vec::new(),
750 Some(text) => namespaces(&text).map_err(|m| table.error("namespaces", &m))?,
751 };
752 check_match(&expression, &namespaces).map_err(|(unsupported, m)| {
753 let error = table.error("match", &m);
754 if unsupported {
755 Error::unsupported(error.to_string())
756 } else {
757 error
758 }
759 })?;
760 return Ok(Selector::Match {
761 namespaces,
762 expression,
763 });
764 }
765 for key in ["namespaces", "stylesheets"] {
766 if table.optional_string(key)?.is_some() {
767 return Err(table.error(key, "only with `match`"));
768 }
769 }
770 let namespace = table.required_string("namespace")?;
771 let root = table.required_string("root")?;
772 if !IDENTIFIED_ROOTS.contains(&(namespace.as_str(), root.as_str())) {
773 return Err(table.error(
774 "root",
775 &format!(
776 "{{{namespace}}}{root}: a scenario matches a UBL Invoice or CreditNote, or a CII CrossIndustryInvoice"
777 ),
778 ));
779 }
780 let identifier = table.required_string("identifier")?;
781 if identifier.is_empty() || identifier.chars().any(char::is_control) {
782 return Err(table.error("identifier", "must be non-empty text on one line"));
783 }
784 Ok(Selector::Identifier {
785 namespace,
786 root,
787 identifier,
788 })
789}
790
791fn namespaces(text: &str) -> Result<Vec<(String, String)>, String> {
794 let mut out: Vec<(String, String)> = Vec::new();
795 for pair in text.split([' ', '\t']).filter(|p| !p.is_empty()) {
796 let Some((prefix, uri)) = pair.split_once('=') else {
797 return Err(format!("{pair:?}: expected prefix=uri"));
798 };
799 if !einvoice_xpath::is_ncname(prefix) || uri.is_empty() {
800 return Err(format!(
801 "{pair:?}: expected prefix=uri, the prefix an NCName"
802 ));
803 }
804 if out.iter().any(|(p, _)| p == prefix) {
805 return Err(format!("prefix {prefix:?} bound twice"));
806 }
807 out.push((prefix.to_owned(), uri.to_owned()));
808 }
809 if out.is_empty() {
810 return Err("no binding (prefix=uri pairs separated by spaces)".to_owned());
811 }
812 Ok(out)
813}
814
815pub(crate) fn namespace_map(namespaces: &[(String, String)]) -> einvoice_xpath::NamespaceMap {
817 namespaces
818 .iter()
819 .fold(einvoice_xpath::NamespaceMap::new(), |map, (prefix, uri)| {
820 map.bind(prefix, uri)
821 })
822}
823
824fn check_match(expression: &str, namespaces: &[(String, String)]) -> Result<(), (bool, String)> {
827 if expression.trim().is_empty() {
828 return Err((false, "empty".to_owned()));
829 }
830 einvoice_xpath::parse_expr(expression, &namespace_map(namespaces))
831 .map(|_| ())
832 .map_err(|e| {
833 let unsupported = matches!(
834 e.kind,
835 einvoice_xpath::ErrorKind::Unsupported | einvoice_xpath::ErrorKind::TooDeep
836 );
837 (unsupported, e.to_string())
838 })
839}
840
841fn check_scenarios(
845 scenarios: &[Scenario],
846 lines: &[u32],
847 stylesheets: &[StylesheetEntry],
848) -> Result<(), Error> {
849 let at = |index: usize| {
850 format!(
851 "{MANIFEST_FILE}: [[scenario]] of line {}",
852 lines.get(index).copied().unwrap_or(0)
853 )
854 };
855 let selecting = scenarios
856 .first()
857 .is_some_and(|s| s.match_expression().is_some());
858 for (index, scenario) in scenarios.iter().enumerate() {
859 if scenario.match_expression().is_some() != selecting {
860 return Err(Error::bundle(format!(
861 "{}: either every [[scenario]] has a `match` expression, or none has",
862 at(index)
863 )));
864 }
865 let names = scenario.stylesheets().unwrap_or_default();
866 for (i, name) in names.iter().enumerate() {
867 if !stylesheets.iter().any(|s| s.name() == name) {
868 return Err(Error::bundle(format!(
869 "{}: `stylesheets`: no stylesheet {name:?} in the bundle",
870 at(index)
871 )));
872 }
873 if names[..i].contains(name) {
874 return Err(Error::bundle(format!(
875 "{}: `stylesheets`: {name:?} twice",
876 at(index)
877 )));
878 }
879 }
880 }
881 Ok(())
882}
883
884fn resource(table: Table, format: u64, paths: &[String]) -> Result<ResourceEntry, Error> {
887 let (path, sha256) = bundle_file(table, format, "[[resource]]", paths)?;
888 Ok(ResourceEntry { path, sha256 })
889}
890
891fn schema_document(
894 table: Table,
895 format: u64,
896 paths: &[String],
897) -> Result<SchemaDocumentEntry, Error> {
898 let (path, sha256) = bundle_file(table, format, "[[schema-document]]", paths)?;
899 Ok(SchemaDocumentEntry { path, sha256 })
900}
901
902fn bundle_file(
905 mut table: Table,
906 format: u64,
907 header: &str,
908 paths: &[String],
909) -> Result<(String, String), Error> {
910 if format < 2 {
911 return Err(Error::bundle(format!(
912 "{MANIFEST_FILE}:{}: {header} needs format = 2",
913 table.header_line
914 )));
915 }
916 table.allow(&["path", "sha256"])?;
917 let path = table.required_string("path")?;
918 check_path(&path).map_err(|m| table.error("path", &m))?;
919 if paths.contains(&path) {
920 return Err(table.error("path", &format!("{path:?} twice in the bundle")));
921 }
922 let sha256 = table.sha256()?;
923 table.finish()?;
924 Ok((path, sha256))
925}
926
927fn check_name(name: &str) -> Result<(), String> {
928 let mut bytes = name.bytes();
929 let first_ok = bytes.next().is_some_and(|b| b.is_ascii_alphanumeric());
930 if first_ok && bytes.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_')) {
931 Ok(())
932 } else {
933 Err(format!(
934 "{name:?}: ASCII letters, digits, `-`, `.` and `_` only, starting with a letter or digit"
935 ))
936 }
937}
938
939fn check_version(version: &str) -> Result<(), String> {
940 if !version.is_empty()
941 && version
942 .chars()
943 .all(|c| !c.is_whitespace() && !c.is_control())
944 {
945 Ok(())
946 } else {
947 Err(format!("{version:?}: must be non-empty, without spaces"))
948 }
949}
950
951fn check_path(path: &str) -> Result<(), String> {
954 let bad = path.is_empty()
955 || path.contains(['\\', ':'])
956 || path.chars().any(char::is_control)
957 || path
958 .split('/')
959 .any(|segment| segment.is_empty() || segment == "." || segment == "..");
960 if bad {
961 Err(format!(
962 "{path:?}: must be a relative `/`-separated path inside the bundle (no empty, `.` or `..` segment, no `\\` or `:`)"
963 ))
964 } else {
965 Ok(())
966 }
967}
968
969#[derive(Debug, Clone, PartialEq, Eq)]
971enum Value {
972 String(String),
973 Integer(u64),
974}
975
976#[derive(Debug, Clone, Copy, PartialEq, Eq)]
979enum TableKind {
980 Top,
981 Stylesheet,
982 Resource,
983 SchemaDocument,
984 Scenario,
985}
986
987#[derive(Debug)]
990struct RawTable {
991 kind: TableKind,
992 header_line: u32,
993 entries: Vec<(String, Value, u32)>,
994}
995
996fn parse_tables(text: &str) -> Result<Vec<RawTable>, Error> {
1001 let mut tables = vec![RawTable {
1002 kind: TableKind::Top,
1003 header_line: 0,
1004 entries: Vec::new(),
1005 }];
1006 for (index, line) in text.split('\n').enumerate() {
1007 let number = u32::try_from(index + 1).unwrap_or(u32::MAX);
1008 let fail = |message: &str| Error::bundle(format!("{MANIFEST_FILE}:{number}: {message}"));
1009 let line = line.strip_suffix('\r').unwrap_or(line);
1010 let content = line.trim_matches([' ', '\t']);
1011 if content.is_empty() || content.starts_with('#') {
1012 continue;
1013 }
1014 if let Some(rest) = content.strip_prefix('[') {
1015 let header = [
1016 ("[stylesheet]]", TableKind::Stylesheet),
1017 ("[resource]]", TableKind::Resource),
1018 ("[schema-document]]", TableKind::SchemaDocument),
1019 ("[scenario]]", TableKind::Scenario),
1020 ]
1021 .into_iter()
1022 .find_map(|(h, kind)| rest.strip_prefix(h).map(|after| (after_value(after), kind)));
1023 match header {
1024 Some((Ok(()), kind)) => {
1025 tables.push(RawTable {
1026 kind,
1027 header_line: number,
1028 entries: Vec::new(),
1029 });
1030 continue;
1031 }
1032 Some((Err(m), _)) => return Err(fail(&m)),
1033 None => {
1034 return Err(fail(
1035 "the only tables allowed are [[stylesheet]], [[resource]], [[schema-document]] and [[scenario]]",
1036 ));
1037 }
1038 }
1039 }
1040 let Some((key, value)) = content.split_once('=') else {
1041 return Err(fail("expected `key = value`"));
1042 };
1043 let key = key.trim_matches([' ', '\t']);
1044 if key.is_empty()
1045 || !key
1046 .bytes()
1047 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_'))
1048 {
1049 return Err(fail(&format!("{key:?}: expected a bare key")));
1050 }
1051 let value = parse_value(value.trim_start_matches([' ', '\t'])).map_err(|m| fail(&m))?;
1052 let Some(table) = tables.last_mut() else {
1053 return Err(Error::internal("manifest: no table"));
1054 };
1055 if table.entries.iter().any(|(k, _, _)| k == key) {
1056 return Err(fail(&format!("key `{key}` repeated")));
1057 }
1058 table.entries.push((key.to_owned(), value, number));
1059 }
1060 Ok(tables)
1061}
1062
1063fn parse_value(text: &str) -> Result<Value, String> {
1064 if let Some(rest) = text.strip_prefix('"') {
1065 let mut value = String::new();
1066 let mut chars = rest.char_indices();
1067 while let Some((i, c)) = chars.next() {
1068 match c {
1069 '"' => {
1070 after_value(&rest[i + 1..])?;
1071 return Ok(Value::String(value));
1072 }
1073 '\\' => match chars.next() {
1074 Some((_, '"')) => value.push('"'),
1075 Some((_, '\\')) => value.push('\\'),
1076 _ => return Err("only the escapes \\\" and \\\\ are accepted".to_owned()),
1077 },
1078 c if c.is_control() && c != '\t' => {
1079 return Err("control character in a string".to_owned());
1080 }
1081 c => value.push(c),
1082 }
1083 }
1084 Err("unterminated string".to_owned())
1085 } else if let Some(rest) = text.strip_prefix('\'') {
1086 let end = rest
1087 .find('\'')
1088 .ok_or_else(|| "unterminated string".to_owned())?;
1089 let value = &rest[..end];
1090 if value.chars().any(|c| c.is_control() && c != '\t') {
1091 return Err("control character in a string".to_owned());
1092 }
1093 after_value(&rest[end + 1..])?;
1094 Ok(Value::String(value.to_owned()))
1095 } else {
1096 let end = text
1097 .find(|c: char| !c.is_ascii_digit())
1098 .unwrap_or(text.len());
1099 let digits = &text[..end];
1100 if digits.is_empty() || (digits.len() > 1 && digits.starts_with('0')) {
1101 return Err("expected a string or a non-negative integer".to_owned());
1102 }
1103 let value = digits
1104 .parse()
1105 .map_err(|_| "integer out of range".to_owned())?;
1106 after_value(&text[end..])?;
1107 Ok(Value::Integer(value))
1108 }
1109}
1110
1111fn after_value(rest: &str) -> Result<(), String> {
1113 let rest = rest.trim_start_matches([' ', '\t']);
1114 if rest.is_empty() || rest.starts_with('#') {
1115 Ok(())
1116 } else {
1117 Err(format!("unexpected {rest:?} after the value"))
1118 }
1119}
1120
1121struct Table {
1123 kind: TableKind,
1124 header_line: u32,
1125 entries: Vec<(String, Option<Value>, u32)>,
1127}
1128
1129impl Table {
1130 fn new(raw: RawTable) -> Self {
1131 Self {
1132 kind: raw.kind,
1133 header_line: raw.header_line,
1134 entries: raw
1135 .entries
1136 .into_iter()
1137 .map(|(k, v, l)| (k, Some(v), l))
1138 .collect(),
1139 }
1140 }
1141
1142 fn where_(&self) -> String {
1143 match self.kind {
1144 TableKind::Top => MANIFEST_FILE.to_owned(),
1145 TableKind::Stylesheet => format!(
1146 "{MANIFEST_FILE}: [[stylesheet]] of line {}",
1147 self.header_line
1148 ),
1149 TableKind::Resource => {
1150 format!("{MANIFEST_FILE}: [[resource]] of line {}", self.header_line)
1151 }
1152 TableKind::SchemaDocument => format!(
1153 "{MANIFEST_FILE}: [[schema-document]] of line {}",
1154 self.header_line
1155 ),
1156 TableKind::Scenario => {
1157 format!("{MANIFEST_FILE}: [[scenario]] of line {}", self.header_line)
1158 }
1159 }
1160 }
1161
1162 fn sha256(&mut self) -> Result<String, Error> {
1164 let sha256 = self.required_string("sha256")?;
1165 if sha256.len() != 64
1166 || !sha256
1167 .bytes()
1168 .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
1169 {
1170 return Err(self.error("sha256", "must be 64 lower-case hexadecimal digits"));
1171 }
1172 Ok(sha256)
1173 }
1174
1175 fn line_of(&self, key: &str) -> u32 {
1177 self.entries
1178 .iter()
1179 .find(|(k, _, _)| k == key)
1180 .map_or(self.header_line, |(_, _, l)| *l)
1181 }
1182
1183 fn error(&self, key: &str, message: &str) -> Error {
1184 Error::bundle(format!(
1185 "{MANIFEST_FILE}:{}: `{key}`: {message}",
1186 self.line_of(key)
1187 ))
1188 }
1189
1190 fn allow(&self, allowed: &[&str]) -> Result<(), Error> {
1192 match self
1193 .entries
1194 .iter()
1195 .find(|(k, _, _)| !allowed.contains(&k.as_str()))
1196 {
1197 Some((key, _, line)) => Err(Error::bundle(format!(
1198 "{MANIFEST_FILE}:{line}: unknown key `{key}` (expected one of: {})",
1199 allowed.join(", ")
1200 ))),
1201 None => Ok(()),
1202 }
1203 }
1204
1205 fn take(&mut self, key: &str) -> Option<Value> {
1206 self.entries
1207 .iter_mut()
1208 .find(|(k, _, _)| k == key)
1209 .and_then(|(_, v, _)| v.take())
1210 }
1211
1212 fn optional_string(&mut self, key: &str) -> Result<Option<String>, Error> {
1213 match self.take(key) {
1214 None => Ok(None),
1215 Some(Value::String(s)) => Ok(Some(s)),
1216 Some(Value::Integer(_)) => Err(self.error(key, "must be a string")),
1217 }
1218 }
1219
1220 fn required_string(&mut self, key: &str) -> Result<String, Error> {
1221 let where_ = self.where_();
1222 self.optional_string(key)?
1223 .ok_or_else(|| Error::bundle(format!("{where_}: the `{key}` key is missing")))
1224 }
1225
1226 fn finish(self) -> Result<(), Error> {
1227 match self.entries.iter().find(|(_, v, _)| v.is_some()) {
1228 Some((key, _, line)) => Err(Error::bundle(format!(
1229 "{MANIFEST_FILE}:{line}: unexpected key `{key}`"
1230 ))),
1231 None => Ok(()),
1232 }
1233 }
1234}
1235
1236#[cfg(test)]
1237mod tests {
1238 use super::*;
1239
1240 const GOOD: &str = r#"# comment
1241format = 1
1242name = "cen-ubl" # trailing comment
1243title = 'CEN EN 16931 UBL'
1244version = "1.3.17"
1245schema = "ubl-2.1"
1246
1247[[stylesheet]]
1248name = "EN16931-UBL"
1249path = "ubl/xslt/EN16931-UBL-validation.xslt"
1250sha256 = "fc4e6cfa8596bba0c2abd19038a98960c6ee9fc1f44566787c115efd4f4aca7c"
1251
1252[[stylesheet]] # second
1253name = "other"
1254version = "3.0.22"
1255path = "x.xsl"
1256sha256 = "0000000000000000000000000000000000000000000000000000000000000000"
1257"#;
1258
1259 #[test]
1260 fn parses_a_manifest() {
1261 let rule_set = RuleSet::parse(GOOD).unwrap();
1262 assert_eq!(rule_set.name(), "cen-ubl");
1263 assert_eq!(rule_set.title(), "CEN EN 16931 UBL");
1264 assert_eq!(rule_set.version(), "1.3.17");
1265 assert_eq!(rule_set.schema(), Some(&SchemaId::Ubl21));
1266 assert_eq!(rule_set.schema_documents(), []);
1267 let s = rule_set.stylesheets();
1268 assert_eq!(s.len(), 2);
1269 assert_eq!(s[0].name(), "EN16931-UBL");
1270 assert_eq!(s[0].version(), "1.3.17");
1271 assert_eq!(s[0].path(), "ubl/xslt/EN16931-UBL-validation.xslt");
1272 assert_eq!(s[1].version(), "3.0.22");
1273 }
1274
1275 #[test]
1276 fn the_embedded_manifest_parses() {
1277 let rule_set = RuleSet::parse(include_str!("../bundles/cen-ubl/bundle.toml")).unwrap();
1278 assert_eq!(rule_set.name(), "cen-ubl");
1279 }
1280
1281 #[test]
1282 fn format_2_lists_resources() {
1283 let zeros = "0".repeat(64);
1284 let text = format!(
1285 "{}[[resource]]\npath = \"codes/a.xml\"\nsha256 = \"{zeros}\"\n\n[[resource]] # b\npath = \"b.xml\"\nsha256 = \"{}\"\n",
1286 GOOD.replace("format = 1", "format = 2"),
1287 "1".repeat(64)
1288 );
1289 let rule_set = RuleSet::parse(&text).unwrap();
1290 let resources: Vec<(&str, &str)> = rule_set
1291 .resources()
1292 .iter()
1293 .map(|r| (r.path(), r.sha256()))
1294 .collect();
1295 assert_eq!(
1296 resources,
1297 [
1298 ("codes/a.xml", zeros.as_str()),
1299 ("b.xml", "1".repeat(64).as_str())
1300 ]
1301 );
1302 assert_eq!(rule_set.stylesheets().len(), 2);
1303 assert_eq!(RuleSet::parse(GOOD).unwrap().resources(), []);
1304 for (bad, expected) in [
1305 (text.replace("codes/a.xml", "../a.xml"), "`path`"),
1306 (text.replace("codes/a.xml", "b.xml"), "twice in the bundle"),
1307 (text.replace("codes/a.xml", "x.xsl"), "twice in the bundle"),
1308 (
1309 text.replace(&format!("sha256 = \"{zeros}\""), "sha256 = \"x\""),
1310 "`sha256`",
1311 ),
1312 (
1313 text.replace("path = \"b.xml\"", "name = \"b\"\npath = \"b.xml\""),
1314 "unknown key `name`",
1315 ),
1316 (
1317 text.replace("path = \"b.xml\"\n", ""),
1318 "[[resource]] of line 22: the `path` key is missing",
1319 ),
1320 ] {
1321 let message = error(&bad);
1322 assert!(
1323 message.contains(expected),
1324 "{expected:?} not in {message:?}"
1325 );
1326 }
1327 }
1328
1329 fn with_severities() -> String {
1332 format!(
1333 "{}
1334[[scenario]]
1335name = \"S 1\"
1336namespace = \"{UBL_INVOICE}\"
1337root = \"Invoice\"
1338identifier = \"urn:x\"
1339fatal = \"R-1 R-2\"
1340other = \"R-3\"
1341
1342[[scenario]] # CII
1343name = \"S 2\"
1344namespace = \"{CII}\"
1345root = \"CrossIndustryInvoice\"
1346identifier = \"urn:y#z\"
1347warning = \"R-1\"
1348",
1349 GOOD.replace("format = 1", "format = 2").replace(
1350 "path = \"x.xsl\"",
1351 "path = \"x.xsl\"\nunflagged-assert = \"fatal\""
1352 )
1353 )
1354 }
1355
1356 #[test]
1357 fn format_2_reads_severities() {
1358 let text = with_severities();
1359 let rule_set = RuleSet::parse(&text).unwrap();
1360 let unflagged: Vec<Severity> = rule_set
1361 .stylesheets()
1362 .iter()
1363 .map(StylesheetEntry::unflagged_assert)
1364 .collect();
1365 assert_eq!(unflagged, [Severity::Other, Severity::Fatal]);
1366 let [s1, s2] = rule_set.scenarios() else {
1367 panic!("{:?}", rule_set.scenarios());
1368 };
1369 assert_eq!(
1370 (s1.name(), s1.namespace(), s1.root(), s1.identifier()),
1371 ("S 1", Some(UBL_INVOICE), Some("Invoice"), Some("urn:x"))
1372 );
1373 assert_eq!(
1374 s1.levels(),
1375 [
1376 ("R-1".to_owned(), Severity::Fatal),
1377 ("R-2".to_owned(), Severity::Fatal),
1378 ("R-3".to_owned(), Severity::Other)
1379 ]
1380 );
1381 assert_eq!(s1.level("R-2"), Some(Severity::Fatal));
1382 assert_eq!(s1.level("R-4"), None);
1383 assert_eq!(
1384 (s2.root(), s2.identifier()),
1385 (Some("CrossIndustryInvoice"), Some("urn:y#z"))
1386 );
1387 assert_eq!(s2.level("R-1"), Some(Severity::Warning));
1388 assert_eq!(RuleSet::parse(GOOD).unwrap().scenarios(), []);
1390 assert!(
1391 RuleSet::parse(GOOD)
1392 .unwrap()
1393 .stylesheets()
1394 .iter()
1395 .all(|s| s.unflagged_assert() == Severity::Other)
1396 );
1397 }
1398
1399 #[test]
1400 fn severities_are_refused_with_the_line() {
1401 let text = with_severities();
1402 let in_format_1 = text.replace("format = 2", "format = 1");
1403 assert!(
1404 error(&in_format_1).contains("bundle.toml:17: `unflagged-assert`: needs format = 2")
1405 );
1406 let scenario_in_format_1 = in_format_1.replace("unflagged-assert = \"fatal\"\n", "");
1407 assert!(
1408 error(&scenario_in_format_1).contains("bundle.toml:19: [[scenario]] needs format = 2"),
1409 "{}",
1410 error(&scenario_in_format_1)
1411 );
1412 for (bad, expected) in [
1413 (
1414 text.replace(
1415 "unflagged-assert = \"fatal\"",
1416 "unflagged-assert = \"error\"",
1417 ),
1418 "`unflagged-assert`: \"error\": expected fatal, warning or other",
1419 ),
1420 (
1421 text.replace("name = \"S 2\"", "name = \"S 1\""),
1422 "scenario \"S 1\" twice",
1423 ),
1424 (
1425 text.replace("root = \"Invoice\"", "root = \"CreditNote\""),
1426 "`root`: {urn:oasis:names:specification:ubl:schema:xsd:Invoice-2}CreditNote: a scenario matches",
1427 ),
1428 (
1429 text.replace("root = \"Invoice\"", "root = \"Order\""),
1430 "a scenario matches a UBL Invoice or CreditNote, or a CII CrossIndustryInvoice",
1431 ),
1432 (
1433 text.replace("other = \"R-3\"", "other = \"R-2\""),
1434 "rule id \"R-2\" given twice",
1435 ),
1436 (
1437 text.replace("warning = \"R-1\"", "warning = \" \""),
1438 "`warning`: no rule id",
1439 ),
1440 (
1441 text.replace("warning = \"R-1\"\n", ""),
1442 "[[scenario]] of line 28: no rule id (the keys fatal, warning and other)",
1443 ),
1444 (
1445 text.replace("identifier = \"urn:x\"", "identifier = \"\""),
1446 "`identifier`",
1447 ),
1448 (
1449 text.replace("name = \"S 1\"", "name = \" \""),
1450 "`name`: must be non-empty",
1451 ),
1452 (
1453 text.replace("identifier = \"urn:x\"\n", ""),
1454 "[[scenario]] of line 20: the `identifier` key is missing",
1455 ),
1456 (
1457 text.replace("other = \"R-3\"", "information = \"R-3\""),
1458 "unknown key `information`",
1459 ),
1460 ] {
1461 let message = error(&bad);
1462 assert!(
1463 message.contains(expected),
1464 "{expected:?} not in {message:?}"
1465 );
1466 }
1467 }
1468
1469 fn with_matches() -> String {
1472 format!(
1473 "{}
1474[[scenario]]
1475name = \"Both\"
1476namespaces = \"cbc=urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2 invoice={UBL_INVOICE}\"
1477match = \"exists(/invoice:Invoice/cbc:CustomizationID[ . = 'urn:x#y']) \"
1478stylesheets = \"EN16931-UBL other\"
1479fatal = \"R-1\"
1480
1481[[scenario]]
1482name = \"First\"
1483namespaces = \"invoice={UBL_INVOICE}\"
1484match = \"exists(/invoice:Invoice)\"
1485stylesheets = \"EN16931-UBL\"
1486
1487[[scenario]]
1488name = \"Every one\"
1489match = \"true()\"
1490",
1491 GOOD.replace("format = 1", "format = 2").replace(
1492 "schema = \"ubl-2.1\"",
1493 "schema = \"ubl-2.1\"\nunchecked-schema = \"Another schema (x.xsd)\""
1494 )
1495 )
1496 }
1497
1498 #[test]
1499 fn format_2_selects_by_scenario() {
1500 let text = with_matches();
1501 let rule_set = RuleSet::parse(&text).unwrap();
1502 assert!(rule_set.selects_by_scenario());
1503 assert_eq!(rule_set.unchecked_schema(), Some("Another schema (x.xsd)"));
1504 let [both, first, every] = rule_set.scenarios() else {
1505 panic!("{:?}", rule_set.scenarios());
1506 };
1507 assert_eq!(
1508 both.match_expression(),
1509 Some("exists(/invoice:Invoice/cbc:CustomizationID[ . = 'urn:x#y']) ")
1510 );
1511 assert_eq!(
1512 both.namespaces(),
1513 [
1514 (
1515 "cbc".to_owned(),
1516 "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"
1517 .to_owned()
1518 ),
1519 ("invoice".to_owned(), UBL_INVOICE.to_owned())
1520 ]
1521 );
1522 assert_eq!(
1523 both.stylesheets(),
1524 Some(&["EN16931-UBL".to_owned(), "other".to_owned()][..])
1525 );
1526 assert_eq!(both.level("R-1"), Some(Severity::Fatal));
1527 assert_eq!(
1528 (both.namespace(), both.root(), both.identifier()),
1529 (None, None, None)
1530 );
1531 assert_eq!(first.levels(), []);
1534 assert_eq!(first.stylesheets().map(<[String]>::len), Some(1));
1535 assert_eq!(every.stylesheets(), None);
1536 assert_eq!(every.namespaces(), []);
1537 let identified = RuleSet::parse(&with_severities()).unwrap();
1539 assert!(!identified.selects_by_scenario());
1540 assert_eq!(identified.scenarios()[0].match_expression(), None);
1541 assert_eq!(identified.scenarios()[0].stylesheets(), None);
1542 assert_eq!(identified.unchecked_schema(), None);
1543 assert!(!RuleSet::parse(GOOD).unwrap().selects_by_scenario());
1544 }
1545
1546 #[test]
1547 fn match_scenarios_are_refused_with_the_line() {
1548 let text = with_matches();
1549 let identified = "\n[[scenario]]\nname = \"I\"\nnamespace = \"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2\"\nroot = \"Invoice\"\nidentifier = \"urn:x\"\nfatal = \"R-1\"\n";
1550 for (bad, expected) in [
1551 (
1552 text.replace("format = 2", "format = 1")
1553 .replace("unchecked-schema = \"Another schema (x.xsd)\"\n", "")
1554 .split("\n[[scenario]]")
1555 .next()
1556 .unwrap()
1557 .replace(
1558 "version = \"1.3.17\"",
1559 "version = \"1.3.17\"\nunchecked-schema = \"x\"",
1560 ),
1561 "bundle.toml:6: `unchecked-schema`: needs format = 2",
1562 ),
1563 (
1564 text.replace("\"Another schema (x.xsd)\"", "\" \""),
1565 "`unchecked-schema`: must be non-empty",
1566 ),
1567 (
1568 text.replace("match = \"true()\"", "match = \"true(\""),
1569 "bundle.toml:35: `match`: syntax error",
1570 ),
1571 (
1572 text.replace(
1573 "match = \"exists(/invoice:Invoice)\"",
1574 "match = \"exists(/x:Invoice)\"",
1575 ),
1576 "`match`: undeclared namespace prefix",
1577 ),
1578 (
1579 text.replace("match = \"true()\"", "match = \" \""),
1580 "`match`: empty",
1581 ),
1582 (
1583 text.replace(
1584 "stylesheets = \"EN16931-UBL\"",
1585 "stylesheets = \"EN16931-UBL x\"",
1586 ),
1587 "[[scenario]] of line 27: `stylesheets`: no stylesheet \"x\" in the bundle",
1588 ),
1589 (
1590 text.replace(
1591 "stylesheets = \"EN16931-UBL\"",
1592 "stylesheets = \"other other\"",
1593 ),
1594 "`stylesheets`: \"other\" twice",
1595 ),
1596 (
1597 text.replace("stylesheets = \"EN16931-UBL\"", "stylesheets = \" \""),
1598 "`stylesheets`: no stylesheet name",
1599 ),
1600 (
1601 text.replace(
1602 "match = \"true()\"",
1603 "match = \"true()\"\nroot = \"Invoice\"",
1604 ),
1605 "`root`: not with `match`",
1606 ),
1607 (
1608 text.replace("namespaces = \"invoice=", "namespaces = \"invoice "),
1609 "`namespaces`: \"invoice\": expected prefix=uri",
1610 ),
1611 (
1612 text.replace("namespaces = \"invoice=", "namespaces = \"1x="),
1613 "the prefix an NCName",
1614 ),
1615 (
1616 text.replace(
1617 "namespaces = \"invoice=",
1618 "namespaces = \"invoice=urn:a invoice=",
1619 ),
1620 "prefix \"invoice\" bound twice",
1621 ),
1622 (
1623 format!("{text}{identified}"),
1624 "[[scenario]] of line 37: either every [[scenario]] has a `match` expression, or none has",
1625 ),
1626 (
1627 format!("{}\nstylesheets = \"other\"\n", with_severities()),
1628 "`stylesheets`: only with `match`",
1629 ),
1630 ] {
1631 let message = error(&bad);
1632 assert!(
1633 message.contains(expected),
1634 "{expected:?} not in {message:?}"
1635 );
1636 }
1637 let unsupported = text.replace("match = \"true()\"", "match = \"let $x := 1 return $x\"");
1639 let e = RuleSet::parse(&unsupported).unwrap_err();
1640 assert_eq!(e.kind(), crate::ErrorKind::Unsupported, "{e}");
1641 }
1642
1643 #[test]
1644 fn schema_is_optional() {
1645 let text = GOOD.replace("schema = \"ubl-2.1\"\n", "");
1646 assert_eq!(RuleSet::parse(&text).unwrap().schema(), None);
1647 }
1648
1649 #[test]
1650 fn schema_names() {
1651 for id in [SchemaId::Ubl21, SchemaId::CiiD16b] {
1652 assert_eq!(SchemaId::from_name(id.as_str()).as_ref(), Some(&id));
1653 let text = GOOD.replace("ubl-2.1", id.as_str());
1654 assert_eq!(RuleSet::parse(&text).unwrap().schema(), Some(&id));
1655 }
1656 assert_eq!(SchemaId::CiiD16b.to_string(), "cii-d16b");
1657 assert_eq!(SchemaId::from_name("CII-D16B"), None);
1658 assert_eq!(SchemaId::from_name("x/main.xsd"), None);
1660 let bundle = SchemaId::Bundle("x/main.xsd".to_owned());
1661 assert_eq!(
1662 (bundle.as_str(), bundle.to_string().as_str()),
1663 ("x/main.xsd", "x/main.xsd")
1664 );
1665 }
1666
1667 fn with_schema_documents() -> String {
1670 format!(
1671 "{}\n[[schema-document]]\npath = \"xsd/main.xsd\"\nsha256 = \"{}\"\n\n[[schema-document]] # imported\npath = \"xsd/types.xsd\"\nsha256 = \"{}\"\n",
1672 GOOD.replace("format = 1", "format = 2")
1673 .replace("schema = \"ubl-2.1\"", "schema = \"xsd/main.xsd\""),
1674 "2".repeat(64),
1675 "3".repeat(64)
1676 )
1677 }
1678
1679 #[test]
1680 fn format_2_names_the_schema_documents_of_the_bundle() {
1681 let text = with_schema_documents();
1682 let rule_set = RuleSet::parse(&text).unwrap();
1683 assert_eq!(
1684 rule_set.schema(),
1685 Some(&SchemaId::Bundle("xsd/main.xsd".to_owned()))
1686 );
1687 let documents: Vec<(&str, &str)> = rule_set
1688 .schema_documents()
1689 .iter()
1690 .map(|d| (d.path(), d.sha256()))
1691 .collect();
1692 assert_eq!(
1693 documents,
1694 [
1695 ("xsd/main.xsd", "2".repeat(64).as_str()),
1696 ("xsd/types.xsd", "3".repeat(64).as_str())
1697 ]
1698 );
1699 assert_eq!(rule_set.resources(), []);
1700 let types = text.replace("schema = \"xsd/main.xsd\"", "schema = \"xsd/types.xsd\"");
1702 assert_eq!(
1703 RuleSet::parse(&types).unwrap().schema(),
1704 Some(&SchemaId::Bundle("xsd/types.xsd".to_owned()))
1705 );
1706 for (bad, expected) in [
1707 (
1709 text.replace("schema = \"xsd/main.xsd\"", "schema = \"xsd/other.xsd\""),
1710 "bundle.toml:6: `schema`: unknown schema \"xsd/other.xsd\"",
1711 ),
1712 (
1714 text.replace("schema = \"xsd/main.xsd\"\n", ""),
1715 "[[schema-document]] of line 18: the schema documents of a bundle need `schema`",
1716 ),
1717 (
1718 text.replace("schema = \"xsd/main.xsd\"", "schema = \"ubl-2.1\""),
1719 "[[schema-document]] of line 19: the schema documents of a bundle need `schema`",
1720 ),
1721 (
1723 text.replace("format = 2", "format = 1"),
1724 "bundle.toml:19: [[schema-document]] needs format = 2",
1725 ),
1726 (
1728 text.replace("xsd/types.xsd", "xsd/main.xsd"),
1729 "twice in the bundle",
1730 ),
1731 (
1732 text.replace("xsd/types.xsd", "x.xsl"),
1733 "twice in the bundle",
1734 ),
1735 (
1736 format!(
1737 "{text}\n[[resource]]\npath = \"xsd/types.xsd\"\nsha256 = \"{}\"\n",
1738 "4".repeat(64)
1739 ),
1740 "twice in the bundle",
1741 ),
1742 (text.replace("xsd/types.xsd", "../types.xsd"), "`path`"),
1743 (
1744 text.replace(
1745 &format!("sha256 = \"{}\"", "3".repeat(64)),
1746 "sha256 = \"3\"",
1747 ),
1748 "`sha256`",
1749 ),
1750 (
1751 text.replace(
1752 "path = \"xsd/types.xsd\"",
1753 "name = \"t\"\npath = \"xsd/types.xsd\"",
1754 ),
1755 "unknown key `name`",
1756 ),
1757 (
1758 text.replace("path = \"xsd/types.xsd\"\n", ""),
1759 "[[schema-document]] of line 23: the `path` key is missing",
1760 ),
1761 ] {
1762 let message = error(&bad);
1763 assert!(
1764 message.contains(expected),
1765 "{expected:?} not in {message:?}"
1766 );
1767 }
1768 }
1769
1770 fn error(text: &str) -> String {
1771 RuleSet::parse(text).unwrap_err().to_string()
1772 }
1773
1774 #[test]
1775 fn refusals_name_the_line() {
1776 let cases = [
1777 (
1778 GOOD.replace("format = 1", "format = 3"),
1779 "bundle.toml:2: format 3",
1780 ),
1781 (
1782 format!(
1783 "{GOOD}[[resource]]\npath = \"r.xml\"\nsha256 = \"{}\"\n",
1784 "0".repeat(64)
1785 ),
1786 "bundle.toml:18: [[resource]] needs format = 2",
1787 ),
1788 (
1789 GOOD.replace("format = 1", "format = \"1\""),
1790 "bundle.toml:2:",
1791 ),
1792 (
1793 GOOD.replace("format = 1\n", ""),
1794 "the `format` key is missing",
1795 ),
1796 (
1797 GOOD.replace("ubl-2.1", "ubl-2.2"),
1798 "bundle.toml:6: `schema`: unknown schema",
1799 ),
1800 (
1801 GOOD.replace("title =", "titel ="),
1802 "bundle.toml:4: unknown key `titel`",
1803 ),
1804 (
1805 GOOD.replace("name = \"other\"", "name = \"EN16931-UBL\""),
1806 "twice",
1807 ),
1808 (GOOD.replace("x.xsl", "../x.xsl"), "`path`"),
1809 (GOOD.replace("x.xsl", "/x.xsl"), "`path`"),
1810 (GOOD.replace("x.xsl", "C:/x.xsl"), "`path`"),
1811 (GOOD.replace("x.xsl", "a//x.xsl"), "`path`"),
1812 (GOOD.replace("x.xsl", "a\\\\x.xsl"), "`path`"),
1813 (GOOD.replace("\"0000", "\"A000"), "`sha256`"),
1814 (
1815 GOOD.replace("version = \"1.3.17\"", "version = \"1 3\""),
1816 "`version`",
1817 ),
1818 (
1819 GOOD.replace("[[stylesheet]] #", "[stylesheet] #"),
1820 "bundle.toml:13: the only tables allowed",
1821 ),
1822 (
1823 GOOD.replace("name = \"cen-ubl\"", "name = \"cen\\nubl\""),
1824 "bundle.toml:3: only the escapes",
1825 ),
1826 (
1827 GOOD.replace("name = \"cen-ubl\"", "name = \"cen-ubl"),
1828 "unterminated",
1829 ),
1830 (
1831 GOOD.replace("version = \"1.3.17\"", "version = \"1.3.17\" x"),
1832 "after the value",
1833 ),
1834 (
1835 GOOD.replace("format = 1", "format = 1\nformat = 1"),
1836 "repeated",
1837 ),
1838 (
1839 GOOD.replace("format = 1", "format = 01"),
1840 "bundle.toml:2: expected a string",
1841 ),
1842 (
1843 GOOD.replace("path = \"x.xsl\"\n", ""),
1844 "the `path` key is missing",
1845 ),
1846 (
1847 GOOD.split("[[stylesheet]]").next().unwrap().to_owned(),
1848 "no [[stylesheet]]",
1849 ),
1850 (String::new(), "the `format` key is missing"),
1851 (
1852 "format\n".to_owned(),
1853 "bundle.toml:1: expected `key = value`",
1854 ),
1855 ];
1856 for (text, expected) in cases {
1857 let message = error(&text);
1858 assert!(
1859 message.contains(expected),
1860 "{expected:?} not in {message:?}"
1861 );
1862 }
1863 }
1864}