mig-assembly 0.33.0

MIG-guided EDIFACT tree assembly — parse RawSegments into typed MIG trees
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
//! Structure check: an assembled message against the MIG's statuses and
//! repetition limits.
//!
//! The assembler places what a message contains; it never asks what the MIG
//! demands. This pass does, for every segment and group of the PID:
//!
//! - a segment or group variant the MIG marks mandatory (`M` / `R`) that is
//!   absent — [`MissingRequiredSegment`], [`MissingRequiredGroup`];
//! - a segment or group variant repeating more often than its `MaxRep` —
//!   [`MaxRepetitionsExceeded`], [`GroupMaxRepetitionsExceeded`].
//!
//! It runs on the PID's **unmerged** view of the MIG
//! ([`filter_mig_for_pid_unmerged`](crate::pid_filter::filter_mig_for_pid_unmerged)).
//! The assembler's MIG merges the variants of a group (all SG8 `SEQ` variants
//! into one definition) and with them their statuses and limits; judged
//! against that, a segment one variant requires would be missing from every
//! repetition of another. Here each group repetition is judged by its own
//! variant, identified by its entry segment's qualifier.
//!
//! A segment counts against the slot whose qualifier it carries, else against
//! an unqualified slot of its tag. When every slot of its tag names qualifiers
//! and the segment carries another one, no slot here can hold it:
//! [`UnrecognizedQualifier`]. Slots of one tag and qualifier pool their
//! minimum and maximum; a MIG example code (`XYZ`) names no qualifier.
//!
//! Every finding carries the input counter of a segment that is there
//! ([`StructureDiagnostic::position`]), so a CONTRL can name it (UCS 0096).
//! A missing segment or group is reported at its predecessor: the last
//! segment of its scope that the MIG places before it (by MIG `Number`), or
//! the scope's entry segment when none does.
//!
//! [`MissingRequiredSegment`]: StructureDiagnosticKind::MissingRequiredSegment
//! [`MissingRequiredGroup`]: StructureDiagnosticKind::MissingRequiredGroup
//! [`MaxRepetitionsExceeded`]: StructureDiagnosticKind::MaxRepetitionsExceeded
//! [`GroupMaxRepetitionsExceeded`]: StructureDiagnosticKind::GroupMaxRepetitionsExceeded
//! [`UnrecognizedQualifier`]: StructureDiagnosticKind::UnrecognizedQualifier

use mig_types::schema::common::Cardinality;
use mig_types::schema::mig::{MigSchema, MigSegment, MigSegmentGroup};

use crate::assembler::{AssembledGroup, AssembledGroupInstance, AssembledSegment, AssembledTree};
use crate::diagnostic::{StructureDiagnostic, StructureDiagnosticKind};

/// Check `tree` against `pid_mig`, the PID's unmerged view of the MIG.
pub fn check_structure(tree: &AssembledTree, pid_mig: &MigSchema) -> Vec<StructureDiagnostic> {
    let mut out = Vec::new();
    let mut root: Vec<&AssembledSegment> = tree.segments.iter().collect();
    root.extend(tree.inter_group_segments.values().flatten());
    let mut whole = root.clone();
    for group in &tree.groups {
        collect_segments(group, &mut whole);
    }
    let scope = Scope {
        name: "message",
        position: root.iter().map(|s| position(s)).min().unwrap_or(0),
        segments: &whole,
    };
    check_segments(&root, &pid_mig.segments, &scope, &mut out);
    check_groups(&tree.groups, &pid_mig.segment_groups, &scope, &mut out);
    out.sort_by_key(|d| d.position);
    out
}

/// Whether a MIG status demands presence: `M` (mandatory) or `R` (required).
fn is_required(status_spec: Option<&str>, status_std: Option<&str>) -> bool {
    let status = status_spec.or(status_std).unwrap_or("C");
    matches!(
        Cardinality::from_status(status),
        Cardinality::Mandatory | Cardinality::Required
    )
}

/// The BDEW limit (`MaxRep_Specification`) where given, else the standard's.
/// `None`: unbounded (no limit in the MIG).
fn max_rep(spec: i32, std: i32) -> Option<usize> {
    [spec, std].into_iter().find(|&n| n > 0).map(|n| n as usize)
}

