edifact 0.20.0

EDIFACT (ISO 9735) for Rust: zero-copy parser, envelope-computing writer, typed derive, layered validation, DTM dates and CONTRL
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
//! Validation context: `ValidationContext`, `ValidationContextBuilder`, `LayeredValidator`.

use super::pack::ProfileRulePack;
use super::{
    CharsetValidator, EnvelopeValidator, ValidationLayer, ValidationRuleContext, Validator,
};
use crate::{Segment, ValidationReport, ValidationSeverity};
use std::any::Any;
use std::sync::Arc;

pub(super) struct LayeredValidator {
    pub(super) layer: ValidationLayer,
    pub(super) validator: Box<dyn Validator + Send + Sync>,
}

/// Runs the validation layers over one segment slice, collecting every
/// issue into a single [`ValidationReport`].
///
/// | Layer | [`ValidationLayer`] | Default | Checks | Provided by |
/// |---|---|---|---|---|
/// | Envelope | `Envelope` | off | interchange structure, counts, references, service-segment values | [`EnvelopeValidator`] |
/// | Syntax | `Syntax` | off (envelope switch) | directory-independent ISO 9735-1 rules | [`SyntaxValidator`][crate::SyntaxValidator] |
/// | Charset | `Charset` | off (envelope switch) | declared character repertoire | [`CharsetValidator`] |
/// | Structure | `Structure` | on | segment presence, order, arity | `DirectoryValidator` |
/// | Code-list | `CodeList` | on | DE values against the directory's code lists | `DirectoryValidator` |
/// | Profile | `Profile` | on | partner and industry business rules | [`ProfileRulePack`] |
///
/// Validators run in registration order within a layer; layers have no ordering
/// beyond that. With the envelope layer on, `UNB`/`UNZ`/`UNG`/`UNE` are excluded
/// from the slice the structure, code-list and profile layers see; envelope,
/// syntax and charset validators always see the whole slice.
///
/// With the envelope layer on, an issue from another layer that repeats an
/// `Envelope` issue — same stable code, segment tag, element and component
/// index, and the same span or, without a span, the same segment position —
/// is dropped, so `DirectoryValidator(service::lookup)` does not report a
/// `UNH`/`UNT` value twice. Issues with neither a span nor a position are
/// never dropped.
///
/// Every issue a validator leaves without a [`layer`][crate::ValidationIssue::layer]
/// is stamped with the layer that validator was registered under, in the flat
/// and the group pass. An explicit layer is kept.
///
/// A pack can be scoped by message type (`for_message_type`) and
/// association-assigned code (`for_release`).
///
/// # Group-aware validation
///
/// [`validate_grouped`][Self::validate_grouped] runs the flat pass and then a
/// group pass over a [`SegmentGroupIndexed`][crate::SegmentGroupIndexed] tree,
/// so rules scoped to a segment group — "DTM must appear in every SG5" — can
/// fire.
///
/// # Example — building a context
///
/// ```rust,ignore
/// use std::sync::{Arc, LazyLock};
/// use edifact::{ProfileRulePack, ValidationContext, ValidationLayer};
///
/// static ORDERS_PACK: LazyLock<Arc<ProfileRulePack>> = LazyLock::new(|| {
///     Arc::new(
///         ProfileRulePack::new("ORDERS-MIG-5.5")
///             .for_message_type("ORDERS")
///             .require_segment("BGM", "MIG-BGM-M")
///             .require_segment_in_group("SG2", "NAD", "SG2-NAD-M"),
///     )
/// });
///
/// let ctx = ValidationContext::builder()
///     .with_envelope_validation()
///     .with_profile_pack_arc(Arc::clone(&*ORDERS_PACK))
///     .build();
///
/// let report = ctx.validate(&segments);
/// ```
pub struct ValidationContext {
    pub(super) validators: Vec<LayeredValidator>,
    pub(super) envelope_enabled: bool,
    pub(super) structure_enabled: bool,
    pub(super) code_list_enabled: bool,
    pub(super) profile_enabled: bool,
    /// Stop evaluating all remaining validators as soon as a `Critical`-severity
    /// issue appears in the report.
    pub(super) bail_on_first_critical: bool,
    pub(super) message_type: Option<String>,
    /// Injected into every emitted `ValidationIssue` when set.
    pub(super) message_ref: Option<String>,
    pub(super) metadata: Option<Arc<dyn Any + Send + Sync>>,
    /// Advisory issues unconditionally appended to every report produced by
    /// this context — regardless of what segments are validated.
    ///
    /// Use [`ValidationContextBuilder::with_static_issue`] to populate.
    pub(super) static_issues: Vec<crate::ValidationIssue>,
}

