gedcomkit 0.1.10

A byte-preserving GEDCOM document model: decoding, parsing, readings, version conversion, plausibility checks, and the GEDZIP container, for GEDCOM 5.5 through 7.x.
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
//! What the file says that cannot all be true, and what it does not say at all.
//!
//! **Check tree** could find every pointer with no record behind it and nothing
//! else. That is one kind of fault and not the kind a genealogist spends their
//! time on: the ones that matter are a person who died before they were born, a
//! mother listed as eleven years old, a marriage after a funeral — and, most of
//! all, a person the file asserts and cites nothing for.
//!
//! Three rules shaped this:
//!
//! **Nothing here is an error.** A file is a record of what somebody wrote
//! down, and a contradiction in it is a fact about the sources, not a fault in
//! the file. Everything is reported, nothing is refused, and nothing is
//! changed.
//!
//! **Every finding says the numbers it was drawn from.** "Married at 9" is
//! checkable against the record; "implausible marriage age" is an opinion the
//! reader cannot audit.
//!
//! **A date nobody can read is not a contradiction.** Half the dates in a real
//! file are approximate, and a check that treats "about 1850" as a claim about
//! a particular day produces a page of findings nobody will read twice. Only
//! years are compared, and only where the date reader recovered a reading: a
//! year merely *mentioned* in an unreadable payload (`WFT Est 1804-1911`) says
//! nothing about when the event happened. A date that bounds a year rather
//! than naming one — `BEF 1811`, `AFT 1850`, `BET 1804 AND 1911` — is
//! compared by its bounds, so it contradicts another only when no year it
//! admits could be true.

use crate::dates::{Calendar, GedcomDate};
use crate::view::{FamilyView, IndividualView, record_title};
use crate::{Document, Node};
use std::collections::HashMap;
use std::fmt;

/// How much a finding is claiming.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub enum Severity {
    /// The file says two things that cannot both be true.
    Contradiction,
    /// Possible, and unlikely enough to be worth a look. A woman of fifty-two
    /// can bear a child; most records that say so are a mis-keyed year.
    Question,
    /// Nothing is contradicted. Something a researcher wants is simply absent.
    Missing,
}

impl Severity {
    /// The word the interface uses.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::Contradiction => "contradiction",
            Self::Question => "worth a look",
            Self::Missing => "not recorded",
        }
    }
}

/// One thing worth telling somebody about their file.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct Finding {
    /// The record it is about.
    pub record: String,
    /// A stable name for the kind of check, so a report can be grouped and a
    /// finding can be recognized between runs.
    pub check: &'static str,
    /// How much the finding is claiming.
    pub severity: Severity,
    /// What was found, with the numbers it was drawn from.
    pub message: String,
}

/// Nobody lives this long. The oldest verified human life was 122 years.
const LONGEST_LIFE: i32 = 125;
/// Below this, a marriage is a record-keeping error far more often than a fact.
const YOUNGEST_MARRIAGE: i32 = 13;
/// A mother older than this is worth a second look at the year.
const OLDEST_MOTHER: i32 = 55;
/// And a father, allowing that the range is genuinely wider.
const OLDEST_FATHER: i32 = 80;
/// A parent younger than this at a birth is almost always a mis-keyed year.
const YOUNGEST_PARENT: i32 = 12;

/// The years a date admits: its earliest and latest, either open when the
/// date bounds only one side (`BEF 1811` has no earliest).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct Years {
    earliest: Option<i32>,
    latest: Option<i32>,
}

impl Years {
    /// The years a `DATE` payload admits, or `None` when the reader could not
    /// read it — a year that merely appears in unreadable text is not used.
    ///
    /// Only Gregorian and Julian years are comparable with each other; a
    /// Hebrew or French Republican year counts from another epoch, so such a
    /// date is left out rather than compared as if it were Gregorian. A range
    /// written backwards (`BET 1910 AND 1900`) admits the same years as one
    /// written forwards.
    fn of(payload: &str) -> Option<Self> {
        let date = GedcomDate::parse(payload);
        if !date.is_parsed() || !matches!(date.calendar, Calendar::Gregorian | Calendar::Julian) {
            return None;
        }
        let mut years = Self {
            earliest: date.earliest.map(|point| point.year),
            latest: date.latest.map(|point| point.year),
        };
        if let (Some(start), Some(end)) = (years.earliest, years.latest)
            && start > end
        {
            years = Self {
                earliest: Some(end),
                latest: Some(start),
            };
        }
        (years.earliest.is_some() || years.latest.is_some()).then_some(years)
    }