/// A MIG example code (`<Code Name="Beispielcode">XYZ</Code>`): stands for any
/// value, so it names no qualifier.
fn is_placeholder(code: &mig_types::schema::common::CodeDefinition) -> bool {
    code.name == "Beispielcode" || code.value == "XYZ"
}

/// A segment's qualifier: its first coded data element, as
/// `(element, component, codes)`. The same rule identifies a group variant by
/// its entry segment (`MigSegmentGroup::entry_qualifier`). A code list of
/// placeholders only (`XYZ`) is no qualifier.
fn qualifier(seg: &MigSegment) -> Option<(usize, usize, Vec<String>)> {
    let simple = seg.data_elements.iter().map(|d| (d.position, 0, d));
    let composite = seg.composites.iter().flat_map(|c| {
        c.data_elements
            .iter()
            .map(move |d| (c.position, d.position, d))
    });
    simple
        .chain(composite)
        .filter(|(_, _, d)| d.codes.iter().any(|c| !c.value.is_empty()))
        .min_by_key(|(e, c, _)| (*e, *c))
        .and_then(|(e, c, d)| {
            let codes: Vec<String> = d
                .codes
                .iter()
                .filter(|c| !c.value.is_empty() && !is_placeholder(c))
                .map(|c| c.value.clone())
                .collect();
            (!codes.is_empty()).then_some((e, c, codes))
        })
}

/// The value a segment carries at a qualifier position, when non-empty.
fn value_at<'s>(elements: &'s [Vec<String>], q: &(usize, usize, Vec<String>)) -> Option<&'s str> {
    let (e, c, _) = q;
    elements
        .get(*e)
        .and_then(|el| el.get(*c))
        .map(String::as_str)
        .filter(|v| !v.is_empty())
}

fn carries(elements: &[Vec<String>], q: &(usize, usize, Vec<String>)) -> bool {
    let (e, c, codes) = q;
    elements
        .get(*e)
        .and_then(|el| el.get(*c))
        .is_some_and(|v| codes.iter().any(|code| code == v))
}

/// Slots of one tag and qualifier, pooled.
struct Pool<'m> {
    tag: &'m str,
    qualifier: Option<(usize, usize, Vec<String>)>,
    /// MIG `Number` of the pool's first slot.
    number: Option<&'m str>,
    required: usize,
    /// `None`: unbounded.
    max: Option<usize>,
    count: usize,
    /// Input position of the first segment beyond `max`.
    first_excess: Option<usize>,
}

fn position(seg: &AssembledSegment) -> usize {
    seg.segment_number.map_or(0, |n| n as usize)
}

/// Where a check runs: a message or one group repetition.
struct Scope<'a, 't> {
    /// For messages: "message", or the group variant.
    name: &'a str,
    /// The counter of the scope's first segment (a group's entry segment).
    position: usize,
    /// Every segment of the scope, its nested groups' included.
    segments: &'a [&'t AssembledSegment],
}

impl Scope<'_, '_> {
    /// The counter a missing segment or group is reported at: the last
    /// segment of this scope whose MIG `Number` lies before `number` (the
    /// missing slot's, or the missing group's first segment's), else the
    /// scope's first segment.
    fn predecessor(&self, number: Option<&str>) -> usize {
        let Some(number) = number.and_then(mig_number) else {
            return self.position;
        };
        self.segments
            .iter()
            .filter(|s| {
                s.mig_number
                    .as_deref()
                    .and_then(mig_number)
                    .is_some_and(|n| n < number)
            })
            .map(|s| position(s))
            .max()
            .unwrap_or(self.position)
    }
}

fn mig_number(number: &str) -> Option<u32> {
    number.trim().parse().ok()
}

/// Every segment of `group`'s repetitions, nested groups included.
fn collect_segments<'t>(group: &'t AssembledGroup, out: &mut Vec<&'t AssembledSegment>) {
    for rep in &group.repetitions {
        collect_rep_segments(rep, out);
    }
}

