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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
//! Validation pipeline for structural and semantic EDIFACT checks.
//!
//! The validation module is split into three sub-modules:
//!
//! - [`pack`] — [`ProfileRule`], [`ProfileRulePack`], and rule construction helpers.
//! - [`context`] — [`ValidationContext`], [`ValidationContextBuilder`].
//! - This module (`mod.rs`) — [`Validator`] trait, [`ValidationRuleContext`],
//!   [`ValidationLayer`], [`EnvelopeValidator`], and helper functions.

pub mod context;
pub mod pack;

pub use context::{ValidationContext, ValidationContextBuilder};
pub use pack::{ProfileRule, ProfileRulePack};

use crate::{
    EdifactError, FindingKind, Segment, Span, ValidationIssue, ValidationReport, ValidationSeverity,
};
use std::any::Any;

/// Typed context injected into profile rule closures at validation time.
///
/// Rules access per-call metadata via [`ValidationRuleContext::metadata`] and
/// the message reference (UNH element 0) via [`ValidationRuleContext::message_ref`].
///
/// # Example
///
/// ```rust,ignore
/// let pack = ProfileRulePack::new("PROFILE-4711")
///     .with_contextual_rule_fn(|segs, ctx, issues| {
///         let Some(process_id) = ctx.metadata::<ProcessId>() else { return };
///         let msg_ref = ctx.message_ref.unwrap_or("<unknown>");
///     });
/// ```
#[derive(Clone, Copy)]
pub struct ValidationRuleContext<'a> {
    pub(super) metadata: Option<&'a (dyn Any + Send + Sync)>,
    /// Message reference (`UNH` element 0) for this validation call.
    pub message_ref: Option<&'a str>,
    /// EDIFACT message type extracted from `UNH` element 1 component 0.
    ///
    /// Pre-extracted once by [`ValidationContext`] before dispatching to validators,
    /// so each [`ProfileRulePack`] can skip its own `UNH` scan.
    /// `None` when the message type could not be determined (no `UNH`, or when calling
    /// [`ProfileRulePack::validate_batch`] directly without a `ValidationContext`).
    pub message_type: Option<&'a str>,
}

impl<'a> ValidationRuleContext<'a> {
    /// Construct a context with no metadata and no message reference.
    pub fn empty() -> Self {
        Self {
            metadata: None,
            message_ref: None,
            message_type: None,
        }
    }

    /// Construct a context holding a typed metadata reference.
    pub fn new<T: Any + Send + Sync>(value: &'a T) -> Self {
        Self {
            metadata: Some(value as &(dyn Any + Send + Sync)),
            message_ref: None,
            message_type: None,
        }
    }

    /// Attach a message reference to this context (builder-style).
    pub fn with_message_ref(mut self, msg_ref: &'a str) -> Self {
        self.message_ref = Some(msg_ref);
        self
    }

    /// Attach a pre-extracted message type to this context (builder-style).
    pub fn with_message_type(mut self, message_type: &'a str) -> Self {
        self.message_type = Some(message_type);
        self
    }

    /// Downcast the metadata to `T`.  Returns `None` if no metadata was
    /// injected or if the concrete type does not match `T`.
    pub fn metadata<T: Any + Send + Sync>(&self) -> Option<&T> {
        self.metadata?.downcast_ref::<T>()
    }

    /// Return `true` if metadata was provided.
    pub fn has_metadata(&self) -> bool {
        self.metadata.is_some()
    }
}

impl std::fmt::Debug for ValidationRuleContext<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ValidationRuleContext")
            .field("has_metadata", &self.metadata.is_some())
            .field("message_ref", &self.message_ref)
            .field("message_type", &self.message_type)
            .finish()
    }
}

/// The validation stage a validator is registered under, and that an issue
/// was produced by ([`ValidationIssue::layer`]).
///
/// | Variant | [`as_str`](Self::as_str) | Stage | Switched by |
/// |---|---|---|---|
/// | `Envelope` | `envelope` | `UNB`/`UNG`/`UNH`/`UNT`/`UNE`/`UNZ` structure, counts and references | [`envelope`][ValidationContextBuilder::envelope] |
/// | `Syntax` | `syntax` | directory-independent ISO 9735-1 rules ([`SyntaxValidator`]) | [`envelope`][ValidationContextBuilder::envelope] |
/// | `Charset` | `charset` | values against the declared character repertoire ([`CharsetValidator`]) | [`envelope`][ValidationContextBuilder::envelope] |
/// | `Structure` | `structure` | directory structure: segment presence, order, arity | [`structure`][ValidationContextBuilder::structure] |
/// | `CodeList` | `code_list` | directory code lists | [`code_list`][ValidationContextBuilder::code_list] |
/// | `Profile` | `profile` | downstream profile packs | [`profile`][ValidationContextBuilder::profile] |
///
/// `Syntax` and `Charset` are interchange-level stages like `Envelope`: they
/// share its switch and, like it, see the whole slice including `UNB`/`UNZ`.
/// They exist as separate variants so an issue says which stage found it — a
/// blank value or a `€` in a `UNOC` interchange is not an envelope fault.
///
/// Marked `#[non_exhaustive]`. With the `serde` feature variants serialise by
/// name (`"CodeList"`), the casing [`ValidationSeverity`] uses.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum ValidationLayer {
    /// Interchange / message envelope checks (`UNB`/`UNH`/`UNT`/`UNZ` counts).
    Envelope,
    /// Directory-independent ISO 9735-1 syntax checks.
    Syntax,
    /// Character repertoire checks.
    Charset,
    /// Directory structure checks (segment presence/order/arity).
    Structure,
    /// Directory code-list checks.
    CodeList,
    /// Downstream profile-pack checks.
    Profile,
}

