1pub mod context;
11pub mod pack;
12
13pub use context::{ValidationContext, ValidationContextBuilder};
14pub use pack::{ProfileRule, ProfileRulePack};
15
16use crate::{
17 EdifactError, FindingKind, Segment, Span, ValidationIssue, ValidationReport, ValidationSeverity,
18};
19use std::any::Any;
20
21#[derive(Clone, Copy)]
36pub struct ValidationRuleContext<'a> {
37 pub(super) metadata: Option<&'a (dyn Any + Send + Sync)>,
38 pub message_ref: Option<&'a str>,
40 pub message_type: Option<&'a str>,
47}
48
49impl<'a> ValidationRuleContext<'a> {
50 pub fn empty() -> Self {
52 Self {
53 metadata: None,
54 message_ref: None,
55 message_type: None,
56 }
57 }
58
59 pub fn new<T: Any + Send + Sync>(value: &'a T) -> Self {
61 Self {
62 metadata: Some(value as &(dyn Any + Send + Sync)),
63 message_ref: None,
64 message_type: None,
65 }
66 }
67
68 pub fn with_message_ref(mut self, msg_ref: &'a str) -> Self {
70 self.message_ref = Some(msg_ref);
71 self
72 }
73
74 pub fn with_message_type(mut self, message_type: &'a str) -> Self {
76 self.message_type = Some(message_type);
77 self
78 }
79
80 pub fn metadata<T: Any + Send + Sync>(&self) -> Option<&T> {
83 self.metadata?.downcast_ref::<T>()
84 }
85
86 pub fn has_metadata(&self) -> bool {
88 self.metadata.is_some()
89 }
90}
91
92impl std::fmt::Debug for ValidationRuleContext<'_> {
93 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94 f.debug_struct("ValidationRuleContext")
95 .field("has_metadata", &self.metadata.is_some())
96 .field("message_ref", &self.message_ref)
97 .field("message_type", &self.message_type)
98 .finish()
99 }
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
122#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
123#[non_exhaustive]
124pub enum ValidationLayer {
125 Envelope,
127 Syntax,
129 Charset,
131 Structure,
133 CodeList,
135 Profile,
137}
138
139impl ValidationLayer {
140 #[must_use]
142 pub fn as_str(self) -> &'static str {
143 match self {
144 Self::Envelope => "envelope",
145 Self::Syntax => "syntax",
146 Self::Charset => "charset",
147 Self::Structure => "structure",
148 Self::CodeList => "code_list",
149 Self::Profile => "profile",
150 }
151 }
152
153 pub(crate) fn is_envelope_class(self) -> bool {
156 matches!(self, Self::Envelope | Self::Syntax | Self::Charset)
157 }
158}
159
160impl std::fmt::Display for ValidationLayer {
161 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162 f.write_str(self.as_str())
163 }
164}
165
166pub trait Validator: Send + Sync {
171 fn validate_batch(
173 &self,
174 segments: &[Segment<'_>],
175 report: &mut ValidationReport,
176 context: &ValidationRuleContext<'_>,
177 );
178
179 fn validate_group_batch(
190 &self,
191 _root: &crate::group::SegmentGroupIndexed<'_>,
192 _all_segments: &[Segment<'_>],
193 _report: &mut ValidationReport,
194 _context: &ValidationRuleContext<'_>,
195 ) {
196 }
197
198 fn has_group_rules(&self) -> bool {
205 false
206 }
207
208 fn set_message_type(&mut self, _message_type: Option<&str>) {}
210
211 fn fork(&self) -> Option<Box<dyn Validator + Send + Sync>> {
223 None
224 }
225}
226
227pub fn validate_each<F>(segments: &[Segment<'_>], report: &mut ValidationReport, mut f: F)
230where
231 F: FnMut(&Segment<'_>) -> Result<(), EdifactError>,
232{
233 for segment in segments {
234 if let Err(err) = f(segment) {
235 report_error(report, err);
236 }
237 }
238}
239
240pub(crate) struct MessagePositions {
246 messages: Vec<(usize, usize)>,
248}
249
250impl MessagePositions {
251 pub(crate) fn new(segments: &[Segment<'_>]) -> Self {
252 let mut messages = Vec::new();
253 let mut open: Option<usize> = None;
254 for (index, segment) in segments.iter().enumerate() {
255 match segment.tag() {
256 "UNH" => {
257 if let Some(start) = open.replace(index) {
258 messages.push((start, index - 1));
259 }
260 }
261 "UNT" => {
262 if let Some(start) = open.take() {
263 messages.push((start, index));
264 }
265 }
266 _ => {}
267 }
268 }
269 if let Some(start) = open
270 && let Some(last) = segments.len().checked_sub(1)
271 {
272 messages.push((start, last));
273 }
274 Self { messages }
275 }
276
277 pub(crate) fn position(&self, index: usize) -> Option<usize> {
279 let at = self.messages.partition_point(|&(start, _)| start <= index);
280 let &(start, end) = self.messages.get(at.checked_sub(1)?)?;
281 (index <= end).then(|| index - start + 1)
282 }
283}
284
285pub(crate) fn push_issue(report: &mut ValidationReport, issue: ValidationIssue) {
287 match issue.severity {
288 ValidationSeverity::Critical | ValidationSeverity::Error => report.add_error(issue),
289 ValidationSeverity::Warning => report.add_warning(issue),
290 ValidationSeverity::Info => report.add_info(issue),
291 }
292}
293
294pub(crate) fn report_error(report: &mut ValidationReport, err: EdifactError) {
303 push_issue(report, issue_from_error(err));
304}
305
306pub(crate) fn report_error_at(
309 report: &mut ValidationReport,
310 err: EdifactError,
311 layer: ValidationLayer,
312 position: Option<usize>,
313) {
314 let mut issue = issue_from_error(err).with_layer(layer);
315 if let Some(position) = position {
316 issue = issue.with_segment_position(position);
317 }
318 push_issue(report, issue);
319}
320
321pub struct EnvelopeValidator;
329
330impl Validator for EnvelopeValidator {
331 fn validate_batch(
332 &self,
333 segments: &[Segment<'_>],
334 report: &mut ValidationReport,
335 _ctx: &ValidationRuleContext<'_>,
336 ) {
337 let (result, located) = crate::envelope::validate_envelope_located(segments);
341 let positions = MessagePositions::new(segments);
342 for (e, index) in result.errors.into_iter().zip(located) {
343 let mut issue = issue_from_error(e).with_layer(ValidationLayer::Envelope);
344 let index = index.or_else(|| {
345 let span = issue.span()?;
346 let at = segments
347 .partition_point(|s| s.span.start <= span.start)
348 .checked_sub(1)?;
349 (span.end <= segments[at].span.end).then_some(at)
350 });
351 if let Some(position) = index.and_then(|i| positions.position(i)) {
352 issue = issue.with_segment_position(position);
353 }
354 push_issue(report, issue);
355 }
356 }
357
358 fn fork(&self) -> Option<Box<dyn Validator + Send + Sync>> {
359 Some(Box::new(EnvelopeValidator))
360 }
361}
362
363pub struct SyntaxValidator;
403
404impl Validator for SyntaxValidator {
405 fn validate_batch(
406 &self,
407 segments: &[Segment<'_>],
408 report: &mut ValidationReport,
409 _context: &ValidationRuleContext<'_>,
410 ) {
411 let positions = MessagePositions::new(segments);
412 for (index, segment) in segments.iter().enumerate() {
413 let position = positions.position(index);
414 let report_syntax = |report: &mut ValidationReport, err: EdifactError| {
415 report_error_at(report, err, ValidationLayer::Syntax, position);
416 };
417 if segment.elements.is_empty() {
423 report_syntax(
424 report,
425 EdifactError::SegmentWithoutDataElements {
426 tag: segment.tag().to_owned(),
427 span: segment.span,
428 },
429 );
430 }
431
432 if segment
436 .elements
437 .last()
438 .is_some_and(|element| element.repetitions().flatten().all(|(v, _)| v.is_empty()))
439 && segment.elements.len() > 1
440 {
441 report_syntax(
442 report,
443 EdifactError::TrailingSeparator {
444 tag: segment.tag().to_owned(),
445 element_index: None,
446 span: segment.span,
447 },
448 );
449 }
450
451 for (element_index, element) in segment.elements.iter().enumerate() {
452 if element.components.len() > 1
456 && element.components.last().is_some_and(|(v, _)| v.is_empty())
457 {
458 report_syntax(
459 report,
460 EdifactError::TrailingSeparator {
461 tag: segment.tag().to_owned(),
462 element_index: Some(element_index),
463 span: element.span,
464 },
465 );
466 }
467
468 for components in element.repetitions() {
469 for (component_index, (value, span)) in components.iter().enumerate() {
470 if !value.is_empty() && value.bytes().all(|b| b == b' ') {
474 report_syntax(
475 report,
476 EdifactError::BlankDataElementValue {
477 tag: segment.tag().to_owned(),
478 element_index,
479 component_index,
480 span: *span,
481 },
482 );
483 }
484 }
485 }
486 }
487 }
488 }
489
490 fn fork(&self) -> Option<Box<dyn Validator + Send + Sync>> {
491 Some(Box::new(SyntaxValidator))
492 }
493}
494
495pub struct CharsetValidator {
533 charset: Option<crate::Charset>,
535}
536
537impl CharsetValidator {
538 #[must_use]
543 pub fn from_envelope() -> Self {
544 Self { charset: None }
545 }
546
547 #[must_use]
552 pub fn with_charset(charset: crate::Charset) -> Self {
553 Self {
554 charset: Some(charset),
555 }
556 }
557
558 fn resolve(&self, segments: &[Segment<'_>]) -> Option<crate::Charset> {
560 if self.charset.is_some() {
561 return self.charset;
562 }
563 let identifier = segments
564 .iter()
565 .find(|s| s.tag == "UNB")
566 .and_then(|unb| unb.component_str(0, 0))?;
567 crate::Charset::from_syntax_identifier(identifier).ok()
571 }
572}
573
574impl Validator for CharsetValidator {
575 fn validate_batch(
576 &self,
577 segments: &[Segment<'_>],
578 report: &mut ValidationReport,
579 _context: &ValidationRuleContext<'_>,
580 ) {
581 let Some(charset) = self.resolve(segments) else {
582 return;
583 };
584 if charset == crate::Charset::UnoY {
585 return; }
587 let positions = MessagePositions::new(segments);
588 for (index, segment) in segments.iter().enumerate() {
589 let position = positions.position(index);
590 for (element_index, element) in segment.elements.iter().enumerate() {
591 for components in element.repetitions() {
592 for (component_index, (value, span)) in components.iter().enumerate() {
593 let Some((offset, character)) = charset.first_violation(value) else {
594 continue;
595 };
596 let mut issue = ValidationIssue::new(
597 ValidationSeverity::Error,
598 format!(
599 "character {character:?} is not in the {charset} character \
600 repertoire declared by UNB S001",
601 ),
602 )
603 .with_error_code(
604 EdifactError::CharacterNotInRepertoire {
605 charset: charset.syntax_identifier(),
606 character,
607 offset,
608 }
609 .stable_code(),
610 )
611 .with_segment(segment.tag())
612 .with_span(*span)
613 .with_element_index(element_index)
614 .with_component_index(component_index)
615 .with_layer(ValidationLayer::Charset)
616 .with_kind(FindingKind::Charset)
617 .with_suggestion(
618 "Transliterate the value, or declare a wider repertoire in UNB S001 \
619 (UNOC for Latin-1, UNOY for UTF-8)",
620 );
621 if let Some(position) = position {
622 issue = issue.with_segment_position(position);
623 }
624 report.add_error(issue);
625 }
626 }
627 }
628 }
629 }
630
631 fn fork(&self) -> Option<Box<dyn Validator + Send + Sync>> {
632 Some(Box::new(Self {
633 charset: self.charset,
634 }))
635 }
636}
637
638#[derive(Debug, Clone)]
674pub struct PlacementValidator {
675 schema: std::sync::Arc<crate::group::GroupSchema>,
676}
677
678impl PlacementValidator {
679 #[must_use]
681 pub fn new(schema: std::sync::Arc<crate::group::GroupSchema>) -> Self {
682 Self { schema }
683 }
684
685 #[must_use]
687 pub fn schema(&self) -> &crate::group::GroupSchema {
688 &self.schema
689 }
690}
691
692impl Validator for PlacementValidator {
693 fn validate_batch(
694 &self,
695 segments: &[Segment<'_>],
696 report: &mut ValidationReport,
697 _context: &ValidationRuleContext<'_>,
698 ) {
699 for issue in self.schema.resolve(segments).findings(segments) {
700 push_issue(report, issue);
701 }
702 }
703
704 fn fork(&self) -> Option<Box<dyn Validator + Send + Sync>> {
705 Some(Box::new(self.clone()))
706 }
707}
708
709pub(crate) fn issue_from_error(err: EdifactError) -> ValidationIssue {
710 let code = err.stable_code();
711 let mut issue = ValidationIssue::new(crate::report::severity_for_error(&err), err.to_string())
712 .with_error_code(code)
713 .with_kind(FindingKind::for_error(&err));
714 let default_hint = err.recovery_hint();
715
716 match err {
717 EdifactError::InvalidSegmentForMessage { tag, span, .. } => {
718 issue = issue.with_segment(tag).with_span(span);
719 }
720 EdifactError::InvalidElementCount { tag, span, .. } => {
721 issue = issue.with_segment(tag).with_span(span);
722 }
723 EdifactError::InvalidComponentCount {
724 tag,
725 element_index,
726 span,
727 ..
728 } => {
729 issue = issue
730 .with_segment(tag)
731 .with_element_index(element_index)
732 .with_span(span);
733 }
734 EdifactError::InvalidCodeValue {
735 tag,
736 element_index,
737 span,
738 suggestion,
739 ..
740 } => {
741 issue = issue
742 .with_segment(tag)
743 .with_element_index(element_index)
744 .with_span(span);
745 if let Some(s) = suggestion {
746 issue = issue.with_suggestion(s);
747 }
748 }
749 EdifactError::MissingSegment { tag, .. } => {
750 issue = issue.with_segment(tag);
751 }
752 EdifactError::SegmentNotPlaced { tag, span, .. }
753 | EdifactError::TooManySegmentOccurrences { tag, span, .. } => {
754 issue = issue.with_segment(tag).with_span(span);
755 }
756 EdifactError::TooManyGroupOccurrences { group, span, .. } => {
757 issue = issue.with_segment_group(group).with_span(span);
758 }
759 EdifactError::QualifierMismatch { tag, span, .. } => {
762 issue = issue.with_segment(tag).with_span(span);
763 }
764 EdifactError::ConditionalRequirementNotMet {
765 tag,
766 element_index,
767 span,
768 ..
769 } => {
770 issue = issue
771 .with_segment(tag)
772 .with_element_index(element_index)
773 .with_span(span);
774 }
775 EdifactError::DuplicateReference { tag, span, .. }
776 | EdifactError::PackageNotSupported { tag, span }
777 | EdifactError::SegmentWithoutDataElements { tag, span } => {
778 issue = issue.with_segment(tag).with_span(span);
779 }
780 EdifactError::EmptyMessage { span, .. } => {
781 issue = issue.with_segment("UNH").with_span(span);
782 }
783 EdifactError::InteractiveSegmentNotSupported { tag, span }
784 | EdifactError::SecuritySegmentNotSupported { tag, span }
785 | EdifactError::ReservedServiceSegmentTag { tag, span }
786 | EdifactError::DataAfterInterchangeTrailer { tag, span } => {
787 issue = issue.with_segment(tag).with_span(span);
788 }
789 EdifactError::MessageCountMismatch { span, .. } => {
790 issue = issue.with_segment("UNZ").with_span(span);
791 }
792 EdifactError::GroupCountMismatch { span, .. } => {
793 issue = issue.with_segment("UNE").with_span(span);
794 }
795 EdifactError::EmptyGroup { span, .. } => {
796 issue = issue.with_segment("UNG").with_span(span);
797 }
798 EdifactError::UnsupportedSyntaxVersion { span, .. } => {
799 issue = issue
800 .with_segment("UNB")
801 .with_span(span)
802 .with_element_index(0)
803 .with_component_index(1);
804 }
805 EdifactError::GroupsAndMessagesMixed { span } => {
806 issue = issue.with_segment("UNH").with_span(span);
807 }
808 EdifactError::TrailingSeparator {
809 tag,
810 element_index,
811 span,
812 } => {
813 issue = issue.with_segment(tag).with_span(span);
814 if let Some(index) = element_index {
815 issue = issue.with_element_index(index);
816 }
817 }
818 EdifactError::SegmentCountMismatch {
821 span, message_ref, ..
822 } => {
823 issue = issue
824 .with_segment("UNT")
825 .with_span(span)
826 .with_message_ref(message_ref);
827 }
828 EdifactError::TooManyRepetitions {
829 tag,
830 element_index,
831 span,
832 ..
833 } => {
834 issue = issue
835 .with_segment(tag)
836 .with_span(span)
837 .with_element_index(element_index);
838 }
839 EdifactError::InvalidCharacterType {
840 tag,
841 element_index,
842 component_index,
843 span,
844 ..
845 }
846 | EdifactError::DataElementTooLong {
847 tag,
848 element_index,
849 component_index,
850 span,
851 ..
852 }
853 | EdifactError::DataElementTooShort {
854 tag,
855 element_index,
856 component_index,
857 span,
858 ..
859 }
860 | EdifactError::InsignificantCharacters {
861 tag,
862 element_index,
863 component_index,
864 span,
865 ..
866 }
867 | EdifactError::BlankDataElementValue {
868 tag,
869 element_index,
870 component_index,
871 span,
872 }
873 | EdifactError::InvalidDateTime {
874 tag,
875 element_index,
876 component_index,
877 span,
878 ..
879 } => {
880 issue = issue
881 .with_segment(tag)
882 .with_span(span)
883 .with_element_index(element_index)
884 .with_component_index(component_index);
885 }
886 EdifactError::MissingRequiredElement { tag, element_index } => {
887 issue = issue.with_segment(tag).with_element_index(element_index);
888 }
889 EdifactError::MissingRequiredComponent {
890 tag,
891 element_index,
892 component_index,
893 } => {
894 issue = issue
895 .with_segment(tag)
896 .with_element_index(element_index)
897 .with_component_index(component_index);
898 }
899 EdifactError::InvalidReleaseSequence { offset }
902 | EdifactError::InvalidDelimiter { offset, .. }
903 | EdifactError::InvalidText { offset }
904 | EdifactError::UnexpectedEof { offset }
905 | EdifactError::UnexpectedDataToken { offset }
906 | EdifactError::SegmentTooLong { offset, .. }
907 | EdifactError::LimitExceeded { offset, .. } => {
908 issue = issue.with_span(Span::new(offset, offset));
909 }
910 _ => {}
911 }
912
913 if issue.suggestion.is_none()
914 && let Some(hint) = default_hint
915 {
916 issue = issue.with_suggestion(hint);
917 }
918
919 issue
920}
921
922#[cfg(test)]
923mod tests {
924 use super::*;
925 use crate::model::Element;
926
927 fn demo_orders_profile_pack() -> ProfileRulePack {
928 ProfileRulePack::new("ORDERS-DEMO")
929 .for_message_type("ORDERS")
930 .with_rule_fn(|segments, issues| {
931 issues.extend((|| -> Option<ValidationIssue> {
932 let bgm = segments.iter().find(|segment| segment.tag == "BGM")?;
933 let document_code = bgm.get_element(0)?.get_component(0)?;
934 (document_code == "220").then(|| {
935 ValidationIssue::new(
936 ValidationSeverity::Error,
937 "profile rule DEMO-P001 violated: BGM document code 220 is rejected in this demo pack",
938 )
939 .with_rule_id("DEMO-P001")
940 .with_segment("BGM")
941 .with_element_index(0)
942 .with_suggestion("Use a different BGM document code in this demo pack")
943 })
944 })());
945 })
946 .with_rule_fn(|segments, issues| {
947 issues.extend((|| -> Option<ValidationIssue> {
948 let bgm = segments.iter().find(|segment| segment.tag == "BGM")?;
949 let reference = bgm.get_element(1)?.get_component(0)?;
950 (reference == "PO123").then(|| {
951 ValidationIssue::new(
952 ValidationSeverity::Warning,
953 "profile rule DEMO-P002 warning: purchase-order reference PO123 is reserved in this demo pack",
954 )
955 .with_rule_id("DEMO-P002")
956 .with_segment("BGM")
957 .with_element_index(1)
958 .with_suggestion("Use a non-reserved reference in this demo pack")
959 })
960 })());
961 })
962 }
963
964 fn positions_of(input: &[u8]) -> Vec<Option<usize>> {
965 let segments: Vec<_> = crate::from_bytes(input)
966 .collect::<Result<_, _>>()
967 .expect("valid input");
968 let positions = MessagePositions::new(&segments);
969 (0..segments.len()).map(|i| positions.position(i)).collect()
970 }
971
972 #[test]
973 fn message_positions_count_from_each_unh() {
974 assert_eq!(
975 positions_of(b"UNH+1+X:D:96A:UN'BGM+1'UNT+3+1'"),
976 [Some(1), Some(2), Some(3)]
977 );
978 assert_eq!(
979 positions_of(
980 b"UNB+UNOC:3+S+R+260101:0900+1'UNH+1+X:D:96A:UN'BGM+1'UNT+3+1'\
981 UNH+2+X:D:96A:UN'BGM+2'UNT+3+2'UNZ+2+1'"
982 ),
983 [
984 None,
985 Some(1),
986 Some(2),
987 Some(3),
988 Some(1),
989 Some(2),
990 Some(3),
991 None
992 ]
993 );
994 assert_eq!(
996 positions_of(b"UNH+1+X:D:96A:UN'BGM+1'UNH+2+X:D:96A:UN'BGM+2'"),
997 [Some(1), Some(2), Some(1), Some(2)]
998 );
999 assert_eq!(positions_of(b"BGM+1'DTM+1'"), [None, None]);
1000 assert_eq!(positions_of(b""), []);
1001 }
1002
1003 struct RejectBgm;
1004
1005 struct WarnBgm;
1006
1007 impl Validator for RejectBgm {
1008 fn validate_batch(
1009 &self,
1010 segments: &[Segment<'_>],
1011 report: &mut ValidationReport,
1012 _context: &ValidationRuleContext<'_>,
1013 ) {
1014 validate_each(segments, report, |segment| {
1015 if segment.tag == "BGM" {
1016 return Err(EdifactError::InvalidSegmentForMessage {
1017 tag: "BGM".to_owned(),
1018 message_type: "TEST".to_owned(),
1019 span: segment.tag_span,
1020 });
1021 }
1022 Ok(())
1023 });
1024 }
1025 }
1026
1027 impl Validator for WarnBgm {
1028 fn validate_batch(
1029 &self,
1030 segments: &[Segment<'_>],
1031 report: &mut ValidationReport,
1032 _context: &ValidationRuleContext<'_>,
1033 ) {
1034 validate_each(segments, report, |segment| {
1035 if segment.tag == "BGM" {
1036 return Err(EdifactError::InvalidCodeValue {
1037 tag: "BGM".to_owned(),
1038 element_index: 0,
1039 value: "XXX".to_owned(),
1040 code_list: "1001".to_owned(),
1041 span: segment.span,
1042 suggestion: None,
1043 });
1044 }
1045 Ok(())
1046 });
1047 }
1048 }
1049
1050 fn test_segment(tag: &'static str) -> Segment<'static> {
1051 Segment::new(tag, vec![Element::of(&["x"])])
1052 }
1053
1054 #[test]
1055 fn lenient_collects_issues() {
1056 let segments = vec![test_segment("UNH"), test_segment("BGM")];
1057 let mut report = ValidationReport::default();
1058 RejectBgm.validate_batch(&segments, &mut report, &ValidationRuleContext::empty());
1059 assert!(report.has_errors());
1060 assert_eq!(report.errors().len(), 1);
1061 }
1062
1063 #[test]
1064 fn strict_fails_on_errors() {
1065 let segments = vec![test_segment("BGM")];
1066 let mut report = ValidationReport::default();
1067 RejectBgm.validate_batch(&segments, &mut report, &ValidationRuleContext::empty());
1068 assert!(report.has_errors());
1069 assert_eq!(report.errors().len(), 1);
1070 }
1071
1072 #[test]
1073 fn context_builder_respects_layer_toggles() {
1074 let segments = vec![test_segment("BGM")];
1075 let ctx = ValidationContext::builder()
1076 .structure(false)
1077 .with_validator(ValidationLayer::Structure, RejectBgm)
1078 .with_validator(ValidationLayer::CodeList, WarnBgm)
1079 .build();
1080
1081 let report = ctx.validate(&segments);
1082 assert!(!report.has_errors());
1083 assert_eq!(report.warnings().len(), 1);
1084 }
1085
1086 #[test]
1087 fn context_strict_fails_when_structure_enabled() {
1088 let segments = vec![test_segment("BGM")];
1089 let ctx = ValidationContext::builder()
1090 .with_message_type("ORDERS")
1091 .with_validator(ValidationLayer::Structure, RejectBgm)
1092 .build();
1093
1094 assert_eq!(ctx.message_type(), Some("ORDERS"));
1095 let result = ctx.validate(&segments).result();
1096 assert!(result.is_err());
1097 assert!(result.unwrap_err().has_errors());
1098 }
1099
1100 #[test]
1101 fn report_error_applies_default_recovery_hint() {
1102 let mut report = ValidationReport::default();
1103 report_error(
1104 &mut report,
1105 EdifactError::InvalidReleaseSequence { offset: 9 },
1106 );
1107
1108 let issue = report
1109 .errors()
1110 .first()
1111 .expect("expected one issue in the report");
1112 let hint = issue
1113 .suggestion
1114 .as_deref()
1115 .expect("expected default hint to be set");
1116 assert!(hint.contains("Release character"));
1117 assert_eq!(issue.error_code(), Some("E019"));
1118 }
1119
1120 #[test]
1121 fn missing_required_component_maps_metadata_to_issue() {
1122 let mut report = ValidationReport::default();
1123 report_error(
1124 &mut report,
1125 EdifactError::MissingRequiredComponent {
1126 tag: "BGM".to_owned(),
1127 element_index: 2,
1128 component_index: 1,
1129 },
1130 );
1131
1132 let issue = report.errors().first().expect("expected one issue");
1133 assert_eq!(issue.error_code(), Some("E021"));
1134 assert_eq!(issue.segment_tag.as_deref(), Some("BGM"));
1135 assert_eq!(issue.element_index, Some(2));
1136 assert_eq!(issue.component_index, Some(1));
1137 }
1138
1139 #[test]
1140 fn profile_pack_lenient_collects_profile_rule_issues() {
1141 let input = b"UNH+1+ORDERS:D:96A:UN'BGM+220+PO123+9'UNT+3+1'";
1142 let segments = crate::from_bytes(input)
1143 .collect::<Result<Vec<_>, _>>()
1144 .expect("expected parse success");
1145
1146 let ctx = ValidationContext::builder()
1147 .with_profile_pack(demo_orders_profile_pack())
1148 .build();
1149
1150 let report = ctx.validate(&segments);
1151 assert!(report.has_errors());
1152 assert!(
1153 report
1154 .errors()
1155 .iter()
1156 .any(|issue| issue.rule_id.as_deref() == Some("DEMO-P001"))
1157 );
1158 assert!(
1159 report
1160 .warnings()
1161 .iter()
1162 .any(|issue| issue.rule_id.as_deref() == Some("DEMO-P002"))
1163 );
1164 }
1165
1166 #[test]
1167 fn profile_pack_strict_fails_when_profile_errors_exist() {
1168 let input = b"UNH+1+ORDERS:D:96A:UN'BGM+220+PO123+9'UNT+3+1'";
1169 let segments = crate::from_bytes(input)
1170 .collect::<Result<Vec<_>, _>>()
1171 .expect("expected parse success");
1172
1173 let ctx = ValidationContext::builder()
1174 .with_profile_pack(demo_orders_profile_pack())
1175 .build();
1176 let result = ctx.validate(&segments).result();
1177 assert!(result.is_err());
1178 assert!(result.unwrap_err().has_errors());
1179 }
1180
1181 fn two_dtm_errors_rule() -> ProfileRulePack {
1185 ProfileRulePack::new("TEST-BAIL")
1186 .with_rule_fn(|segments, issues| {
1187 for seg in segments.iter().filter(|s| s.tag == "DTM") {
1189 issues.push(
1190 ValidationIssue::new(
1191 ValidationSeverity::Error,
1192 format!("DTM error at offset {}", seg.span.start),
1193 )
1194 .with_rule_id("BAIL-R1")
1195 .with_segment("DTM"),
1196 );
1197 }
1198 })
1199 .with_rule_fn(|segments, issues| {
1200 for seg in segments.iter().filter(|s| s.tag == "BGM") {
1202 issues.push(
1203 ValidationIssue::new(ValidationSeverity::Error, "BGM error")
1204 .with_rule_id("BAIL-R2")
1205 .with_segment(seg.tag()),
1206 );
1207 }
1208 })
1209 }
1210
1211 #[test]
1212 fn bail_on_first_error_fires_at_rule_invocation_granularity() {
1213 let input =
1216 b"UNH+1+ORDERS:D:96A:UN'BGM+220+9'DTM+137:20240101:102'DTM+163:20240201:102'UNT+5+1'";
1217 let segments = crate::from_bytes(input)
1218 .collect::<Result<Vec<_>, _>>()
1219 .expect("parse failed");
1220
1221 let pack_with_bail = two_dtm_errors_rule().with_bail_on_first_error(true);
1222 let ctx = ValidationContext::builder()
1223 .with_profile_pack(pack_with_bail)
1224 .build();
1225 let report = ctx.validate(&segments);
1226
1227 assert_eq!(
1230 report
1231 .errors()
1232 .iter()
1233 .filter(|i| i.rule_id.as_deref() == Some("BAIL-R1"))
1234 .count(),
1235 2,
1236 "both DTM errors from Rule A should be present"
1237 );
1238 assert_eq!(
1240 report
1241 .errors()
1242 .iter()
1243 .filter(|i| i.rule_id.as_deref() == Some("BAIL-R2"))
1244 .count(),
1245 0,
1246 "Rule B should have been skipped by bail"
1247 );
1248 }
1249
1250 #[test]
1251 fn bail_disabled_runs_all_rules() {
1252 let input = b"UNH+1+ORDERS:D:96A:UN'BGM+220+9'DTM+137:20240101:102'UNT+4+1'";
1253 let segments = crate::from_bytes(input)
1254 .collect::<Result<Vec<_>, _>>()
1255 .expect("parse failed");
1256
1257 let pack_no_bail = two_dtm_errors_rule(); let ctx = ValidationContext::builder()
1259 .with_profile_pack(pack_no_bail)
1260 .build();
1261 let report = ctx.validate(&segments);
1262
1263 assert_eq!(
1265 report
1266 .errors()
1267 .iter()
1268 .filter(|i| i.rule_id.as_deref() == Some("BAIL-R1"))
1269 .count(),
1270 1
1271 );
1272 assert_eq!(
1273 report
1274 .errors()
1275 .iter()
1276 .filter(|i| i.rule_id.as_deref() == Some("BAIL-R2"))
1277 .count(),
1278 1
1279 );
1280 }
1281
1282 #[test]
1285 fn message_ref_is_visible_inside_rule_closure() {
1286 let input = b"UNH+MSG001+ORDERS:D:96A:UN'BGM+220+9'UNT+3+1'";
1287 let segments = crate::from_bytes(input)
1288 .collect::<Result<Vec<_>, _>>()
1289 .expect("parse failed");
1290
1291 let pack =
1292 ProfileRulePack::new("MSG-REF-TEST").with_contextual_rule_fn(|_segs, ctx, issues| {
1293 if let Some(mref) = ctx.message_ref {
1294 issues.push(
1295 ValidationIssue::new(
1296 ValidationSeverity::Info,
1297 format!("validating message {mref}"),
1298 )
1299 .with_rule_id("CTX-REF"),
1300 );
1301 }
1302 });
1303
1304 let ctx = ValidationContext::builder()
1305 .with_profile_pack(pack)
1306 .with_message_ref("MSG001")
1307 .build();
1308
1309 let report = ctx.validate(&segments);
1310 let info = report
1311 .infos()
1312 .iter()
1313 .find(|i| i.rule_id.as_deref() == Some("CTX-REF"))
1314 .expect("expected info issue from CTX-REF rule");
1315 assert!(info.message.contains("MSG001"));
1316 assert_eq!(info.message_ref.as_deref(), Some("MSG001"));
1318 }
1319}