fn collect_rep_segments<'t>(rep: &'t AssembledGroupInstance, out: &mut Vec<&'t AssembledSegment>) {
    out.extend(&rep.segments);
    for child in &rep.child_groups {
        collect_segments(child, out);
    }
}

fn count(p: &mut Pool, seg: &AssembledSegment) {
    p.count += 1;
    if p.max.is_some_and(|m| p.count > m) && p.first_excess.is_none() {
        p.first_excess = Some(position(seg));
    }
}

fn check_segments(
    present: &[&AssembledSegment],
    slots: &[MigSegment],
    scope: &Scope,
    out: &mut Vec<StructureDiagnostic>,
) {
    let mut pools: Vec<Pool> = Vec::new();
    for slot in slots {
        let q = qualifier(slot);
        let required = usize::from(is_required(
            slot.status_spec.as_deref(),
            slot.status_std.as_deref(),
        ));
        let max = max_rep(slot.max_rep_spec, slot.max_rep_std);
        match pools
            .iter_mut()
            .find(|p| p.tag == slot.id && p.qualifier == q)
        {
            Some(p) => {
                p.required += required;
                p.max = p.max.zip(max).map(|(a, b)| a + b);
            }
            None => pools.push(Pool {
                tag: &slot.id,
                qualifier: q,
                number: slot.number.as_deref(),
                required,
                max,
                count: 0,
                first_excess: None,
            }),
        }
    }
    for seg in present {
        let pool = pools
            .iter()
            .position(|p| {
                p.tag == seg.tag
                    && p.qualifier
                        .as_ref()
                        .is_some_and(|q| carries(&seg.elements, q))
            })
            .or_else(|| {
                pools
                    .iter()
                    .position(|p| p.tag == seg.tag && p.qualifier.is_none())
            });
        let Some(i) = pool else {
            // Every slot of this tag names its qualifiers and the segment
            // carries none of them: no slot here can hold it. An empty
            // qualifier element is not a wrong one — count the segment for
            // the first slot of its tag then (e.g. CONTRL `UCS` without an
            // error code).
            let tagged: Vec<&Pool> = pools.iter().filter(|p| p.tag == seg.tag).collect();
            let carried = tagged.iter().find_map(|p| {
                p.qualifier
                    .as_ref()
                    .and_then(|q| value_at(&seg.elements, q))
            });
            match carried {
                Some(value) => {
                    let mut allowed: Vec<&str> = Vec::new();
                    for code in tagged
                        .iter()
                        .filter_map(|p| p.qualifier.as_ref())
                        .flat_map(|(_, _, codes)| codes.iter().map(String::as_str))
                    {
                        if !allowed.contains(&code) {
                            allowed.push(code);
                        }
                    }
                    out.push(StructureDiagnostic {
                        kind: StructureDiagnosticKind::UnrecognizedQualifier,
                        segment_id: seg.tag.clone(),
                        position: position(seg),
                        message: format!(
                            "Segment '{}+{value}' is not allowed in {}: the MIG allows {} here",
                            seg.tag,
                            scope.name,
                            allowed
                                .iter()
                                .map(|c| format!("{}+{c}", seg.tag))
                                .collect::<Vec<_>>()
                                .join(", ")
                        ),
                    });
                    // With one slot of its tag here, the segment is that
                    // slot's, with a wrong qualifier: it is not also missing.
                    // (It fills a required slot, never one beyond MaxRep.)
                    if tagged.len() == 1 {
                        if let Some(p) = pools
                            .iter_mut()
                            .find(|p| p.tag == seg.tag && p.count < p.required)
                        {
                            p.count += 1;
                        }
                    }
                }
                None => {
                    if let Some(i) = pools.iter().position(|p| p.tag == seg.tag) {
                        count(&mut pools[i], seg);
                    }
                }
            }
            continue;
        };
        count(&mut pools[i], seg);
    }
    for p in &pools {
        let name = match &p.qualifier {
            Some((_, _, codes)) if codes.len() == 1 => format!("{}+{}", p.tag, codes[0]),
            _ => p.tag.to_string(),
        };
        if p.count < p.required {
            out.push(StructureDiagnostic {
                kind: StructureDiagnosticKind::MissingRequiredSegment,
                segment_id: p.tag.to_string(),
                position: scope.predecessor(p.number),
                message: format!(
                    "Mandatory segment '{name}' is missing in {} (found {}, required {})",
                    scope.name, p.count, p.required
                ),
            });
        }
        if let (Some(max), Some(at)) = (p.max, p.first_excess) {
            out.push(StructureDiagnostic {
                kind: StructureDiagnosticKind::MaxRepetitionsExceeded,
                segment_id: p.tag.to_string(),
                position: at,
                message: format!(
                    "Segment '{name}' repeats {} times in {}, the MIG allows {max}",
                    p.count, scope.name
                ),
            });
        }
    }
}

