Skip to main content

edifact/validator/
mod.rs

1//! Validation pipeline for structural and semantic EDIFACT checks.
2//!
3//! The validation module is split into three sub-modules:
4//!
5//! - [`pack`] — [`ProfileRule`], [`ProfileRulePack`], and rule construction helpers.
6//! - [`context`] — [`ValidationContext`], [`ValidationContextBuilder`].
7//! - This module (`mod.rs`) — [`Validator`] trait, [`ValidationRuleContext`],
8//!   [`ValidationLayer`], [`EnvelopeValidator`], and helper functions.
9
10pub 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/// Typed context injected into profile rule closures at validation time.
22///
23/// Rules access per-call metadata via [`ValidationRuleContext::metadata`] and
24/// the message reference (UNH element 0) via [`ValidationRuleContext::message_ref`].
25///
26/// # Example
27///
28/// ```rust,ignore
29/// let pack = ProfileRulePack::new("PROFILE-4711")
30///     .with_contextual_rule_fn(|segs, ctx, issues| {
31///         let Some(process_id) = ctx.metadata::<ProcessId>() else { return };
32///         let msg_ref = ctx.message_ref.unwrap_or("<unknown>");
33///     });
34/// ```
35#[derive(Clone, Copy)]
36pub struct ValidationRuleContext<'a> {
37    pub(super) metadata: Option<&'a (dyn Any + Send + Sync)>,
38    /// Message reference (`UNH` element 0) for this validation call.
39    pub message_ref: Option<&'a str>,
40    /// EDIFACT message type extracted from `UNH` element 1 component 0.
41    ///
42    /// Pre-extracted once by [`ValidationContext`] before dispatching to validators,
43    /// so each [`ProfileRulePack`] can skip its own `UNH` scan.
44    /// `None` when the message type could not be determined (no `UNH`, or when calling
45    /// [`ProfileRulePack::validate_batch`] directly without a `ValidationContext`).
46    pub message_type: Option<&'a str>,
47}
48
49impl<'a> ValidationRuleContext<'a> {
50    /// Construct a context with no metadata and no message reference.
51    pub fn empty() -> Self {
52        Self {
53            metadata: None,
54            message_ref: None,
55            message_type: None,
56        }
57    }
58
59    /// Construct a context holding a typed metadata reference.
60    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    /// Attach a message reference to this context (builder-style).
69    pub fn with_message_ref(mut self, msg_ref: &'a str) -> Self {
70        self.message_ref = Some(msg_ref);
71        self
72    }
73
74    /// Attach a pre-extracted message type to this context (builder-style).
75    pub fn with_message_type(mut self, message_type: &'a str) -> Self {
76        self.message_type = Some(message_type);
77        self
78    }
79
80    /// Downcast the metadata to `T`.  Returns `None` if no metadata was
81    /// injected or if the concrete type does not match `T`.
82    pub fn metadata<T: Any + Send + Sync>(&self) -> Option<&T> {
83        self.metadata?.downcast_ref::<T>()
84    }
85
86    /// Return `true` if metadata was provided.
87    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/// The validation stage a validator is registered under, and that an issue
103/// was produced by ([`ValidationIssue::layer`]).
104///
105/// | Variant | [`as_str`](Self::as_str) | Stage | Switched by |
106/// |---|---|---|---|
107/// | `Envelope` | `envelope` | `UNB`/`UNG`/`UNH`/`UNT`/`UNE`/`UNZ` structure, counts and references | [`envelope`][ValidationContextBuilder::envelope] |
108/// | `Syntax` | `syntax` | directory-independent ISO 9735-1 rules ([`SyntaxValidator`]) | [`envelope`][ValidationContextBuilder::envelope] |
109/// | `Charset` | `charset` | values against the declared character repertoire ([`CharsetValidator`]) | [`envelope`][ValidationContextBuilder::envelope] |
110/// | `Structure` | `structure` | directory structure: segment presence, order, arity | [`structure`][ValidationContextBuilder::structure] |
111/// | `CodeList` | `code_list` | directory code lists | [`code_list`][ValidationContextBuilder::code_list] |
112/// | `Profile` | `profile` | downstream profile packs | [`profile`][ValidationContextBuilder::profile] |
113///
114/// `Syntax` and `Charset` are interchange-level stages like `Envelope`: they
115/// share its switch and, like it, see the whole slice including `UNB`/`UNZ`.
116/// They exist as separate variants so an issue says which stage found it — a
117/// blank value or a `€` in a `UNOC` interchange is not an envelope fault.
118///
119/// Marked `#[non_exhaustive]`. With the `serde` feature variants serialise by
120/// name (`"CodeList"`), the casing [`ValidationSeverity`] uses.
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
122#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
123#[non_exhaustive]
124pub enum ValidationLayer {
125    /// Interchange / message envelope checks (`UNB`/`UNH`/`UNT`/`UNZ` counts).
126    Envelope,
127    /// Directory-independent ISO 9735-1 syntax checks.
128    Syntax,
129    /// Character repertoire checks.
130    Charset,
131    /// Directory structure checks (segment presence/order/arity).
132    Structure,
133    /// Directory code-list checks.
134    CodeList,
135    /// Downstream profile-pack checks.
136    Profile,
137}
138
139impl ValidationLayer {
140    /// A stable lowercase identifier, e.g. `"code_list"`.
141    #[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    /// Whether this layer is an interchange-level stage: switched by the
154    /// envelope switch and run over the unfiltered slice.
155    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
166/// Pluggable validator for parsed EDIFACT segments.
167///
168/// The primary contract is [`validate_batch`](Validator::validate_batch), which processes an
169/// entire segment sequence and appends issues to a [`ValidationReport`].
170pub trait Validator: Send + Sync {
171    /// Validate a full segment set and append issues to `report`.
172    fn validate_batch(
173        &self,
174        segments: &[Segment<'_>],
175        report: &mut ValidationReport,
176        context: &ValidationRuleContext<'_>,
177    );
178
179    /// Validate a segment-group tree and append issues to `report`.
180    ///
181    /// Called by [`ValidationContext::validate_grouped`] in addition to
182    /// [`validate_batch`](Validator::validate_batch).  Validators that only perform
183    /// flat segment checks (e.g. [`EnvelopeValidator`]) can leave this as the
184    /// default no-op; only validators with group-scoped rules (such as a
185    /// [`ProfileRulePack`] with at least one group rule) need to override it.
186    ///
187    /// The default implementation is a no-op, so validators without group
188    /// rules need not implement it.
189    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    /// Returns `true` if this validator has any group-scoped rules.
199    ///
200    /// Used by [`crate::ValidationContext`] to short-circuit the
201    /// group-tree walk when no validator in the context has group rules.
202    ///
203    /// The default implementation returns `false`.
204    fn has_group_rules(&self) -> bool {
205        false
206    }
207
208    /// Configure message-type metadata for validators that support explicit scoping.
209    fn set_message_type(&mut self, _message_type: Option<&str>) {}
210
211    /// Create a `Box<dyn Validator>` clone of this validator for context forking.
212    ///
213    /// Return `Some(boxed_clone)` for validators that support cheap forking
214    /// (e.g. those backed by `Arc` data, like [`ProfileRulePack`]).
215    ///
216    /// Return `None` for validators that cannot be forked (e.g. stateful validators
217    /// without `Clone`).  Returning `None` causes the validator to be silently
218    /// **excluded** from forked contexts — forking is used by
219    /// [`crate::ValidationContext::validate_grouped`] to validate
220    /// each group in isolation, so omitting a non-forkable validator from the
221    /// forked context is safer than panicking.
222    fn fork(&self) -> Option<Box<dyn Validator + Send + Sync>> {
223        None
224    }
225}
226
227/// Helper for per-segment validators: iterates `segments`, calls `f` for each one,
228/// and converts any `Err` into report entries.
229pub 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
240/// One-based segment positions within each message (DE 0096, `UNH` = 1).
241///
242/// A message runs from its `UNH` to its `UNT`; one without `UNT` ends before
243/// the next `UNH` or at the end of the batch. Segments outside every message
244/// have no position.
245pub(crate) struct MessagePositions {
246    /// `(start, end)` index range of each message, `end` inclusive, ascending.
247    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    /// The one-based position of `segments[index]` within its message.
278    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
285/// Add `issue` to the bucket its severity belongs in.
286pub(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
294/// Convert a low-level validation error to a user-facing issue and append it.
295///
296/// Severity comes from [`report::severity_for_error`][crate::report::severity_for_error],
297/// which is also what the `miette` rendering uses.
298///
299/// The issue's [`kind`][ValidationIssue::kind] is
300/// [`FindingKind::for_error`]; layer and segment position are left for the
301/// caller, which knows them.
302pub(crate) fn report_error(report: &mut ValidationReport, err: EdifactError) {
303    push_issue(report, issue_from_error(err));
304}
305
306/// [`report_error`] with the producing layer and, when known, the segment's
307/// one-based message position.
308pub(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
321// ── EnvelopeValidator ─────────────────────────────────────────────────────────
322
323/// Built-in validator for the EDIFACT interchange envelope.
324///
325/// Reports every finding of [`validate_envelope_lenient`][crate::validate_envelope_lenient]:
326/// structure, control counts and references, and every service-segment value.  Registered by
327/// [`ValidationContextBuilder::with_envelope_validation`].
328pub 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        // The lenient path, so one report holds every envelope violation.
338        // A finding is placed at the segment its check ran on or, failing
339        // that, at the segment its span falls in.
340        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
363// ── SyntaxValidator ───────────────────────────────────────────────────────────
364
365/// Checks the ISO 9735-1 rules that hold for **every** interchange, whatever
366/// directory or profile it claims.
367///
368/// These are the rules a partner's translator enforces before it ever looks at a
369/// message type, and they need no directory to check:
370///
371/// | Rule | Source | Reported as |
372/// |---|---|---|
373/// | A segment carries at least one data element besides its tag | §7.5, §8.5 | `E046` |
374/// | No data element value is made only of spaces | §9.3 | `E045` (warning) |
375///
376/// Both are things a hand-rolled writer produces by accident: an `ABC'` where a
377/// conditional segment should have been dropped entirely, or a fixed-width field
378/// padded with spaces instead of suppressed. Neither trips a count check, and
379/// both are rejected downstream.
380///
381/// Registered by
382/// [`ValidationContextBuilder::with_syntax_validation`][crate::ValidationContextBuilder::with_syntax_validation].
383///
384/// # Example
385///
386/// ```
387/// use edifact::{from_bytes, ValidationContext};
388///
389/// // `FTX+` carries a value of nothing but spaces; `DTM` carries no data at all.
390/// let segments: Vec<_> = from_bytes(b"FTX+   'DTM'")
391///     .collect::<Result<_, _>>()?;
392///
393/// let report = ValidationContext::builder()
394///     .with_syntax_validation()
395///     .build()
396///     .validate(&segments);
397///
398/// assert_eq!(report.errors()[0].error_code(), Some("E046")); // DTM has no data element
399/// assert_eq!(report.warnings()[0].error_code(), Some("E045")); // FTX value is only spaces
400/// # Ok::<(), edifact::EdifactError>(())
401/// ```
402pub 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            // §7.5: "A segment shall contain at least one data element in
418            // addition to the segment tag."  A segment whose only element is
419            // empty still satisfies this — §8.4 spells out `ABC'` versus the
420            // mandatory-segment-with-no-data form — so the test is on presence,
421            // not on content.
422            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            // §8.7.1: separators that would follow omitted data elements at the
433            // end of a segment "shall also be omitted".  A segment ending in an
434            // empty element carries a separator that says nothing.
435            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                // §8.7.2 says the same for components at the end of a composite.
453                // Only a composite can have one: a single-component element that
454                // is empty is an omitted element, not a trailing separator.
455                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                        // §9.3: "A data element value containing only space(s)
471                        // shall not be allowed."  An empty value is a different
472                        // thing entirely — that is how EDIFACT spells "absent".
473                        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
495// ── CharsetValidator ──────────────────────────────────────────────────────────
496
497/// Checks that every value in the message is expressible in the interchange's
498/// declared character repertoire (`UNB` S001 DE 0001).
499///
500/// This is the check partners actually enforce and that costs real money when it
501/// is missed: a `UNOA` interchange carrying a lower-case letter, or a `UNOC` one
502/// carrying `€`, is rejected at the far end — but only after it has been sent.
503///
504/// Values are checked as **decoded text**, so run this after
505/// [`decode_interchange`][crate::decode_interchange] (or on natively-ASCII
506/// input). It answers "can this text be written back out in the repertoire the
507/// header promises?", which is the question that matters.
508///
509/// Registered by
510/// [`ValidationContextBuilder::with_charset_validation`][crate::ValidationContextBuilder::with_charset_validation].
511///
512/// # Example
513///
514/// ```
515/// use edifact::{from_bytes, ValidationContext};
516///
517/// // UNOA is upper-case only, but the party name is mixed case.
518/// let segments: Vec<_> = from_bytes(
519///     b"UNB+UNOA:3+S+R+200101:0900+1'NAD+BY+Acme Ltd'UNZ+0+1'",
520/// )
521/// .collect::<Result<_, _>>()?;
522///
523/// let report = ValidationContext::builder()
524///     .with_charset_validation()
525///     .build()
526///     .validate(&segments);
527///
528/// let issue = report.errors().iter().find(|i| i.error_code() == Some("E038")).unwrap();
529/// assert_eq!(issue.segment_tag.as_deref(), Some("NAD"));
530/// # Ok::<(), edifact::EdifactError>(())
531/// ```
532pub struct CharsetValidator {
533    /// Repertoire to check against; `None` reads it from the interchange's `UNB`.
534    charset: Option<crate::Charset>,
535}
536
537impl CharsetValidator {
538    /// Read the repertoire from the interchange's own `UNB` S001 DE 0001.
539    ///
540    /// A slice with no `UNB` — a single message window, say — is not checked,
541    /// because nothing declares what it should be checked against.
542    #[must_use]
543    pub fn from_envelope() -> Self {
544        Self { charset: None }
545    }
546
547    /// Check against a fixed repertoire, whatever the `UNB` says.
548    ///
549    /// Use this for message-level slices that carry no `UNB`, or to hold a
550    /// partner to a stricter repertoire than the one they declare.
551    #[must_use]
552    pub fn with_charset(charset: crate::Charset) -> Self {
553        Self {
554            charset: Some(charset),
555        }
556    }
557
558    /// The repertoire in force for `segments`.
559    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        // An unrecognised or unsupported identifier is the envelope validator's
568        // finding to report, not this one's — silently declining to check is the
569        // right move rather than raising a second, confusing error for it.
570        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; // Everything is permitted; nothing to check.
586        }
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// ── PlacementValidator ────────────────────────────────────────────────────────
639
640/// Resolves each message against a [`GroupSchema`][crate::group::GroupSchema]
641/// and reports what does not fit: unplaced segments, places and groups beyond
642/// their `max`, places and groups below their `min`.
643///
644/// The issues are exactly
645/// [`GroupResolution::findings`][crate::group::GroupResolution::findings], with
646/// layer [`Structure`](ValidationLayer::Structure) — register it under that
647/// layer. Give it the message (`UNH` to `UNT`) the schema describes: with the
648/// envelope layer on, the context already hides `UNB`/`UNZ`/`UNG`/`UNE`.
649///
650/// # Example
651///
652/// ```
653/// use std::sync::Arc;
654/// use edifact::group::{Entry, GroupSchema, SegmentPlace};
655/// use edifact::{FindingKind, PlacementValidator, ValidationContext, ValidationLayer};
656///
657/// let schema = GroupSchema::ordered(
658///     "MSG",
659///     ["UNH", "BGM", "UNT"].map(|t| Entry::Segment(SegmentPlace::new(t).with_min(1).with_max(1))),
660/// )?;
661/// let ctx = ValidationContext::builder()
662///     .with_validator(ValidationLayer::Structure, PlacementValidator::new(Arc::new(schema)))
663///     .build();
664///
665/// let segments: Vec<_> = edifact::from_bytes(b"UNH+1+X:D:11A:UN'DTM+137:1:102'BGM+220'UNT+4+1'")
666///     .collect::<Result<_, _>>()?;
667/// let report = ctx.validate(&segments);
668/// let issue = &report.errors()[0];
669/// assert_eq!(issue.kind(), Some(FindingKind::Placement));
670/// assert_eq!(issue.segment_position(), Some(2));
671/// # Ok::<(), edifact::EdifactError>(())
672/// ```
673#[derive(Debug, Clone)]
674pub struct PlacementValidator {
675    schema: std::sync::Arc<crate::group::GroupSchema>,
676}
677
678impl PlacementValidator {
679    /// A validator resolving against `schema`.
680    #[must_use]
681    pub fn new(schema: std::sync::Arc<crate::group::GroupSchema>) -> Self {
682        Self { schema }
683    }
684
685    /// The schema this validator resolves against.
686    #[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        // The error names the segment, not an element: an index invented here
760        // would become a wrong S011 on the CONTRL that reports it.
761        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        // The trailer is what got the count wrong, and carrying its span is what
819        // places the finding on that message rather than on the interchange.
820        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        // Lexical faults are a point in the byte stream, not a range: record a
900        // zero-width span so `span` stays the single positional field.
901        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        // An unterminated message ends before the next `UNH`.
995        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    // ── bail_on_first_error ──────────────────────────────────────────────────
1182
1183    /// A rule that emits two error-severity issues (one per DTM segment).
1184    fn two_dtm_errors_rule() -> ProfileRulePack {
1185        ProfileRulePack::new("TEST-BAIL")
1186            .with_rule_fn(|segments, issues| {
1187                // Rule A: emits one error per DTM segment.
1188                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                // Rule B: never fires; used to verify bail skips this rule.
1201                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        // Two DTM segments → Rule A emits 2 errors for them.
1214        // With bail, Rule B (BGM check) must NOT run.
1215        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        // Rule A fires: both DTM errors are in the report (the whole rule invocation
1228        // runs to completion before bail is checked).
1229        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        // Bail fired after Rule A: Rule B (BGM) must be skipped.
1239        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(); // bail_on_first_error defaults to false
1258        let ctx = ValidationContext::builder()
1259            .with_profile_pack(pack_no_bail)
1260            .build();
1261        let report = ctx.validate(&segments);
1262
1263        // Both rules run: one DTM error from Rule A, one BGM error from Rule B.
1264        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    // ── message_ref in ValidationRuleContext ─────────────────────────────────
1283
1284    #[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        // The message_ref is also stamped onto the issue itself.
1317        assert_eq!(info.message_ref.as_deref(), Some("MSG001"));
1318    }
1319}