/// Builder for [`ValidationContext`].
#[must_use = "call `.build()` to produce a `ValidationContext`"]
pub struct ValidationContextBuilder {
    pub(super) inner: ValidationContext,
}

impl Default for ValidationContextBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl ValidationContextBuilder {
    /// Create a new context builder.
    ///
    /// Structure, code-list, and profile layers are enabled by default.
    /// The envelope layer is **disabled** by default.
    pub fn new() -> Self {
        Self {
            inner: ValidationContext {
                validators: Vec::new(),
                envelope_enabled: false,
                structure_enabled: true,
                code_list_enabled: true,
                profile_enabled: true,
                bail_on_first_critical: false,
                message_type: None,
                message_ref: None,
                metadata: None,
                static_issues: Vec::new(),
            },
        }
    }

    /// Attach typed metadata accessible to context-aware profile rules.
    pub fn with_metadata<T: Any + Send + Sync + 'static>(mut self, value: T) -> Self {
        self.inner.metadata = Some(Arc::new(value));
        self
    }

    /// Stamp every issue produced by this context with the given message reference.
    pub fn with_message_ref(mut self, message_ref: impl Into<String>) -> Self {
        self.inner.message_ref = Some(message_ref.into());
        self
    }

    /// Set message type metadata for downstream validators.
    pub fn with_message_type(mut self, message_type: impl Into<String>) -> Self {
        self.inner.message_type = Some(message_type.into());
        let configured = self.inner.message_type.as_deref();
        for layered in &mut self.inner.validators {
            layered.validator.set_message_type(configured);
        }
        self
    }

    /// Enable/disable structure validators.
    pub fn structure(mut self, enabled: bool) -> Self {
        self.inner.structure_enabled = enabled;
        self
    }

    /// Enable/disable code-list validators.
    pub fn code_list(mut self, enabled: bool) -> Self {
        self.inner.code_list_enabled = enabled;
        self
    }

    /// Enable/disable profile validators.
    pub fn profile(mut self, enabled: bool) -> Self {
        self.inner.profile_enabled = enabled;
        self
    }

    /// Stop validating once a `Critical`-severity issue has appeared.
    ///
    /// The check happens **between validators**, not between issues: the
    /// validator that raised the `Critical` still finishes and contributes
    /// everything it found, and every validator after it — in any layer — is
    /// skipped. Bailing mid-validator would mean a report whose contents depend
    /// on the order rules happen to run in.
    ///
    /// Default: `false` (run every enabled layer and collect all issues).
    pub fn bail_on_first_critical(mut self, bail: bool) -> Self {
        self.inner.bail_on_first_critical = bail;
        self
    }

    /// Enable/disable envelope layer validators.
    ///
    /// Off by default.  Call [`with_envelope_validation`][Self::with_envelope_validation]
    /// to add the built-in [`EnvelopeValidator`] and enable the layer in one step.
    pub fn envelope(mut self, enabled: bool) -> Self {
        self.inner.envelope_enabled = enabled;
        self
    }

    /// Add the built-in [`EnvelopeValidator`] and enable the envelope layer.
    pub fn with_envelope_validation(mut self) -> Self {
        self.inner.envelope_enabled = true;
        self.inner.validators.push(LayeredValidator {
            layer: ValidationLayer::Envelope,
            validator: Box::new(EnvelopeValidator),
        });
        self
    }

    /// Check every value against the repertoire the interchange declares, and
    /// enable the envelope layer.
    ///
    /// Adds a [`CharsetValidator`] reading `UNB` S001 DE 0001, registered under
    /// [`ValidationLayer::Charset`] (switched by the envelope switch). See
    /// [`with_charset_validation_for`][Self::with_charset_validation_for] to pin
    /// a repertoire instead of reading it from the envelope.
    pub fn with_charset_validation(mut self) -> Self {
        self.inner.envelope_enabled = true;
        self.inner.validators.push(LayeredValidator {
            layer: ValidationLayer::Charset,
            validator: Box::new(CharsetValidator::from_envelope()),
        });
        self
    }

    /// Check every value against a fixed repertoire, and enable the envelope layer.
    ///
    /// Use for message-level slices that carry no `UNB`, or to hold a partner to
    /// a stricter repertoire than the one they declare.
    pub fn with_charset_validation_for(mut self, charset: crate::Charset) -> Self {
        self.inner.envelope_enabled = true;
        self.inner.validators.push(LayeredValidator {
            layer: ValidationLayer::Charset,
            validator: Box::new(CharsetValidator::with_charset(charset)),
        });
        self
    }

    /// Check the directory-independent ISO 9735-1 syntax rules, and enable the
    /// envelope layer.
    ///
    /// Registered under [`ValidationLayer::Syntax`], which the envelope switch
    /// controls. See [`SyntaxValidator`][crate::SyntaxValidator] for the exact rules. They
    /// apply to any interchange from any partner in any directory, so this needs
    /// no configuration and is worth enabling wherever the envelope layer is on.
    pub fn with_syntax_validation(mut self) -> Self {
        self.inner.envelope_enabled = true;
        self.inner.validators.push(LayeredValidator {
            layer: ValidationLayer::Syntax,
            validator: Box::new(crate::validator::SyntaxValidator),
        });
        self
    }

    /// Add a validator assigned to `layer`.
    pub fn with_validator<V>(mut self, layer: ValidationLayer, mut validator: V) -> Self
    where
        V: Validator + 'static,
    {
        validator.set_message_type(self.inner.message_type.as_deref());
        self.inner.validators.push(LayeredValidator {
            layer,
            validator: Box::new(validator),
        });
        self
    }

    /// Add a profile rule pack to the profile layer.
    ///
    /// The pack's own message-type scoping — set with
    /// [`ProfileRulePack::for_message_type`] — is what decides whether its rules
    /// run.  The context's message type does not narrow an unscoped pack.
    pub fn with_profile_pack(self, pack: ProfileRulePack) -> Self {
        self.with_profile_pack_inner(pack)
    }

    fn with_profile_pack_inner(mut self, pack: ProfileRulePack) -> Self {
        self.inner.validators.push(LayeredValidator {
            layer: ValidationLayer::Profile,
            validator: Box::new(pack),
        });
        self
    }

    /// Add a reference-counted profile rule pack to the profile layer.
    ///
    /// Unlike [`with_profile_pack`](Self::with_profile_pack), this method stores the pack
    /// behind an [`Arc`] so context forking (via
    /// [`ValidationContext::fork_with_message_ref`]) only increments the reference count
    /// instead of deep-cloning the rule vec.
    ///
    /// This is the preferred API for downstream code that caches packs in static
    /// storage (`LazyLock`, `OnceLock`) and reuses them across many validation calls.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use std::sync::{Arc, LazyLock};
    /// use edifact::{ProfileRulePack, ValidationContext};
    ///
    /// static PACK: LazyLock<Arc<ProfileRulePack>> = LazyLock::new(|| {
    ///     Arc::new(ProfileRulePack::new("MIG").require_segment("BGM", "MIG-BGM-M"))
    /// });
    ///
    /// let ctx = ValidationContext::builder()
    ///     .with_profile_pack_arc(Arc::clone(&*PACK))
    ///     .build();
    /// ```
    pub fn with_profile_pack_arc(mut self, pack: std::sync::Arc<ProfileRulePack>) -> Self {
        self.inner.validators.push(LayeredValidator {
            layer: ValidationLayer::Profile,
            validator: Box::new(pack),
        });
        self
    }

    /// Unconditionally append `issue` to every report produced by this context.
    ///
    /// Static issues are emitted on every `validate_*` call — they are not
    /// evaluated against segments.  This is useful for advisory notices that
    /// should always be present regardless of message content (e.g. "the profile layer
    /// is inactive for this message type").
    pub fn with_static_issue(mut self, issue: crate::ValidationIssue) -> Self {
        self.inner.static_issues.push(issue);
        self
    }

    /// Finalize builder and create context.
    #[must_use = "call `.validate()` on the resulting context"]
    pub fn build(self) -> ValidationContext {
        self.inner
    }
}