/// The variants of `variants` (all of one group id) a repetition may belong
/// to: the only one, or those whose entry qualifier its entry segment
/// carries. A whole MIG can hold several variants with one entry qualifier
/// (UTILMD SG8 `SEQ+Z22`, with `RFF+AVE` in one and `RFF+AUU` in the other).
fn variants_of<'m>(
    rep: &AssembledGroupInstance,
    variants: &[&'m MigSegmentGroup],
) -> Vec<&'m MigSegmentGroup> {
    if variants.len() == 1 {
        return vec![variants[0]];
    }
    let Some(entry) = rep.segments.first() else {
        return Vec::new();
    };
    variants
        .iter()
        .copied()
        .filter(|v| {
            v.entry_qualifier()
                .is_some_and(|q| q.tag == entry.tag && q.matches(&entry.elements))
        })
        .collect()
}

fn describe(variant: &MigSegmentGroup) -> String {
    match variant.entry_qualifier() {
        Some(q) if q.codes.len() == 1 => format!("{} ({}+{})", variant.id, q.tag, q.codes[0]),
        Some(q) => format!("{} ({}+{})", variant.id, q.tag, q.codes.join("|")),
        None => variant.id.clone(),
    }
}

/// Check one group repetition against `variant`.
fn check_repetition(
    rep: &AssembledGroupInstance,
    variant: &MigSegmentGroup,
    scope: &Scope,
    out: &mut Vec<StructureDiagnostic>,
) {
    let at = rep.segments.first().map_or(scope.position, position);
    let name = describe(variant);
    let own: Vec<&AssembledSegment> = rep.segments.iter().collect();
    let mut all = Vec::new();
    collect_rep_segments(rep, &mut all);
    let inner = Scope {
        name: &name,
        position: at,
        segments: &all,
    };
    check_segments(&own, &variant.segments, &inner, out);
    check_groups(&rep.child_groups, &variant.nested_groups, &inner, out);
}