impl ValidationLayer {
    /// A stable lowercase identifier, e.g. `"code_list"`.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Envelope => "envelope",
            Self::Syntax => "syntax",
            Self::Charset => "charset",
            Self::Structure => "structure",
            Self::CodeList => "code_list",
            Self::Profile => "profile",
        }
    }

    /// Whether this layer is an interchange-level stage: switched by the
    /// envelope switch and run over the unfiltered slice.
    pub(crate) fn is_envelope_class(self) -> bool {
        matches!(self, Self::Envelope | Self::Syntax | Self::Charset)
    }
}

impl std::fmt::Display for ValidationLayer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Pluggable validator for parsed EDIFACT segments.
///
/// The primary contract is [`validate_batch`](Validator::validate_batch), which processes an
/// entire segment sequence and appends issues to a [`ValidationReport`].
pub trait Validator: Send + Sync {
    /// Validate a full segment set and append issues to `report`.
    fn validate_batch(
        &self,
        segments: &[Segment<'_>],
        report: &mut ValidationReport,
        context: &ValidationRuleContext<'_>,
    );

    /// Validate a segment-group tree and append issues to `report`.
    ///
    /// Called by [`ValidationContext::validate_grouped`] in addition to
    /// [`validate_batch`](Validator::validate_batch).  Validators that only perform
    /// flat segment checks (e.g. [`EnvelopeValidator`]) can leave this as the
    /// default no-op; only validators with group-scoped rules (such as a
    /// [`ProfileRulePack`] with at least one group rule) need to override it.
    ///
    /// The default implementation is a no-op, so validators without group
    /// rules need not implement it.
    fn validate_group_batch(
        &self,
        _root: &crate::group::SegmentGroupIndexed<'_>,
        _all_segments: &[Segment<'_>],
        _report: &mut ValidationReport,
        _context: &ValidationRuleContext<'_>,
    ) {
    }

    /// Returns `true` if this validator has any group-scoped rules.
    ///
    /// Used by [`crate::ValidationContext`] to short-circuit the
    /// group-tree walk when no validator in the context has group rules.
    ///
    /// The default implementation returns `false`.
    fn has_group_rules(&self) -> bool {
        false
    }

    /// Configure message-type metadata for validators that support explicit scoping.
    fn set_message_type(&mut self, _message_type: Option<&str>) {}

    /// Create a `Box<dyn Validator>` clone of this validator for context forking.
    ///
    /// Return `Some(boxed_clone)` for validators that support cheap forking
    /// (e.g. those backed by `Arc` data, like [`ProfileRulePack`]).
    ///
    /// Return `None` for validators that cannot be forked (e.g. stateful validators
    /// without `Clone`).  Returning `None` causes the validator to be silently
    /// **excluded** from forked contexts — forking is used by
    /// [`crate::ValidationContext::validate_grouped`] to validate
    /// each group in isolation, so omitting a non-forkable validator from the
    /// forked context is safer than panicking.
    fn fork(&self) -> Option<Box<dyn Validator + Send + Sync>> {
        None
    }
}

/// Helper for per-segment validators: iterates `segments`, calls `f` for each one,
/// and converts any `Err` into report entries.
pub fn validate_each<F>(segments: &[Segment<'_>], report: &mut ValidationReport, mut f: F)
where
    F: FnMut(&Segment<'_>) -> Result<(), EdifactError>,
{
    for segment in segments {
        if let Err(err) = f(segment) {
            report_error(report, err);
        }
    }
}

/// One-based segment positions within each message (DE 0096, `UNH` = 1).
///
/// A message runs from its `UNH` to its `UNT`; one without `UNT` ends before
/// the next `UNH` or at the end of the batch. Segments outside every message
/// have no position.
pub(crate) struct MessagePositions {
    /// `(start, end)` index range of each message, `end` inclusive, ascending.
    messages: Vec<(usize, usize)>,
}

impl MessagePositions {
    pub(crate) fn new(segments: &[Segment<'_>]) -> Self {
        let mut messages = Vec::new();
        let mut open: Option<usize> = None;
        for (index, segment) in segments.iter().enumerate() {
            match segment.tag() {
                "UNH" => {
                    if let Some(start) = open.replace(index) {
                        messages.push((start, index - 1));
                    }
                }
                "UNT" => {
                    if let Some(start) = open.take() {
                        messages.push((start, index));
                    }
                }
                _ => {}
            }
        }
        if let Some(start) = open
            && let Some(last) = segments.len().checked_sub(1)
        {
            messages.push((start, last));
        }
        Self { messages }
    }

    /// The one-based position of `segments[index]` within its message.
    pub(crate) fn position(&self, index: usize) -> Option<usize> {
        let at = self.messages.partition_point(|&(start, _)| start <= index);
        let &(start, end) = self.messages.get(at.checked_sub(1)?)?;
        (index <= end).then(|| index - start + 1)
    }
}

/// Add `issue` to the bucket its severity belongs in.
pub(crate) fn push_issue(report: &mut ValidationReport, issue: ValidationIssue) {
    match issue.severity {
        ValidationSeverity::Critical | ValidationSeverity::Error => report.add_error(issue),
        ValidationSeverity::Warning => report.add_warning(issue),
        ValidationSeverity::Info => report.add_info(issue),
    }
}

/// Convert a low-level validation error to a user-facing issue and append it.
///
/// Severity comes from [`report::severity_for_error`][crate::report::severity_for_error],
/// which is also what the `miette` rendering uses.
///
/// The issue's [`kind`][ValidationIssue::kind] is
/// [`FindingKind::for_error`]; layer and segment position are left for the
/// caller, which knows them.
pub(crate) fn report_error(report: &mut ValidationReport, err: EdifactError) {
    push_issue(report, issue_from_error(err));
}

/// [`report_error`] with the producing layer and, when known, the segment's
/// one-based message position.
pub(crate) fn report_error_at(
    report: &mut ValidationReport,
    err: EdifactError,
    layer: ValidationLayer,
    position: Option<usize>,
) {
    let mut issue = issue_from_error(err).with_layer(layer);
    if let Some(position) = position {
        issue = issue.with_segment_position(position);
    }
    push_issue(report, issue);
}

// ── EnvelopeValidator ─────────────────────────────────────────────────────────

/// Built-in validator for the EDIFACT interchange envelope.
///
/// Reports every finding of [`validate_envelope_lenient`][crate::validate_envelope_lenient]:
/// structure, control counts and references, and every service-segment value.  Registered by
/// [`ValidationContextBuilder::with_envelope_validation`].
pub struct EnvelopeValidator;

impl Validator for EnvelopeValidator {
    fn validate_batch(
        &self,
        segments: &[Segment<'_>],
        report: &mut ValidationReport,
        _ctx: &ValidationRuleContext<'_>,
    ) {
        // The lenient path, so one report holds every envelope violation.
        // A finding is placed at the segment its check ran on or, failing
        // that, at the segment its span falls in.
        let (result, located) = crate::envelope::validate_envelope_located(segments);
        let positions = MessagePositions::new(segments);
        for (e, index) in result.errors.into_iter().zip(located) {
            let mut issue = issue_from_error(e).with_layer(ValidationLayer::Envelope);
            let index = index.or_else(|| {
                let span = issue.span()?;
                let at = segments
                    .partition_point(|s| s.span.start <= span.start)
                    .checked_sub(1)?;
                (span.end <= segments[at].span.end).then_some(at)
            });
            if let Some(position) = index.and_then(|i| positions.position(i)) {
                issue = issue.with_segment_position(position);
            }
            push_issue(report, issue);
        }
    }

    fn fork(&self) -> Option<Box<dyn Validator + Send + Sync>> {
        Some(Box::new(EnvelopeValidator))
    }
}

// ── SyntaxValidator ───────────────────────────────────────────────────────────

/// Checks the ISO 9735-1 rules that hold for **every** interchange, whatever
/// directory or profile it claims.
///
/// These are the rules a partner's translator enforces before it ever looks at a
/// message type, and they need no directory to check:
///
/// | Rule | Source | Reported as |
/// |---|---|---|
/// | A segment carries at least one data element besides its tag | §7.5, §8.5 | `E046` |
/// | No data element value is made only of spaces | §9.3 | `E045` (warning) |
///
/// Both are things a hand-rolled writer produces by accident: an `ABC'` where a
/// conditional segment should have been dropped entirely, or a fixed-width field
/// padded with spaces instead of suppressed. Neither trips a count check, and
/// both are rejected downstream.
///
/// Registered by
/// [`ValidationContextBuilder::with_syntax_validation`][crate::ValidationContextBuilder::with_syntax_validation].
///
/// # Example
///
/// ```
/// use edifact::{from_bytes, ValidationContext};
///
/// // `FTX+` carries a value of nothing but spaces; `DTM` carries no data at all.
/// let segments: Vec<_> = from_bytes(b"FTX+   'DTM'")
///     .collect::<Result<_, _>>()?;
///
/// let report = ValidationContext::builder()
///     .with_syntax_validation()
///     .build()
///     .validate(&segments);
///
/// assert_eq!(report.errors()[0].error_code(), Some("E046")); // DTM has no data element
/// assert_eq!(report.warnings()[0].error_code(), Some("E045")); // FTX value is only spaces
/// # Ok::<(), edifact::EdifactError>(())
/// ```
pub struct SyntaxValidator;

impl Validator for SyntaxValidator {
    fn validate_batch(
        &self,
        segments: &[Segment<'_>],
        report: &mut ValidationReport,
        _context: &ValidationRuleContext<'_>,
    ) {
        let positions = MessagePositions::new(segments);
        for (index, segment) in segments.iter().enumerate() {
            let position = positions.position(index);
            let report_syntax = |report: &mut ValidationReport, err: EdifactError| {
                report_error_at(report, err, ValidationLayer::Syntax, position);
            };
            // §7.5: "A segment shall contain at least one data element in
            // addition to the segment tag."  A segment whose only element is
            // empty still satisfies this — §8.4 spells out `ABC'` versus the
            // mandatory-segment-with-no-data form — so the test is on presence,
            // not on content.
            if segment.elements.is_empty() {
                report_syntax(
                    report,
                    EdifactError::SegmentWithoutDataElements {
                        tag: segment.tag().to_owned(),
                        span: segment.span,
                    },
                );
            }

            // §8.7.1: separators that would follow omitted data elements at the
            // end of a segment "shall also be omitted".  A segment ending in an
            // empty element carries a separator that says nothing.
            if segment
                .elements
                .last()
                .is_some_and(|element| element.repetitions().flatten().all(|(v, _)| v.is_empty()))
                && segment.elements.len() > 1
            {
                report_syntax(
                    report,
                    EdifactError::TrailingSeparator {
                        tag: segment.tag().to_owned(),
                        element_index: None,
                        span: segment.span,
                    },
                );
            }

            for (element_index, element) in segment.elements.iter().enumerate() {
                // §8.7.2 says the same for components at the end of a composite.
                // Only a composite can have one: a single-component element that
                // is empty is an omitted element, not a trailing separator.
                if element.components.len() > 1
                    && element.components.last().is_some_and(|(v, _)| v.is_empty())
                {
                    report_syntax(
                        report,
                        EdifactError::TrailingSeparator {
                            tag: segment.tag().to_owned(),
                            element_index: Some(element_index),
                            span: element.span,
                        },
                    );
                }

                for components in element.repetitions() {
                    for (component_index, (value, span)) in components.iter().enumerate() {
                        // §9.3: "A data element value containing only space(s)
                        // shall not be allowed."  An empty value is a different
                        // thing entirely — that is how EDIFACT spells "absent".
                        if !value.is_empty() && value.bytes().all(|b| b == b' ') {
                            report_syntax(
                                report,
                                EdifactError::BlankDataElementValue {
                                    tag: segment.tag().to_owned(),
                                    element_index,
                                    component_index,
                                    span: *span,
                                },
                            );
                        }
                    }
                }
            }
        }
    }

    fn fork(&self) -> Option<Box<dyn Validator + Send + Sync>> {
        Some(Box::new(SyntaxValidator))
    }
}

// ── CharsetValidator ──────────────────────────────────────────────────────────

/// Checks that every value in the message is expressible in the interchange's
/// declared character repertoire (`UNB` S001 DE 0001).
///
/// This is the check partners actually enforce and that costs real money when it
/// is missed: a `UNOA` interchange carrying a lower-case letter, or a `UNOC` one
/// carrying `€`, is rejected at the far end — but only after it has been sent.
///
/// Values are checked as **decoded text**, so run this after
/// [`decode_interchange`][crate::decode_interchange] (or on natively-ASCII
/// input). It answers "can this text be written back out in the repertoire the
/// header promises?", which is the question that matters.
///
/// Registered by
/// [`ValidationContextBuilder::with_charset_validation`][crate::ValidationContextBuilder::with_charset_validation].
///
/// # Example
///
/// ```
/// use edifact::{from_bytes, ValidationContext};
///
/// // UNOA is upper-case only, but the party name is mixed case.
/// let segments: Vec<_> = from_bytes(
///     b"UNB+UNOA:3+S+R+200101:0900+1'NAD+BY+Acme Ltd'UNZ+0+1'",
/// )
/// .collect::<Result<_, _>>()?;
///
/// let report = ValidationContext::builder()
///     .with_charset_validation()
///     .build()
///     .validate(&segments);
///
/// let issue = report.errors().iter().find(|i| i.error_code() == Some("E038")).unwrap();
/// assert_eq!(issue.segment_tag.as_deref(), Some("NAD"));
/// # Ok::<(), edifact::EdifactError>(())
/// ```
pub struct CharsetValidator {
    /// Repertoire to check against; `None` reads it from the interchange's `UNB`.
    charset: Option<crate::Charset>,
}

impl CharsetValidator {
    /// Read the repertoire from the interchange's own `UNB` S001 DE 0001.
    ///
    /// A slice with no `UNB` — a single message window, say — is not checked,
    /// because nothing declares what it should be checked against.
    #[must_use]
    pub fn from_envelope() -> Self {
        Self { charset: None }
    }

    /// Check against a fixed repertoire, whatever the `UNB` says.
    ///
    /// Use this for message-level slices that carry no `UNB`, or to hold a
    /// partner to a stricter repertoire than the one they declare.
    #[must_use]
    pub fn with_charset(charset: crate::Charset) -> Self {
        Self {
            charset: Some(charset),
        }
    }

    /// The repertoire in force for `segments`.
    fn resolve(&self, segments: &[Segment<'_>]) -> Option<crate::Charset> {
        if self.charset.is_some() {
            return self.charset;
        }
        let identifier = segments
            .iter()
            .find(|s| s.tag == "UNB")
            .and_then(|unb| unb.component_str(0, 0))?;
        // An unrecognised or unsupported identifier is the envelope validator's
        // finding to report, not this one's — silently declining to check is the
        // right move rather than raising a second, confusing error for it.
        crate::Charset::from_syntax_identifier(identifier).ok()
    }
}

impl Validator for CharsetValidator {
    fn validate_batch(
        &self,
        segments: &[Segment<'_>],
        report: &mut ValidationReport,
        _context: &ValidationRuleContext<'_>,
    ) {
        let Some(charset) = self.resolve(segments) else {
            return;
        };
        if charset == crate::Charset::UnoY {
            return; // Everything is permitted; nothing to check.
        }
        let positions = MessagePositions::new(segments);
        for (index, segment) in segments.iter().enumerate() {
            let position = positions.position(index);
            for (element_index, element) in segment.elements.iter().enumerate() {
                for components in element.repetitions() {
                    for (component_index, (value, span)) in components.iter().enumerate() {
                        let Some((offset, character)) = charset.first_violation(value) else {
                            continue;
                        };
                        let mut issue = ValidationIssue::new(
                            ValidationSeverity::Error,
                            format!(
                                "character {character:?} is not in the {charset} character \
                                 repertoire declared by UNB S001",
                            ),
                        )
                        .with_error_code(
                            EdifactError::CharacterNotInRepertoire {
                                charset: charset.syntax_identifier(),
                                character,
                                offset,
                            }
                            .stable_code(),
                        )
                        .with_segment(segment.tag())
                        .with_span(*span)
                        .with_element_index(element_index)
                        .with_component_index(component_index)
                        .with_layer(ValidationLayer::Charset)
                        .with_kind(FindingKind::Charset)
                        .with_suggestion(
                            "Transliterate the value, or declare a wider repertoire in UNB S001 \
                             (UNOC for Latin-1, UNOY for UTF-8)",
                        );
                        if let Some(position) = position {
                            issue = issue.with_segment_position(position);
                        }
                        report.add_error(issue);
                    }
                }
            }
        }
    }

    fn fork(&self) -> Option<Box<dyn Validator + Send + Sync>> {
        Some(Box::new(Self {
            charset: self.charset,
        }))
    }
}

// ── PlacementValidator ────────────────────────────────────────────────────────

/// Resolves each message against a [`GroupSchema`][crate::group::GroupSchema]
/// and reports what does not fit: unplaced segments, places and groups beyond
/// their `max`, places and groups below their `min`.
///
/// The issues are exactly
/// [`GroupResolution::findings`][crate::group::GroupResolution::findings], with
/// layer [`Structure`](ValidationLayer::Structure) — register it under that
/// layer. Give it the message (`UNH` to `UNT`) the schema describes: with the
/// envelope layer on, the context already hides `UNB`/`UNZ`/`UNG`/`UNE`.
///
/// # Example
///
/// ```
/// use std::sync::Arc;
/// use edifact::group::{Entry, GroupSchema, SegmentPlace};
/// use edifact::{FindingKind, PlacementValidator, ValidationContext, ValidationLayer};
///
/// let schema = GroupSchema::ordered(
///     "MSG",
///     ["UNH", "BGM", "UNT"].map(|t| Entry::Segment(SegmentPlace::new(t).with_min(1).with_max(1))),
/// )?;
/// let ctx = ValidationContext::builder()
///     .with_validator(ValidationLayer::Structure, PlacementValidator::new(Arc::new(schema)))
///     .build();
///
/// let segments: Vec<_> = edifact::from_bytes(b"UNH+1+X:D:11A:UN'DTM+137:1:102'BGM+220'UNT+4+1'")
///     .collect::<Result<_, _>>()?;
/// let report = ctx.validate(&segments);
/// let issue = &report.errors()[0];
/// assert_eq!(issue.kind(), Some(FindingKind::Placement));
/// assert_eq!(issue.segment_position(), Some(2));
/// # Ok::<(), edifact::EdifactError>(())
/// ```
#[derive(Debug, Clone)]
pub struct PlacementValidator {
    schema: std::sync::Arc<crate::group::GroupSchema>,
}

impl PlacementValidator {
    /// A validator resolving against `schema`.
    #[must_use]
    pub fn new(schema: std::sync::Arc<crate::group::GroupSchema>) -> Self {
        Self { schema }
    }

    /// The schema this validator resolves against.
    #[must_use]
    pub fn schema(&self) -> &crate::group::GroupSchema {
        &self.schema
    }
}

impl Validator for PlacementValidator {
    fn validate_batch(
        &self,
        segments: &[Segment<'_>],
        report: &mut ValidationReport,
        _context: &ValidationRuleContext<'_>,
    ) {
        for issue in self.schema.resolve(segments).findings(segments) {
            push_issue(report, issue);
        }
    }

    fn fork(&self) -> Option<Box<dyn Validator + Send + Sync>> {
        Some(Box::new(self.clone()))
    }
}

pub(crate) fn issue_from_error(err: EdifactError) -> ValidationIssue {
    let code = err.stable_code();
    let mut issue = ValidationIssue::new(crate::report::severity_for_error(&err), err.to_string())
        .with_error_code(code)
        .with_kind(FindingKind::for_error(&err));
    let default_hint = err.recovery_hint();

    match err {
        EdifactError::InvalidSegmentForMessage { tag, span, .. } => {
            issue = issue.with_segment(tag).with_span(span);
        }
        EdifactError::InvalidElementCount { tag, span, .. } => {
            issue = issue.with_segment(tag).with_span(span);
        }
        EdifactError::InvalidComponentCount {
            tag,
            element_index,
            span,
            ..
        } => {
            issue = issue
                .with_segment(tag)
                .with_element_index(element_index)
                .with_span(span);
        }
        EdifactError::InvalidCodeValue {
            tag,
            element_index,
            span,
            suggestion,
            ..
        } => {
            issue = issue
                .with_segment(tag)
                .with_element_index(element_index)
                .with_span(span);
            if let Some(s) = suggestion {
                issue = issue.with_suggestion(s);
            }
        }
        EdifactError::MissingSegment { tag, .. } => {
            issue = issue.with_segment(tag);
        }
        EdifactError::SegmentNotPlaced { tag, span, .. }
        | EdifactError::TooManySegmentOccurrences { tag, span, .. } => {
            issue = issue.with_segment(tag).with_span(span);
        }
        EdifactError::TooManyGroupOccurrences { group, span, .. } => {
            issue = issue.with_segment_group(group).with_span(span);
        }
        // The error names the segment, not an element: an index invented here
        // would become a wrong S011 on the CONTRL that reports it.
        EdifactError::QualifierMismatch { tag, span, .. } => {
            issue = issue.with_segment(tag).with_span(span);
        }
        EdifactError::ConditionalRequirementNotMet {
            tag,
            element_index,
            span,
            ..
        } => {
            issue = issue
                .with_segment(tag)
                .with_element_index(element_index)
                .with_span(span);
        }
        EdifactError::DuplicateReference { tag, span, .. }
        | EdifactError::PackageNotSupported { tag, span }
        | EdifactError::SegmentWithoutDataElements { tag, span } => {
            issue = issue.with_segment(tag).with_span(span);
        }
        EdifactError::EmptyMessage { span, .. } => {
            issue = issue.with_segment("UNH").with_span(span);
        }
        EdifactError::InteractiveSegmentNotSupported { tag, span }
        | EdifactError::SecuritySegmentNotSupported { tag, span }
        | EdifactError::ReservedServiceSegmentTag { tag, span }
        | EdifactError::DataAfterInterchangeTrailer { tag, span } => {
            issue = issue.with_segment(tag).with_span(span);
        }
        EdifactError::MessageCountMismatch { span, .. } => {
            issue = issue.with_segment("UNZ").with_span(span);
        }
        EdifactError::GroupCountMismatch { span, .. } => {
            issue = issue.with_segment("UNE").with_span(span);
        }
        EdifactError::EmptyGroup { span, .. } => {
            issue = issue.with_segment("UNG").with_span(span);
        }
        EdifactError::UnsupportedSyntaxVersion { span, .. } => {
            issue = issue
                .with_segment("UNB")
                .with_span(span)
                .with_element_index(0)
                .with_component_index(1);
        }
        EdifactError::GroupsAndMessagesMixed { span } => {
            issue = issue.with_segment("UNH").with_span(span);
        }
        EdifactError::TrailingSeparator {
            tag,
            element_index,
            span,
        } => {
            issue = issue.with_segment(tag).with_span(span);
            if let Some(index) = element_index {
                issue = issue.with_element_index(index);
            }
        }
        // The trailer is what got the count wrong, and carrying its span is what
        // places the finding on that message rather than on the interchange.
        EdifactError::SegmentCountMismatch {
            span, message_ref, ..
        } => {
            issue = issue
                .with_segment("UNT")
                .with_span(span)
                .with_message_ref(message_ref);
        }
        EdifactError::TooManyRepetitions {
            tag,
            element_index,
            span,
            ..
        } => {
            issue = issue
                .with_segment(tag)
                .with_span(span)
                .with_element_index(element_index);
        }
        EdifactError::InvalidCharacterType {
            tag,
            element_index,
            component_index,
            span,
            ..
        }
        | EdifactError::DataElementTooLong {
            tag,
            element_index,
            component_index,
            span,
            ..
        }
        | EdifactError::DataElementTooShort {
            tag,
            element_index,
            component_index,
            span,
            ..
        }
        | EdifactError::InsignificantCharacters {
            tag,
            element_index,
            component_index,
            span,
            ..
        }
        | EdifactError::BlankDataElementValue {
            tag,
            element_index,
            component_index,
            span,
        }
        | EdifactError::InvalidDateTime {
            tag,
            element_index,
            component_index,
            span,
            ..
        } => {
            issue = issue
                .with_segment(tag)
                .with_span(span)
                .with_element_index(element_index)
                .with_component_index(component_index);
        }
        EdifactError::MissingRequiredElement { tag, element_index } => {
            issue = issue.with_segment(tag).with_element_index(element_index);
        }
        EdifactError::MissingRequiredComponent {
            tag,
            element_index,
            component_index,
        } => {
            issue = issue
                .with_segment(tag)
                .with_element_index(element_index)
                .with_component_index(component_index);
        }
        // Lexical faults are a point in the byte stream, not a range: record a
        // zero-width span so `span` stays the single positional field.
        EdifactError::InvalidReleaseSequence { offset }
        | EdifactError::InvalidDelimiter { offset, .. }
        | EdifactError::InvalidText { offset }
        | EdifactError::UnexpectedEof { offset }
        | EdifactError::UnexpectedDataToken { offset }
        | EdifactError::SegmentTooLong { offset, .. }
        | EdifactError::LimitExceeded { offset, .. } => {
            issue = issue.with_span(Span::new(offset, offset));
        }
        _ => {}
    }

    if issue.suggestion.is_none()
        && let Some(hint) = default_hint
    {
        issue = issue.with_suggestion(hint);
    }

    issue
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::Element;

    fn demo_orders_profile_pack() -> ProfileRulePack {
        ProfileRulePack::new("ORDERS-DEMO")
            .for_message_type("ORDERS")
            .with_rule_fn(|segments, issues| {
                issues.extend((|| -> Option<ValidationIssue> {
                    let bgm = segments.iter().find(|segment| segment.tag == "BGM")?;
                    let document_code = bgm.get_element(0)?.get_component(0)?;
                    (document_code == "220").then(|| {
                        ValidationIssue::new(
                            ValidationSeverity::Error,
                            "profile rule DEMO-P001 violated: BGM document code 220 is rejected in this demo pack",
                        )
                        .with_rule_id("DEMO-P001")
                        .with_segment("BGM")
                        .with_element_index(0)
                        .with_suggestion("Use a different BGM document code in this demo pack")
                    })
                })());
            })
            .with_rule_fn(|segments, issues| {
                issues.extend((|| -> Option<ValidationIssue> {
                    let bgm = segments.iter().find(|segment| segment.tag == "BGM")?;
                    let reference = bgm.get_element(1)?.get_component(0)?;
                    (reference == "PO123").then(|| {
                        ValidationIssue::new(
                            ValidationSeverity::Warning,
                            "profile rule DEMO-P002 warning: purchase-order reference PO123 is reserved in this demo pack",
                        )
                        .with_rule_id("DEMO-P002")
                        .with_segment("BGM")
                        .with_element_index(1)
                        .with_suggestion("Use a non-reserved reference in this demo pack")
                    })
                })());
            })
    }

    fn positions_of(input: &[u8]) -> Vec<Option<usize>> {
        let segments: Vec<_> = crate::from_bytes(input)
            .collect::<Result<_, _>>()
            .expect("valid input");
        let positions = MessagePositions::new(&segments);
        (0..segments.len()).map(|i| positions.position(i)).collect()
    }

    #[test]
    fn message_positions_count_from_each_unh() {
        assert_eq!(
            positions_of(b"UNH+1+X:D:96A:UN'BGM+1'UNT+3+1'"),
            [Some(1), Some(2), Some(3)]
        );
        assert_eq!(
            positions_of(
                b"UNB+UNOC:3+S+R+260101:0900+1'UNH+1+X:D:96A:UN'BGM+1'UNT+3+1'\
                  UNH+2+X:D:96A:UN'BGM+2'UNT+3+2'UNZ+2+1'"
            ),
            [
                None,
                Some(1),
                Some(2),
                Some(3),
                Some(1),
                Some(2),
                Some(3),
                None
            ]
        );
        // An unterminated message ends before the next `UNH`.
        assert_eq!(
            positions_of(b"UNH+1+X:D:96A:UN'BGM+1'UNH+2+X:D:96A:UN'BGM+2'"),
            [Some(1), Some(2), Some(1), Some(2)]
        );
        assert_eq!(positions_of(b"BGM+1'DTM+1'"), [None, None]);
        assert_eq!(positions_of(b""), []);
    }

    struct RejectBgm;

    struct WarnBgm;

    impl Validator for RejectBgm {
        fn validate_batch(
            &self,
            segments: &[Segment<'_>],
            report: &mut ValidationReport,
            _context: &ValidationRuleContext<'_>,
        ) {
            validate_each(segments, report, |segment| {
                if segment.tag == "BGM" {
                    return Err(EdifactError::InvalidSegmentForMessage {
                        tag: "BGM".to_owned(),
                        message_type: "TEST".to_owned(),
                        span: segment.tag_span,
                    });
                }
                Ok(())
            });
        }
    }

    impl Validator for WarnBgm {
        fn validate_batch(
            &self,
            segments: &[Segment<'_>],
            report: &mut ValidationReport,
            _context: &ValidationRuleContext<'_>,
        ) {
            validate_each(segments, report, |segment| {
                if segment.tag == "BGM" {
                    return Err(EdifactError::InvalidCodeValue {
                        tag: "BGM".to_owned(),
                        element_index: 0,
                        value: "XXX".to_owned(),
                        code_list: "1001".to_owned(),
                        span: segment.span,
                        suggestion: None,
                    });
                }
                Ok(())
            });
        }
    }

    fn test_segment(tag: &'static str) -> Segment<'static> {
        Segment::new(tag, vec![Element::of(&["x"])])
    }

    #[test]
    fn lenient_collects_issues() {
        let segments = vec![test_segment("UNH"), test_segment("BGM")];
        let mut report = ValidationReport::default();
        RejectBgm.validate_batch(&segments, &mut report, &ValidationRuleContext::empty());
        assert!(report.has_errors());
        assert_eq!(report.errors().len(), 1);
    }

    #[test]
    fn strict_fails_on_errors() {
        let segments = vec![test_segment("BGM")];
        let mut report = ValidationReport::default();
        RejectBgm.validate_batch(&segments, &mut report, &ValidationRuleContext::empty());
        assert!(report.has_errors());
        assert_eq!(report.errors().len(), 1);
    }

    #[test]
    fn context_builder_respects_layer_toggles() {
        let segments = vec![test_segment("BGM")];
        let ctx = ValidationContext::builder()
            .structure(false)
            .with_validator(ValidationLayer::Structure, RejectBgm)
            .with_validator(ValidationLayer::CodeList, WarnBgm)
            .build();

        let report = ctx.validate(&segments);
        assert!(!report.has_errors());
        assert_eq!(report.warnings().len(), 1);
    }

    #[test]
    fn context_strict_fails_when_structure_enabled() {
        let segments = vec![test_segment("BGM")];
        let ctx = ValidationContext::builder()
            .with_message_type("ORDERS")
            .with_validator(ValidationLayer::Structure, RejectBgm)
            .build();

        assert_eq!(ctx.message_type(), Some("ORDERS"));
        let result = ctx.validate(&segments).result();
        assert!(result.is_err());
        assert!(result.unwrap_err().has_errors());
    }

    #[test]
    fn report_error_applies_default_recovery_hint() {
        let mut report = ValidationReport::default();
        report_error(
            &mut report,
            EdifactError::InvalidReleaseSequence { offset: 9 },
        );

        let issue = report
            .errors()
            .first()
            .expect("expected one issue in the report");
        let hint = issue
            .suggestion
            .as_deref()
            .expect("expected default hint to be set");
        assert!(hint.contains("Release character"));
        assert_eq!(issue.error_code(), Some("E019"));
    }

    #[test]
    fn missing_required_component_maps_metadata_to_issue() {
        let mut report = ValidationReport::default();
        report_error(
            &mut report,
            EdifactError::MissingRequiredComponent {
                tag: "BGM".to_owned(),
                element_index: 2,
                component_index: 1,
            },
        );

        let issue = report.errors().first().expect("expected one issue");
        assert_eq!(issue.error_code(), Some("E021"));
        assert_eq!(issue.segment_tag.as_deref(), Some("BGM"));
        assert_eq!(issue.element_index, Some(2));
        assert_eq!(issue.component_index, Some(1));
    }

    #[test]
    fn profile_pack_lenient_collects_profile_rule_issues() {
        let input = b"UNH+1+ORDERS:D:96A:UN'BGM+220+PO123+9'UNT+3+1'";
        let segments = crate::from_bytes(input)
            .collect::<Result<Vec<_>, _>>()
            .expect("expected parse success");

        let ctx = ValidationContext::builder()
            .with_profile_pack(demo_orders_profile_pack())
            .build();

        let report = ctx.validate(&segments);
        assert!(report.has_errors());
        assert!(
            report
                .errors()
                .iter()
                .any(|issue| issue.rule_id.as_deref() == Some("DEMO-P001"))
        );
        assert!(
            report
                .warnings()
                .iter()
                .any(|issue| issue.rule_id.as_deref() == Some("DEMO-P002"))
        );
    }

    #[test]
    fn profile_pack_strict_fails_when_profile_errors_exist() {
        let input = b"UNH+1+ORDERS:D:96A:UN'BGM+220+PO123+9'UNT+3+1'";
        let segments = crate::from_bytes(input)
            .collect::<Result<Vec<_>, _>>()
            .expect("expected parse success");

        let ctx = ValidationContext::builder()
            .with_profile_pack(demo_orders_profile_pack())
            .build();
        let result = ctx.validate(&segments).result();
        assert!(result.is_err());
        assert!(result.unwrap_err().has_errors());
    }

    // ── bail_on_first_error ──────────────────────────────────────────────────

    /// A rule that emits two error-severity issues (one per DTM segment).
    fn two_dtm_errors_rule() -> ProfileRulePack {
        ProfileRulePack::new("TEST-BAIL")
            .with_rule_fn(|segments, issues| {
                // Rule A: emits one error per DTM segment.
                for seg in segments.iter().filter(|s| s.tag == "DTM") {
                    issues.push(
                        ValidationIssue::new(
                            ValidationSeverity::Error,
                            format!("DTM error at offset {}", seg.span.start),
                        )
                        .with_rule_id("BAIL-R1")
                        .with_segment("DTM"),
                    );
                }
            })
            .with_rule_fn(|segments, issues| {
                // Rule B: never fires; used to verify bail skips this rule.
                for seg in segments.iter().filter(|s| s.tag == "BGM") {
                    issues.push(
                        ValidationIssue::new(ValidationSeverity::Error, "BGM error")
                            .with_rule_id("BAIL-R2")
                            .with_segment(seg.tag()),
                    );
                }
            })
    }

    #[test]
    fn bail_on_first_error_fires_at_rule_invocation_granularity() {
        // Two DTM segments → Rule A emits 2 errors for them.
        // With bail, Rule B (BGM check) must NOT run.
        let input =
            b"UNH+1+ORDERS:D:96A:UN'BGM+220+9'DTM+137:20240101:102'DTM+163:20240201:102'UNT+5+1'";
        let segments = crate::from_bytes(input)
            .collect::<Result<Vec<_>, _>>()
            .expect("parse failed");

        let pack_with_bail = two_dtm_errors_rule().with_bail_on_first_error(true);
        let ctx = ValidationContext::builder()
            .with_profile_pack(pack_with_bail)
            .build();
        let report = ctx.validate(&segments);

        // Rule A fires: both DTM errors are in the report (the whole rule invocation
        // runs to completion before bail is checked).
        assert_eq!(
            report
                .errors()
                .iter()
                .filter(|i| i.rule_id.as_deref() == Some("BAIL-R1"))
                .count(),
            2,
            "both DTM errors from Rule A should be present"
        );
        // Bail fired after Rule A: Rule B (BGM) must be skipped.
        assert_eq!(
            report
                .errors()
                .iter()
                .filter(|i| i.rule_id.as_deref() == Some("BAIL-R2"))
                .count(),
            0,
            "Rule B should have been skipped by bail"
        );
    }

    #[test]
    fn bail_disabled_runs_all_rules() {
        let input = b"UNH+1+ORDERS:D:96A:UN'BGM+220+9'DTM+137:20240101:102'UNT+4+1'";
        let segments = crate::from_bytes(input)
            .collect::<Result<Vec<_>, _>>()
            .expect("parse failed");

        let pack_no_bail = two_dtm_errors_rule(); // bail_on_first_error defaults to false
        let ctx = ValidationContext::builder()
            .with_profile_pack(pack_no_bail)
            .build();
        let report = ctx.validate(&segments);

        // Both rules run: one DTM error from Rule A, one BGM error from Rule B.
        assert_eq!(
            report
                .errors()
                .iter()
                .filter(|i| i.rule_id.as_deref() == Some("BAIL-R1"))
                .count(),
            1
        );
        assert_eq!(
            report
                .errors()
                .iter()
                .filter(|i| i.rule_id.as_deref() == Some("BAIL-R2"))
                .count(),
            1
        );
    }

    // ── message_ref in ValidationRuleContext ─────────────────────────────────

    #[test]
    fn message_ref_is_visible_inside_rule_closure() {
        let input = b"UNH+MSG001+ORDERS:D:96A:UN'BGM+220+9'UNT+3+1'";
        let segments = crate::from_bytes(input)
            .collect::<Result<Vec<_>, _>>()
            .expect("parse failed");

        let pack =
            ProfileRulePack::new("MSG-REF-TEST").with_contextual_rule_fn(|_segs, ctx, issues| {
                if let Some(mref) = ctx.message_ref {
                    issues.push(
                        ValidationIssue::new(
                            ValidationSeverity::Info,
                            format!("validating message {mref}"),
                        )
                        .with_rule_id("CTX-REF"),
                    );
                }
            });

        let ctx = ValidationContext::builder()
            .with_profile_pack(pack)
            .with_message_ref("MSG001")
            .build();

        let report = ctx.validate(&segments);
        let info = report
            .infos()
            .iter()
            .find(|i| i.rule_id.as_deref() == Some("CTX-REF"))
            .expect("expected info issue from CTX-REF rule");
        assert!(info.message.contains("MSG001"));
        // The message_ref is also stamped onto the issue itself.
        assert_eq!(info.message_ref.as_deref(), Some("MSG001"));
    }
}