impl ValidationContext {
    /// Start building a validation context.
    pub fn builder() -> ValidationContextBuilder {
        ValidationContextBuilder::new()
    }

    /// Execute validators in lenient mode for enabled layers.
    pub fn validate(&self, segments: &[Segment<'_>]) -> ValidationReport {
        self.validate_with_context(segments, &self.build_rule_context())
    }

    /// Execute flat + group-aware validators in lenient mode.
    ///
    /// This method runs the full flat validation pass (same as
    /// [`validate`](Self::validate)) **and** then runs the
    /// group-aware pass by calling [`Validator::validate_group_batch`] on every
    /// validator.  Validators without group rules treat `validate_group_batch`
    /// as a no-op, so this is safe to call for any context.
    ///
    /// # When to use
    ///
    /// Use this method when you have already grouped your segments with
    /// [`group_segments_indexed`][crate::group_segments_indexed] or
    /// [`group_segments_indexed`][crate::group_segments_indexed] and
    /// want group-presence or cross-group rules (via
    /// [`ProfileRulePack::with_scoped_group_rule_fn`][crate::ProfileRulePack::with_scoped_group_rule_fn])
    /// to fire.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use edifact::{group_segments_indexed, ValidationContext};
    /// use edifact::group::GroupDef;
    ///
    /// static SCHEMA: &[GroupDef] = &[GroupDef::new("SG5", "LOC")];
    ///
    /// let tree = group_segments_indexed(&segments, SCHEMA, "ROOT");
    /// let pack = ProfileRulePack::new("PROFILE")
    ///     .require_segment_in_group("SG5", "DTM", "SG5-DTM-M");
    /// let ctx = ValidationContext::builder().with_profile_pack(pack).build();
    ///
    /// let report = ctx.validate_grouped(&tree, &segments);
    /// ```
    pub fn validate_grouped(
        &self,
        root: &crate::group::SegmentGroupIndexed<'_>,
        segments: &[Segment<'_>],
    ) -> ValidationReport {
        let base_ctx = self.build_rule_context();
        // Phase 1: flat validation.
        let mut report = self.validate_with_context(segments, &base_ctx);
        // Phase 2: group-aware validation with pre-extracted UNH message type.
        let unh_mt = segments
            .iter()
            .find(|s| s.tag == "UNH")
            .and_then(|s| s.get_element(1))
            .and_then(|e| e.get_component(0));
        let ctx_with_type;
        let group_ctx: &ValidationRuleContext<'_> = if let Some(mt) = unh_mt {
            ctx_with_type = ValidationRuleContext {
                metadata: base_ctx.metadata,
                message_ref: base_ctx.message_ref,
                message_type: Some(mt),
            };
            &ctx_with_type
        } else {
            &base_ctx
        };
        self.run_group_pass(root, segments, &mut report, group_ctx);
        report
    }

    /// Phase-2 group pass: call `validate_group_batch` on each enabled validator.
    fn run_group_pass(
        &self,
        root: &crate::group::SegmentGroupIndexed<'_>,
        segments: &[Segment<'_>],
        report: &mut ValidationReport,
        context: &ValidationRuleContext<'_>,
    ) {
        // Nothing to do when no enabled validator has group rules.
        if !self
            .validators
            .iter()
            .any(|lv| self.layer_enabled(lv.layer) && lv.validator.has_group_rules())
        {
            return;
        }
        for lv in &self.validators {
            if !self.layer_enabled(lv.layer) {
                continue;
            }
            let before = IssueCounts::of(report);
            lv.validator
                .validate_group_batch(root, segments, report, context);
            before.stamp_layer(report, lv.layer);
            if self.bail_on_first_critical && report.has_critical_errors() {
                break;
            }
        }
    }

    /// Execute validators with per-call typed metadata.
    ///
    /// `message_type` is set to `None` here; the concrete validation method
    /// (`validate_with_context`) re-extracts the message type from the `UNH`
    /// segment, so there is no information loss.
    pub fn validate_with<T: Any + Send + Sync>(
        &self,
        segments: &[Segment<'_>],
        value: &T,
    ) -> ValidationReport {
        let ctx = ValidationRuleContext {
            metadata: Some(value as &(dyn Any + Send + Sync)),
            message_ref: self.message_ref.as_deref(),
            message_type: None,
        };
        self.validate_with_context(segments, &ctx)
    }

    fn build_rule_context(&self) -> ValidationRuleContext<'_> {
        self.metadata
            .as_ref()
            .map(|arc| ValidationRuleContext {
                metadata: Some(arc.as_ref() as &(dyn Any + Send + Sync)),
                message_ref: self.message_ref.as_deref(),
                message_type: None,
            })
            .unwrap_or_else(|| ValidationRuleContext {
                metadata: None,
                message_ref: self.message_ref.as_deref(),
                message_type: None,
            })
    }

    fn validate_with_context(
        &self,
        segments: &[Segment<'_>],
        context: &ValidationRuleContext<'_>,
    ) -> ValidationReport {
        let mut report = ValidationReport::default();
        // Pre-extract the UNH message type once for every validator.
        let unh_message_type = segments
            .iter()
            .find(|s| s.tag == "UNH")
            .and_then(|s| s.get_element(1))
            .and_then(|e| e.get_component(0));
        let ctx_with_type;
        let effective_ctx: &ValidationRuleContext<'_> = if let Some(mt) = unh_message_type {
            ctx_with_type = ValidationRuleContext {
                metadata: context.metadata,
                message_ref: context.message_ref,
                message_type: Some(mt),
            };
            &ctx_with_type
        } else {
            context
        };
        let mut filtered: Option<Vec<Segment<'_>>> = None;
        // Computed once, up front: whether envelope segments are hidden from
        // the other layers must not depend on the order validators were
        // registered in.
        let envelope_active = self.envelope_layer_active();

        for lv in &self.validators {
            if !self.layer_enabled(lv.layer) {
                continue;
            }
            let before = IssueCounts::of(&report);
            if lv.layer.is_envelope_class() {
                lv.validator
                    .validate_batch(segments, &mut report, effective_ctx);
            } else {
                let active: &[Segment<'_>] = if envelope_active {
                    match envelope_interior(segments) {
                        // UNB/UNZ bracket the message and no UNG/UNE appear
                        // inside: a sub-slice suffices and no segment is cloned.
                        Some(interior) => interior,
                        None => filtered.get_or_insert_with(|| {
                            segments
                                .iter()
                                .filter(|s| !matches!(s.tag(), "UNB" | "UNZ" | "UNG" | "UNE"))
                                .cloned()
                                .collect()
                        }),
                    }
                } else {
                    segments
                };
                lv.validator
                    .validate_batch(active, &mut report, effective_ctx);
            }
            before.stamp_layer(&mut report, lv.layer);
            if self.bail_on_first_critical && report.has_critical_errors() {
                break;
            }
        }

        if envelope_active {
            drop_envelope_duplicates(&mut report);
        }

        if let Some(ref msg_ref) = self.message_ref {
            for issue in report
                .errors
                .iter_mut()
                .chain(report.warnings.iter_mut())
                .chain(report.infos.iter_mut())
            {
                if issue.message_ref.is_none() {
                    issue.message_ref = Some(msg_ref.clone());
                }
            }
        }
        // Append static advisory issues unconditionally.
        for issue in &self.static_issues {
            match issue.severity {
                ValidationSeverity::Critical | ValidationSeverity::Error => {
                    report.add_error(issue.clone());
                }
                ValidationSeverity::Warning => {
                    report.warnings.push(issue.clone());
                }
                ValidationSeverity::Info => {
                    report.infos.push(issue.clone());
                }
            }
        }
        report
    }

    /// Message type metadata associated with this context, if provided.
    pub fn message_type(&self) -> Option<&str> {
        self.message_type.as_deref()
    }

    /// Message reference (`UNH` element 0) associated with this context, if provided.
    pub fn message_ref(&self) -> Option<&str> {
        self.message_ref.as_deref()
    }

    /// Create a child context that inherits all rules and configuration from `self`
    /// but is scoped to a specific message reference (UNH DE 0062).
    ///
    /// Issues produced by the child context are automatically stamped with
    /// `message_ref`, making it easy to correlate findings in a multi-message
    /// interchange back to the originating `UNH`/`UNT` envelope.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let base_ctx = ValidationContext::builder()
    ///     .with_profile_pack(mig_pack)
    ///     .build();
    ///
    /// for (ref_no, message_segments) in messages {
    ///     let child = base_ctx.fork_with_message_ref(&ref_no);
    ///     let report = child.validate(&message_segments);
    /// }
    /// ```
    pub fn fork_with_message_ref(&self, message_ref: impl Into<String>) -> Self {
        let validators: Vec<LayeredValidator> = self
            .validators
            .iter()
            .filter_map(|lv| {
                lv.validator.fork().map(|forked| LayeredValidator {
                    layer: lv.layer,
                    validator: forked,
                })
            })
            .collect();
        // Count how many validators were excluded (non-forkable).
        let excluded_count = self.validators.len() - validators.len();

        let mut static_issues = self.static_issues.clone();
        if excluded_count > 0 {
            static_issues.push(
                crate::ValidationIssue::new(
                    crate::ValidationSeverity::Info,
                    format!(
                        "{excluded_count} validator(s) excluded from forked context \
                         because fork() returned None; all their rules (flat and \
                         group-pass) will not run for this message",
                    ),
                )
                .with_rule_id("edifact::fork::excluded-validator")
                // A note about the context, not about the message: no layer.
                .with_kind(crate::FindingKind::Other),
            );
        }

        Self {
            validators,
            envelope_enabled: self.envelope_enabled,
            structure_enabled: self.structure_enabled,
            code_list_enabled: self.code_list_enabled,
            profile_enabled: self.profile_enabled,
            bail_on_first_critical: self.bail_on_first_critical,
            message_type: self.message_type.clone(),
            message_ref: Some(message_ref.into()),
            metadata: self.metadata.clone(),
            static_issues,
        }
    }

    fn layer_enabled(&self, layer: ValidationLayer) -> bool {
        match layer {
            ValidationLayer::Envelope | ValidationLayer::Syntax | ValidationLayer::Charset => {
                self.envelope_enabled
            }
            ValidationLayer::Structure => self.structure_enabled,
            ValidationLayer::CodeList => self.code_list_enabled,
            ValidationLayer::Profile => self.profile_enabled,
        }
    }

    /// Whether an enabled envelope-class validator (envelope, syntax or charset)
    /// is registered.
    ///
    /// Determines whether envelope segments are hidden from later layers.  It is
    /// a property of the context as a whole, not of how far the validator loop
    /// has progressed.
    fn envelope_layer_active(&self) -> bool {
        self.envelope_enabled
            && self
                .validators
                .iter()
                .any(|lv| lv.layer.is_envelope_class())
    }
}

/// Drop every non-envelope issue that repeats an `Envelope`-layer issue: same
/// stable code, segment tag, element and component index, and the same span
/// or, for an issue without one, the same segment position.
///
/// `DirectoryValidator(service::lookup)` checks the service segments the
/// envelope layer already checks, with the same code. An issue with neither a
/// span nor a position is never dropped: "the same" cannot be told from
/// "another one of the same kind".
fn drop_envelope_duplicates(report: &mut ValidationReport) {
    #[derive(PartialEq, Eq, Hash)]
    enum Key {
        Spanned(
            String,
            crate::Span,
            Option<String>,
            Option<u16>,
            Option<u16>,
        ),
        Positioned(String, Option<String>, Option<u16>, Option<u16>, u32),
    }
    let key = |issue: &crate::ValidationIssue| -> Option<Key> {
        let code = issue.error_code()?.to_owned();
        let tag = issue.segment_tag().map(str::to_owned);
        let (element, component) = (issue.element_index, issue.component_index);
        match (issue.span, issue.segment_position) {
            (Some(span), _) => Some(Key::Spanned(code, span, tag, element, component)),
            (None, Some(position)) => {
                Some(Key::Positioned(code, tag, element, component, position))
            }
            (None, None) => None,
        }
    };
    let is_envelope =
        |issue: &crate::ValidationIssue| issue.layer == Some(ValidationLayer::Envelope);
    let envelope: std::collections::HashSet<Key> = report
        .errors
        .iter()
        .chain(&report.warnings)
        .chain(&report.infos)
        .filter(|issue| is_envelope(issue))
        .filter_map(key)
        .collect();
    if envelope.is_empty() {
        return;
    }
    let duplicate = |issue: &crate::ValidationIssue| {
        !is_envelope(issue) && key(issue).is_some_and(|k| envelope.contains(&k))
    };
    report.errors.retain(|issue| !duplicate(issue));
    report.warnings.retain(|issue| !duplicate(issue));
    report.infos.retain(|issue| !duplicate(issue));
}

/// Bucket lengths of a report before a validator runs, so the issues that
/// validator added can be told apart afterwards.
///
/// Validators only ever append, so everything past these lengths is new.
#[derive(Clone, Copy)]
struct IssueCounts {
    errors: usize,
    warnings: usize,
    infos: usize,
}

impl IssueCounts {
    fn of(report: &ValidationReport) -> Self {
        Self {
            errors: report.errors.len(),
            warnings: report.warnings.len(),
            infos: report.infos.len(),
        }
    }

    /// Stamp `layer` onto every issue added since `self` that has none.
    fn stamp_layer(self, report: &mut ValidationReport, layer: ValidationLayer) {
        let new = report
            .errors
            .iter_mut()
            .skip(self.errors)
            .chain(report.warnings.iter_mut().skip(self.warnings))
            .chain(report.infos.iter_mut().skip(self.infos));
        for issue in new {
            if issue.layer.is_none() {
                issue.layer = Some(layer);
            }
        }
    }
}

/// Return the message body as a sub-slice when the envelope segments form a
/// clean `UNB` … `UNZ` bracket with no functional groups inside.
///
/// Returns `None` when the caller must fall back to filter-and-clone (functional
/// groups present, or the interchange is not bracketed as expected).
fn envelope_interior<'s, 'a>(segments: &'s [Segment<'a>]) -> Option<&'s [Segment<'a>]> {
    let (first, last) = (segments.first()?, segments.last()?);
    if segments.len() < 2 || first.tag != "UNB" || last.tag != "UNZ" {
        return None;
    }
    let interior = &segments[1..segments.len() - 1];
    if interior
        .iter()
        .any(|s| matches!(s.tag(), "UNB" | "UNZ" | "UNG" | "UNE"))
    {
        return None;
    }
    Some(interior)
}