fn check_groups(
    present: &[AssembledGroup],
    variants: &[MigSegmentGroup],
    scope: &Scope,
    out: &mut Vec<StructureDiagnostic>,
) {
    // Per variant (by index into `variants`): repetitions, first beyond max.
    let mut counts = vec![0usize; variants.len()];
    let mut first_excess: Vec<Option<usize>> = vec![None; variants.len()];
    for group in present {
        let same_id: Vec<&MigSegmentGroup> =
            variants.iter().filter(|v| v.id == group.group_id).collect();
        for rep in &group.repetitions {
            // Of several candidate variants, the one the repetition fits best.
            let mut best: Option<(&MigSegmentGroup, Vec<StructureDiagnostic>)> = None;
            for variant in variants_of(rep, &same_id) {
                let mut found = Vec::new();
                check_repetition(rep, variant, scope, &mut found);
                if best.as_ref().map_or(true, |(_, b)| found.len() < b.len()) {
                    best = Some((variant, found));
                }
            }
            let Some((variant, found)) = best else {
                continue;
            };
            out.extend(found);
            let i = variants
                .iter()
                .position(|v| std::ptr::eq(v, variant))
                .expect("variant is one of `variants`");
            counts[i] += 1;
            let max = max_rep(variant.max_rep_spec, variant.max_rep_std);
            let at = rep.segments.first().map_or(scope.position, position);
            if max.is_some_and(|m| counts[i] > m) && first_excess[i].is_none() {
                first_excess[i] = Some(at);
            }
        }
    }
    for (i, variant) in variants.iter().enumerate() {
        let name = describe(variant);
        if counts[i] == 0
            && is_required(
                variant.status_spec.as_deref(),
                variant.status_std.as_deref(),
            )
        {
            out.push(StructureDiagnostic {
                kind: StructureDiagnosticKind::MissingRequiredGroup,
                segment_id: variant.id.clone(),
                position: scope
                    .predecessor(variant.segments.first().and_then(|s| s.number.as_deref())),
                message: format!("Mandatory group {name} is missing in {}", scope.name),
            });
        }
        if let (Some(max), Some(at)) = (
            max_rep(variant.max_rep_spec, variant.max_rep_std),
            first_excess[i],
        ) {
            out.push(StructureDiagnostic {
                kind: StructureDiagnosticKind::GroupMaxRepetitionsExceeded,
                segment_id: variant.id.clone(),
                position: at,
                message: format!(
                    "Group {name} repeats {} times in {}, the MIG allows {max}",
                    counts[i], scope.name
                ),
            });
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::{make_mig_group, make_mig_segment};
    use mig_types::schema::common::CodeDefinition;
    use mig_types::schema::mig::MigDataElement;

    /// A slot with `status` / `max`, qualified by `codes` at element 0.
    fn slot(tag: &str, status: &str, max: i32, codes: &[&str]) -> MigSegment {
        let mut s = make_mig_segment(tag);
        s.status_spec = Some(status.into());
        s.max_rep_spec = max;
        if !codes.is_empty() {
            s.data_elements = vec![MigDataElement {
                id: "q".into(),
                name: "q".into(),
                description: None,
                status_std: None,
                status_spec: None,
                format_std: None,
                format_spec: None,
                codes: codes
                    .iter()
                    .map(|c| CodeDefinition {
                        value: (*c).into(),
                        name: if *c == "XYZ" { "Beispielcode" } else { "code" }.into(),
                        description: None,
                    })
                    .collect(),
                position: 0,
            }];
        }
        s
    }

    fn group(id: &str, status: &str, max: i32, segments: Vec<MigSegment>) -> MigSegmentGroup {
        let mut g = make_mig_group(id, vec![], vec![]);
        g.status_spec = Some(status.into());
        g.max_rep_spec = max;
        g.segments = segments;
        g
    }

    /// UNH BGM; SG2 NAD+MS / NAD+MR (each required, once); SG8 SEQ+A needs
    /// RFF+Z13, SEQ+B has no RFF; DTM at most twice.
    fn mig() -> MigSchema {
        let seq_a = group(
            "SG8",
            "D",
            99,
            vec![
                slot("SEQ", "M", 1, &["A"]),
                slot("RFF", "R", 1, &["Z13"]),
                slot("DTM", "D", 2, &[]),
            ],
        );
        let seq_b = group("SG8", "D", 99, vec![slot("SEQ", "M", 1, &["B"])]);
        let mut sg4 = group("SG4", "M", 1, vec![slot("IDE", "M", 1, &[])]);
        sg4.nested_groups = vec![seq_a, seq_b];
        MigSchema {
            message_type: "TEST".into(),
            variant: None,
            version: String::new(),
            publication_date: String::new(),
            author: String::new(),
            format_version: "FV".into(),
            source_file: String::new(),
            segments: vec![slot("UNH", "M", 1, &[]), slot("BGM", "M", 1, &[])],
            segment_groups: vec![
                group("SG2", "R", 1, vec![slot("NAD", "M", 1, &["MS"])]),
                group("SG2", "R", 1, vec![slot("NAD", "M", 1, &["MR"])]),
                sg4,
            ],
        }
    }

    fn seg(tag: &str, qualifier: &str) -> AssembledSegment {
        AssembledSegment {
            tag: tag.into(),
            elements: vec![vec![qualifier.into()]],
            mig_number: None,
            segment_number: Some(1),
        }
    }

    fn rep(
        segments: Vec<AssembledSegment>,
        children: Vec<AssembledGroup>,
    ) -> AssembledGroupInstance {
        AssembledGroupInstance {
            segments,
            child_groups: children,
            entry_mig_number: None,
            variant_mig_numbers: vec![],
            skipped_segments: vec![],
            skipped_positions: vec![],
        }
    }

    fn grp(id: &str, reps: Vec<AssembledGroupInstance>) -> AssembledGroup {
        AssembledGroup {
            group_id: id.into(),
            repetitions: reps,
        }
    }

    /// A clean message; `sg8` replaces its SG8 repetitions.
    fn tree(sg8: Vec<AssembledGroupInstance>) -> AssembledTree {
        let sg2 = grp(
            "SG2",
            vec![
                rep(vec![seg("NAD", "MS")], vec![]),
                rep(vec![seg("NAD", "MR")], vec![]),
            ],
        );
        let sg4 = grp(
            "SG4",
            vec![rep(vec![seg("IDE", "24")], vec![grp("SG8", sg8)])],
        );
        AssembledTree {
            segments: vec![seg("UNH", "1"), seg("BGM", "E01")],
            groups: vec![sg2, sg4],
            post_group_start: 2,
            inter_group_segments: Default::default(),
        }
    }

    fn kinds(t: &AssembledTree) -> Vec<(StructureDiagnosticKind, String)> {
        check_structure(t, &mig())
            .into_iter()
            .map(|d| (d.kind, d.message))
            .collect()
    }

    /// `seg`, at input counter `at`, in MIG slot `number`.
    fn numbered(tag: &str, qualifier: &str, number: &str, at: u32) -> AssembledSegment {
        AssembledSegment {
            mig_number: Some(number.into()),
            segment_number: Some(at),
            ..seg(tag, qualifier)
        }
    }

    #[test]
    fn a_missing_segment_or_group_is_reported_at_its_predecessor() {
        // MIG order: UNH 1, BGM 2, DTM 3 (missing), SG2 NAD 4, SG4 IDE 5,
        // SG8 SEQ 6, RFF 7 (missing in the 2nd SEQ+A).
        let mut m = mig();
        let numbers = [("UNH", "00001"), ("BGM", "00002")];
        for (slot, (_, n)) in m.segments.iter_mut().zip(numbers) {
            slot.number = Some(n.into());
        }
        let mut dtm = slot("DTM", "M", 1, &[]);
        dtm.number = Some("00003".into());
        m.segments.push(dtm);
        m.segment_groups[0].segments[0].number = Some("00004".into());
        m.segment_groups[1].segments[0].number = Some("00004".into());
        let sg4 = &mut m.segment_groups[2];
        sg4.segments[0].number = Some("00005".into());
        sg4.nested_groups[0].segments[0].number = Some("00006".into());
        sg4.nested_groups[0].segments[1].number = Some("00007".into());

        let t = AssembledTree {
            // Counter 1 is UNB.
            segments: vec![
                numbered("UNH", "1", "00001", 2),
                numbered("BGM", "E01", "00002", 3),
            ],
            groups: vec![
                // SG2 NAD+MR is missing.
                grp(
                    "SG2",
                    vec![rep(vec![numbered("NAD", "MS", "00004", 4)], vec![])],
                ),
                grp(
                    "SG4",
                    vec![rep(
                        vec![numbered("IDE", "24", "00005", 5)],
                        vec![grp(
                            "SG8",
                            vec![
                                rep(
                                    vec![
                                        numbered("SEQ", "A", "00006", 6),
                                        numbered("RFF", "Z13", "00007", 7),
                                    ],
                                    vec![],
                                ),
                                rep(vec![numbered("SEQ", "A", "00006", 8)], vec![]),
                            ],
                        )],
                    )],
                ),
            ],
            post_group_start: 2,
            inter_group_segments: Default::default(),
        };
        let found: Vec<(String, usize)> = check_structure(&t, &m)
            .into_iter()
            .map(|d| (d.segment_id, d.position))
            .collect();
        // DTM follows BGM; the NAD+MR group follows the NAD+MS one in the MIG
        // and starts with a segment of the same Number, so its predecessor is
        // BGM; RFF+Z13 follows the second SEQ+A.
        assert!(found.contains(&("DTM".into(), 3)), "{found:?}");
        assert!(found.contains(&("SG2".into(), 3)), "{found:?}");
        assert!(found.contains(&("RFF".into(), 8)), "{found:?}");
    }

    #[test]
    fn a_complete_message_is_clean() {
        let t = tree(vec![
            rep(vec![seg("SEQ", "A"), seg("RFF", "Z13")], vec![]),
            rep(vec![seg("SEQ", "B")], vec![]),
        ]);
        assert!(kinds(&t).is_empty(), "{:?}", kinds(&t));
    }

    #[test]
    fn each_repetition_is_judged_by_its_own_variant() {
        // SEQ+B has no RFF slot, so its missing RFF is fine; SEQ+A's is not.
        let t = tree(vec![
            rep(vec![seg("SEQ", "A")], vec![]),
            rep(vec![seg("SEQ", "B")], vec![]),
        ]);
        let found = kinds(&t);
        assert_eq!(found.len(), 1, "{found:?}");
        assert_eq!(found[0].0, StructureDiagnosticKind::MissingRequiredSegment);
        assert!(
            found[0].1.contains("RFF+Z13") && found[0].1.contains("SEQ+A"),
            "{found:?}"
        );
    }

    #[test]
    fn a_missing_root_segment_and_a_missing_group_variant() {
        let mut t = tree(vec![]);
        t.segments.retain(|s| s.tag != "BGM");
        t.groups[0].repetitions.remove(1); // NAD+MR
        let found = kinds(&t);
        assert!(found.iter().any(
            |(k, m)| *k == StructureDiagnosticKind::MissingRequiredSegment && m.contains("'BGM'")
        ));
        assert!(found
            .iter()
            .any(|(k, m)| *k == StructureDiagnosticKind::MissingRequiredGroup
                && m.contains("NAD+MR")));
        assert_eq!(found.len(), 2, "{found:?}");
    }

    #[test]
    fn too_many_repetitions_of_a_segment_and_of_a_group_variant() {
        let mut t = tree(vec![rep(
            vec![
                seg("SEQ", "A"),
                seg("RFF", "Z13"),
                seg("DTM", "1"),
                seg("DTM", "2"),
                seg("DTM", "3"),
            ],
            vec![],
        )]);
        t.groups[0]
            .repetitions
            .push(rep(vec![seg("NAD", "MS")], vec![]));
        let found = kinds(&t);
        assert!(found.iter().any(
            |(k, m)| *k == StructureDiagnosticKind::MaxRepetitionsExceeded
                && m.contains("'DTM' repeats 3 times")
        ));
        assert!(found.iter().any(|(k, m)| *k
            == StructureDiagnosticKind::GroupMaxRepetitionsExceeded
            && m.contains("NAD+MS")
            && m.contains("2 times")));
        assert_eq!(found.len(), 2, "{found:?}");
    }

    #[test]
    fn a_qualifier_no_slot_accepts_is_unrecognized() {
        let t = tree(vec![rep(
            vec![seg("SEQ", "A"), seg("RFF", "Z13"), seg("RFF", "Z99")],
            vec![],
        )]);
        let found = kinds(&t);
        assert_eq!(found.len(), 1, "{found:?}");
        assert_eq!(found[0].0, StructureDiagnosticKind::UnrecognizedQualifier);
        assert!(
            found[0].1.contains("RFF+Z99") && found[0].1.contains("RFF+Z13"),
            "{found:?}"
        );
    }

    #[test]
    fn an_example_code_names_no_qualifier() {
        // A slot listing only the MIG's example code `XYZ` takes any value.
        let mut m = mig();
        m.segments.push(slot("CAV", "R", 1, &["XYZ"]));
        let mut t = tree(vec![]);
        t.segments.push(seg("CAV", "Z90"));
        assert!(check_structure(&t, &m).is_empty());
    }

    #[test]
    fn an_empty_qualifier_element_is_not_a_wrong_one() {
        // CONTRL `UCS` without an error code: counts for its slot.
        let mut m = mig();
        m.segments.push(slot("UCS", "R", 1, &["13", "15"]));
        let mut t = tree(vec![]);
        t.segments.push(seg("UCS", ""));
        assert!(check_structure(&t, &m).is_empty());
    }
}