    /// Whether every year this admits comes before every year `other` admits.
    const fn wholly_before(self, other: Self) -> bool {
        matches!((self.latest, other.earliest), (Some(end), Some(start)) if end < start)
    }

    /// The smallest and largest number of years from `self` to `later` that
    /// the two dates allow, each `None` when a bound is open.
    fn gap_to(self, later: Self) -> (Option<i32>, Option<i32>) {
        let least = later
            .earliest
            .zip(self.latest)
            .map(|(end, start)| end - start);
        let most = later
            .latest
            .zip(self.earliest)
            .map(|(end, start)| end - start);
        (least, most)
    }
}

impl fmt::Display for Years {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match (self.earliest, self.latest) {
            (Some(start), Some(end)) if start == end => write!(formatter, "{start}"),
            (Some(start), Some(end)) => write!(formatter, "between {start} and {end}"),
            (None, Some(end)) => write!(formatter, "before {end}"),
            (Some(start), None) => write!(formatter, "after {start}"),
            (None, None) => formatter.write_str("undated"),
        }
    }
}

/// What one person's record says about when they lived.
#[derive(Clone, Copy, Default)]
struct Life {
    born: Option<Years>,
    died: Option<Years>,
    buried: Option<Years>,
}

/// Every finding in the document, in record order.
#[must_use]
pub fn inspect(document: &Document) -> Vec<Finding> {
    // Read once, used twice. Every person's view is needed for the checks on
    // their own record and for the ones about their family, and building it a
    // second time is a second pass over the whole file.
    let people: Vec<(&Node, IndividualView)> = document
        .records_of("INDI")
        .map(|record| (record, IndividualView::from_node(record)))
        .collect();
    let lives: HashMap<String, Life> = people
        .iter()
        .filter_map(|(record, view)| {
            record
                .xref
                .as_ref()
                .map(|xref| (xref.to_ascii_uppercase(), life_of(view)))
        })
        .collect();

    let mut found = Vec::new();
    for (record, view) in &people {
        inspect_person(record, view, &lives, &mut found);
    }
    for record in document.records_of("FAM") {
        inspect_family(record, &lives, &mut found);
    }
    found
}

fn year_of(view: &IndividualView, tag: &str) -> Option<Years> {
    view.events
        .iter()
        .find(|event| event.tag == tag)
        .and_then(|event| event.date.as_deref())
        .and_then(Years::of)
}

fn life_of(view: &IndividualView) -> Life {
    Life {
        born: year_of(view, "BIRT"),
        died: year_of(view, "DEAT"),
        buried: year_of(view, "BURI"),
    }
}

fn add(
    found: &mut Vec<Finding>,
    record: &Node,
    check: &'static str,
    severity: Severity,
    message: String,
) {
    found.push(Finding {
        record: record.xref.clone().unwrap_or_else(|| record.tag.clone()),
        check,
        severity,
        message,
    });
}

fn inspect_person(
    record: &Node,
    view: &IndividualView,
    lives: &HashMap<String, Life>,
    found: &mut Vec<Finding>,
) {
    let life = lives
        .get(&record.xref.clone().unwrap_or_default().to_ascii_uppercase())
        .copied()
        .unwrap_or_default();

    if let (Some(born), Some(died)) = (life.born, life.died) {
        if died.wholly_before(born) {
            add(
                found,
                record,
                "died-before-born",
                Severity::Contradiction,
                format!("born {born} and died {died}"),
            );
        } else if let (Some(shortest), _) = born.gap_to(died)
            && shortest > LONGEST_LIFE
        {
            add(
                found,
                record,
                "improbable-lifespan",
                Severity::Question,
                format!(
                    "born {born} and died {died}, which is {}{shortest} years",
                    if born.gap_to(died).1 == Some(shortest) {
                        ""
                    } else {
                        "at least "
                    }
                ),
            );
        }
    }

    if let (Some(died), Some(buried)) = (life.died, life.buried)
        && buried.wholly_before(died)
    {
        add(
            found,
            record,
            "buried-before-died",
            Severity::Contradiction,
            format!("died {died} and buried {buried}"),
        );
    }

    // An event after the funeral is either a wrong year or a second person.
    // Probate and a will are the two that legitimately come after a death;
    // a birth after it is already `died-before-born`, reported once.
    if let Some(died) = life.died {
        for event in &view.events {
            if matches!(
                event.tag.as_str(),
                "BIRT" | "DEAT" | "BURI" | "CREM" | "PROB" | "WILL"
            ) {
                continue;
            }
            let Some(year) = event.date.as_deref().and_then(Years::of) else {
                continue;
            };
            if died.wholly_before(year) {
                add(
                    found,
                    record,
                    "event-after-death",
                    Severity::Contradiction,
                    format!("died {died}, and {} is dated {year}", event.label),
                );
            }
        }
    }

    // The one a researcher actually wants: what does this file assert with
    // nothing behind it at all?
    let cited = record.walk().any(|node| node.tag == "SOUR");
    if !cited {
        add(
            found,
            record,
            "no-source",
            Severity::Missing,
            "nothing on this record cites a source".to_owned(),
        );
    }
}

fn inspect_family(record: &Node, lives: &HashMap<String, Life>, found: &mut Vec<Finding>) {
    let family = FamilyView::from_node(record);
    let married = record
        .first("MARR")
        .and_then(|event| event.value_of("DATE"))
        .and_then(|payload| Years::of(&payload));

    for parent in family.partners() {
        let Some(parent_life) = lives.get(&parent.to_ascii_uppercase()).copied() else {
            continue;
        };
        inspect_marriage(record, married, parent_life, found);
        // The wider window for a father is not chivalry: it is what the
        // records actually contain.
        let mother = record
            .first("WIFE")
            .and_then(Node::pointer)
            .is_some_and(|wife| wife.eq_ignore_ascii_case(&parent));
        for child in &family.children {
            let Some(child_life) = lives.get(&child.to_ascii_uppercase()).copied() else {
                continue;
            };
            inspect_parenthood(record, parent_life, child_life, mother, found);
        }
    }

    // A child recorded twice in one family is one child and a duplicate line.
    let mut seen: Vec<String> = Vec::new();
    for child in &family.children {
        let key = child.to_ascii_uppercase();
        if seen.contains(&key) {
            add(
                found,
                record,
                "child-listed-twice",
                Severity::Question,
                format!("{child} is listed as a child of this family more than once"),
            );
        } else {
            seen.push(key);
        }
    }

    if family.partners().is_empty() && family.children.is_empty() {
        add(
            found,
            record,
            "empty-family",
            Severity::Question,
            "this family records nobody at all".to_owned(),
        );
    }
}

fn inspect_marriage(record: &Node, married: Option<Years>, parent: Life, found: &mut Vec<Finding>) {
    let (Some(married), Some(born)) = (married, parent.born) else {
        return;
    };
    if married.wholly_before(born) {
        add(
            found,
            record,
            "married-before-born",
            Severity::Contradiction,
            format!("a marriage {} for somebody born {born}", in_year(married)),
        );
    } else if let (_, Some(oldest)) = born.gap_to(married)
        && oldest < YOUNGEST_MARRIAGE
    {
        add(
            found,
            record,
            "married-as-a-child",
            Severity::Question,
            format!(
                "married {} {}, born {born}",
                in_year(married),
                age(born, married)
            ),
        );
    }
}

/// `in 1900`, or the bounded form (`before 1811`) as it stands.
fn in_year(years: Years) -> String {
    match (years.earliest, years.latest) {
        (Some(start), Some(end)) if start == end => format!("in {start}"),
        _ => years.to_string(),
    }
}

/// The age between two dates as a phrase: `at 9` when both are single years,
/// the range the dates allow otherwise (`at 9 to 12`, `at most 9`).
fn age(from: Years, to: Years) -> String {
    match from.gap_to(to) {
        (Some(least), Some(most)) if least == most => format!("at {least}"),
        (Some(least), Some(most)) => format!("at {least} to {most}"),
        (Some(least), None) => format!("at least {least}"),
        (None, Some(most)) => format!("at most {most}"),
        (None, None) => "at an unknown age".to_owned(),
    }
}

fn inspect_parenthood(
    record: &Node,
    parent: Life,
    child: Life,
    mother: bool,
    found: &mut Vec<Finding>,
) {
    let Some(child_born) = child.born else {
        return;
    };

    // A father may die before a birth; a mother may not. This needs only her
    // death and the child's birth, not her own birth year.
    if let (true, Some(parent_died)) = (mother, parent.died)
        && parent_died.wholly_before(child_born)
    {
        add(
            found,
            record,
            "child-born-after-mother-died",
            Severity::Contradiction,
            format!("a mother who died {parent_died} with a child born {child_born}"),
        );
    }

    let Some(parent_born) = parent.born else {
        return;
    };
    let (youngest, oldest) = parent_born.gap_to(child_born);
    // Too young only if even the oldest age the dates allow is too young.
    if let Some(oldest) = oldest
        && oldest < YOUNGEST_PARENT
    {
        // The sign decides the wording: a negative oldest age means the child
        // was born before the parent whatever the dates' ranges.
        let said = if oldest < 0 {
            format!("{} years before the parent was born", oldest.abs())
        } else if youngest == Some(oldest) {
            format!("at {oldest} years old")
        } else {
            format!("at most {oldest} years old")
        };
        add(
            found,
            record,
            "parent-too-young",
            Severity::Contradiction,
            format!("a parent born {parent_born} with a child born {child_born}, {said}"),
        );
        return;
    }

    let limit = if mother { OLDEST_MOTHER } else { OLDEST_FATHER };
    if let Some(youngest) = youngest
        && youngest > limit
    {
        add(
            found,
            record,
            "parent-too-old",
            Severity::Question,
            format!(
                "a parent born {parent_born} with a child born {child_born}, {}",
                age(parent_born, child_born)
            ),
        );
    }
}

/// A one-line heading for the record a finding is about.
#[must_use]
pub fn heading(document: &Document, xref: &str) -> String {
    document
        .record(xref)
        .map_or_else(|| xref.to_owned(), record_title)
}

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

    fn findings(text: &str) -> Vec<Finding> {
        inspect(&Document::parse(text).expect("parse"))
    }

    fn checks(found: &[Finding]) -> Vec<&str> {
        found.iter().map(|finding| finding.check).collect()
    }

    #[test]
    fn a_life_that_runs_backwards_is_a_contradiction() {
        let found = findings(
            "0 HEAD\n\
0 @I1@ INDI\n\
1 BIRT\n\
2 DATE 1900\n\
1 DEAT\n\
2 DATE 1880\n\
0 TRLR\n",
        );
        let died = found
            .iter()
            .find(|finding| finding.check == "died-before-born")
            .expect("the contradiction");
        assert_eq!(died.severity, Severity::Contradiction);
        // The numbers are in the message, so a reader can check it themselves.
        assert!(died.message.contains("1900") && died.message.contains("1880"));
    }

    #[test]
    fn an_event_after_the_funeral_is_reported_and_probate_is_not() {
        let found = findings(
            "0 HEAD\n\
0 @I1@ INDI\n\
1 DEAT\n\
2 DATE 1920\n\
1 RESI\n\
2 DATE 1925\n\
1 PROB\n\
2 DATE 1921\n\
0 TRLR\n",
        );
        let after: Vec<&Finding> = found
            .iter()
            .filter(|finding| finding.check == "event-after-death")
            .collect();
        assert_eq!(after.len(), 1, "{found:?}");
        assert!(
            after[0].message.contains("Residence"),
            "{}",
            after[0].message
        );
    }

    #[test]
    fn a_parent_younger_than_their_child_is_a_contradiction_and_an_old_one_is_a_question() {
        let found = findings(
            "0 HEAD\n\
0 @I1@ INDI\n\
1 SEX F\n\
1 BIRT\n\
2 DATE 1900\n\
1 FAMS @F1@\n\
0 @I2@ INDI\n\
1 BIRT\n\
2 DATE 1905\n\
1 FAMC @F1@\n\
0 @F1@ FAM\n\
1 WIFE @I1@\n\
1 CHIL @I2@\n\
0 TRLR\n",
        );
        assert!(checks(&found).contains(&"parent-too-young"), "{found:?}");

        let older = findings(
            "0 HEAD\n\
0 @I1@ INDI\n\
1 BIRT\n\
2 DATE 1900\n\
1 FAMS @F1@\n\
0 @I2@ INDI\n\
1 BIRT\n\
2 DATE 1960\n\
1 FAMC @F1@\n\
0 @F1@ FAM\n\
1 WIFE @I1@\n\
1 CHIL @I2@\n\
0 TRLR\n",
        );
        let old = older
            .iter()
            .find(|finding| finding.check == "parent-too-old")
            .expect("a question");
        assert_eq!(old.severity, Severity::Question);
        assert!(old.message.contains("60"), "{}", old.message);
    }

    #[test]
    fn a_marriage_before_a_birth_and_one_in_childhood_are_told_apart() {
        let found = findings(
            "0 HEAD\n\
0 @I1@ INDI\n\
1 BIRT\n\
2 DATE 1900\n\
1 FAMS @F1@\n\
0 @I2@ INDI\n\
1 BIRT\n\
2 DATE 1899\n\
1 FAMS @F1@\n\
0 @F1@ FAM\n\
1 HUSB @I1@\n\
1 WIFE @I2@\n\
1 MARR\n\
2 DATE 1890\n\
0 TRLR\n",
        );
        assert_eq!(
            checks(&found)
                .iter()
                .filter(|check| **check == "married-before-born")
                .count(),
            2,
            "both partners were married before they were born: {found:?}"
        );
    }

    #[test]
    fn a_person_nothing_cites_is_the_finding_a_researcher_wants() {
        let found = findings(
            "0 HEAD\n\
0 @I1@ INDI\n\
1 NAME Cited /Sampleperson/\n\
1 BIRT\n\
2 DATE 1900\n\
3 SOUR @S1@\n\
0 @I2@ INDI\n\
1 NAME Unsourced /Sampleperson/\n\
0 @S1@ SOUR\n\
1 TITL A register\n\
0 TRLR\n",
        );
        let missing: Vec<&Finding> = found
            .iter()
            .filter(|finding| finding.check == "no-source")
            .collect();
        assert_eq!(missing.len(), 1, "{found:?}");
        assert_eq!(missing[0].record, "@I2@");
        assert_eq!(missing[0].severity, Severity::Missing);
    }

    #[test]
    fn an_approximate_date_is_not_turned_into_a_contradiction() {
        // Two people, one born "about 1850" and dying in 1849. A year is a
        // year however it was written, so this is still reported — but a date
        // with no year in it at all cannot contradict anything.
        let unreadable = findings(
            "0 HEAD\n\
0 @I1@ INDI\n\
1 BIRT\n\
2 DATE Infant\n\
1 DEAT\n\
2 DATE Unknown\n\
0 TRLR\n",
        );
        assert!(
            !checks(&unreadable).contains(&"died-before-born"),
            "{unreadable:?}"
        );
    }

    #[test]
    fn a_year_mentioned_in_an_unreadable_date_is_not_a_death_year() {
        // `WFT Est 1804-1911` mentions 1804; it does not say the person died
        // then, so a birth in 1807 contradicts nothing.
        let found = findings(
            "0 HEAD\n0 @I1@ INDI\n1 BIRT\n2 DATE 1807\n1 DEAT\n2 DATE WFT Est 1804-1911\n0 TRLR\n",
        );
        assert!(
            !checks(&found).contains(&"died-before-born")
                && !checks(&found).contains(&"event-after-death"),
            "{found:?}"
        );
    }

    #[test]
    fn a_bounded_date_contradicts_only_when_no_year_it_allows_could_be_true() {
        // Died before 1811 and born 1807: both can be true.
        let found =
            findings("0 HEAD\n0 @I1@ INDI\n1 BIRT\n2 DATE 1807\n1 DEAT\n2 DATE BEF 1811\n0 TRLR\n");
        assert!(!checks(&found).contains(&"died-before-born"), "{found:?}");
        // Died before 1805 and born 1807: they cannot.
        let found =
            findings("0 HEAD\n0 @I1@ INDI\n1 BIRT\n2 DATE 1807\n1 DEAT\n2 DATE BEF 1805\n0 TRLR\n");
        let died = found
            .iter()
            .find(|finding| finding.check == "died-before-born")
            .expect("a contradiction");
        assert_eq!(died.message, "born 1807 and died before 1805");
        // A range is compared by both of its ends.
        let found = findings(
            "0 HEAD\n0 @I1@ INDI\n1 BIRT\n2 DATE BET 1800 AND 1810\n1 DEAT\n2 DATE 1805\n0 TRLR\n",
        );
        assert!(!checks(&found).contains(&"died-before-born"), "{found:?}");
    }

    #[test]
    fn a_bounded_marriage_says_its_age_once() {
        let found = findings(
            "0 HEAD\n\
0 @I1@ INDI\n\
1 BIRT\n\
2 DATE 1802\n\
0 @F1@ FAM\n\
1 HUSB @I1@\n\
1 MARR\n\
2 DATE BEF 1811\n\
0 TRLR\n",
        );
        let child = found
            .iter()
            .find(|finding| finding.check == "married-as-a-child")
            .expect("married as a child");
        assert_eq!(child.message, "married before 1811 at most 9, born 1802");
    }

    #[test]
    fn another_calendar_and_a_backwards_range_are_not_misread() {
        // 5620 is a Hebrew year (1859-60), not a birth after a death in 1900.
        let found = findings(
            "0 HEAD\n\
0 @I1@ INDI\n\
1 BIRT\n\
2 DATE @#DHEBREW@ 5620\n\
1 DEAT\n\
2 DATE 1900\n\
0 TRLR\n",
        );
        assert!(!checks(&found).contains(&"died-before-born"), "{found:?}");
        let found = findings(
            "0 HEAD\n\
0 @I1@ INDI\n\
1 BIRT\n\
2 DATE BET 1910 AND 1900\n\
1 DEAT\n\
2 DATE 1905\n\
0 TRLR\n",
        );
        assert!(!checks(&found).contains(&"died-before-born"), "{found:?}");
    }

    #[test]
    fn a_child_born_before_its_parent_says_so_plainly() {
        let found = findings(
            "0 HEAD\n\
0 @I1@ INDI\n\
1 BIRT\n\
2 DATE BET 1850 AND 1855\n\
0 @I2@ INDI\n\
1 BIRT\n\
2 DATE BET 1840 AND 1845\n\
0 @F1@ FAM\n\
1 HUSB @I1@\n\
1 CHIL @I2@\n\
0 TRLR\n",
        );
        let young = found
            .iter()
            .find(|finding| finding.check == "parent-too-young")
            .expect("born before the parent");
        assert!(
            young
                .message
                .ends_with("5 years before the parent was born"),
            "{}",
            young.message
        );
    }

    #[test]
    fn a_mother_dead_before_the_birth_needs_no_birth_year_of_her_own() {
        let found = findings(
            "0 HEAD\n\
0 @I1@ INDI\n\
1 DEAT\n\
2 DATE 1850\n\
0 @I2@ INDI\n\
1 BIRT\n\
2 DATE 1860\n\
0 @F1@ FAM\n\
1 WIFE @I1@\n\
1 CHIL @I2@\n\
0 TRLR\n",
        );
        assert!(
            checks(&found).contains(&"child-born-after-mother-died"),
            "{found:?}"
        );
    }

    #[test]
    fn a_parent_with_a_bounded_birth_is_too_young_only_when_every_age_is() {
        let family = |parent: &str, child: &str| {
            findings(&format!(
                "0 HEAD\n0 @I1@ INDI\n1 BIRT\n2 DATE {parent}\n0 @I2@ INDI\n1 BIRT\n2 DATE {child}\n\
0 @F1@ FAM\n1 HUSB @I1@\n1 CHIL @I2@\n0 TRLR\n"
            ))
        };
        assert!(!checks(&family("AFT 1850", "1870")).contains(&"parent-too-young"));
        let found = family("BET 1860 AND 1865", "1870");
        let young = found
            .iter()
            .find(|finding| finding.check == "parent-too-young")
            .expect("too young at every allowed age");
        assert_eq!(
            young.message,
            "a parent born between 1860 and 1865 with a child born 1870, at most 10 years old"
        );
    }

    #[test]
    fn a_clean_record_produces_nothing_but_what_is_actually_missing() {
        let found = findings(
            "0 HEAD\n\
0 @I1@ INDI\n\
1 NAME Ordinary /Sampleperson/\n\
1 BIRT\n\
2 DATE 1900\n\
2 SOUR @S1@\n\
1 DEAT\n\
2 DATE 1975\n\
0 @S1@ SOUR\n\
1 TITL A register\n\
0 TRLR\n",
        );
        assert!(found.is_empty(), "{found:?}");
    }

    #[test]
    fn a_child_listed_twice_is_one_child_and_a_duplicate_line() {
        let found = findings(
            "0 HEAD\n\
0 @I1@ INDI\n\
1 FAMC @F1@\n\
0 @F1@ FAM\n\
1 CHIL @I1@\n\
1 CHIL @I1@\n\
0 TRLR\n",
        );
        assert!(checks(&found).contains(&"child-listed-twice"), "{found:?}");
    }
}