1
//! The stage-switch gate for plan 0014.
2
//!
3
//! The plan's ledger grows while a stage is worked, but a stage's `Closes:`
4
//! list is written once. Without a check the two drift: measured on
5
//! 2026-10-14, Stage 5 named 11 issues and owned 42. These tests make a
6
//! stage's `Closes:` list the complete index of what that stage owns, so
7
//! entering a stage cannot silently skip a row.
8

            
9
use std::collections::{BTreeMap, BTreeSet};
10
use std::fs;
11
use std::path::PathBuf;
12

            
13
/// Stages whose scope must be complete. A closed stage is excluded: its rows
14
/// are settled and its `Closes:` list is history, not a worklist.
15
const OPEN_STAGES: [&str; 4] = ["4", "5", "6", "7"];
16

            
17
3
fn plan() -> String {
18
3
    let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
19
3
        .join("../doc/ops/0014-compiler-defect-families.org");
20
3
    fs::read_to_string(&path)
21
        .unwrap_or_else(|e| panic!("plan 0014 unreadable at {}: {e}", path.display()))
22
3
}
23

            
24
struct Row {
25
    id: String,
26
    owner: String,
27
}
28

            
29
/// Ledger rows are not confined to one table: `* Issue ledger` carries
30
/// ISS-001..125 and the later issues are appended in the Stages section. Exit
31
/// tables and Stage 7's closure schedule also lead rows with an issue id, so
32
/// the owner cell's shape is what identifies a ledger row.
33
///
34
/// An owner is a stage number (`5`, `3 (slice 3.2b)`, `4 (A) / 7 (B)`), a
35
/// slice (`slice 6.12 after Stage 6 (A) …`), `WONTFIX`, `DEFERRED` or `—`.
36
/// Prose (`CL HANDLER-CASE`, `one pipeline, one accounting`) is not, and
37
/// neither is an exit table's `0011 rows` — hence the bound on the digits.
38
810
fn is_owner(cell: &str) -> bool {
39
    const WORDS: [&str; 3] = ["WONTFIX", "DEFERRED", "slice "];
40
1974
    if cell == "—" || WORDS.iter().any(|w| cell.starts_with(w)) {
41
240
        return true;
42
570
    }
43
570
    let digits = cell.chars().take_while(char::is_ascii_digit).count();
44
570
    (1..=2).contains(&digits) && !cell[digits..].starts_with(|c: char| c.is_ascii_digit())
45
810
}
46

            
47
/// A ledger row is a table row whose first cell is an issue id and whose
48
/// third cell is an owner.
49
3
fn ledger_rows(plan: &str) -> Vec<Row> {
50
3
    plan.lines()
51
9438
        .filter_map(|line| {
52
9438
            let cells: Vec<&str> = line.trim().split('|').map(str::trim).collect();
53
            // A leading `|` yields an empty first cell, so the id is at 1.
54
9438
            match cells.as_slice() {
55
1788
                [_, id, _text, owner, ..] if id.starts_with("ISS-") && is_owner(owner) => {
56
675
                    Some(Row {
57
675
                        id: (*id).to_owned(),
58
675
                        owner: (*owner).to_owned(),
59
675
                    })
60
                }
61
8763
                _ => None,
62
            }
63
9438
        })
64
        .collect()
65
3
}
66

            
67
/// The issue ids named in a stage's `Closes:` paragraph, which ends at the
68
/// `Rows:` sentence or the paragraph break after it.
69
8
fn closes(plan: &str, stage: &str) -> BTreeSet<String> {
70
8
    let heading = format!("** Stage {stage} ");
71
8
    let Some(start) = plan.find(&heading) else {
72
        return BTreeSet::new();
73
    };
74
8
    let section = &plan[start..];
75
8
    let end = section
76
8
        .get(heading.len()..)
77
8
        .and_then(|rest| rest.find("\n** ").map(|i| i + heading.len()))
78
8
        .unwrap_or(section.len());
79
8
    let section = &section[..end];
80

            
81
    // Stage 7 spells it `Closes (Branch B arms only):`, so the colon is not
82
    // fixed to the word.
83
8
    let Some(c) = section
84
8
        .lines()
85
32
        .scan(0usize, |at, line| {
86
32
            let start = *at;
87
32
            *at += line.len() + 1;
88
32
            Some((start, line))
89
32
        })
90
32
        .find_map(|(at, line)| line.trim_start().starts_with("Closes").then_some(at))
91
    else {
92
        return BTreeSet::new();
93
    };
94
8
    let tail = &section[c..];
95
8
    let scope_end = tail
96
8
        .find("Rows:")
97
6
        .or_else(|| tail.find("\n\n"))
98
8
        .unwrap_or(tail.len());
99
8
    issue_ids(&tail[..scope_end])
100
8
}
101

            
102
8
fn issue_ids(text: &str) -> BTreeSet<String> {
103
39116
    text.split(|c: char| !c.is_ascii_alphanumeric() && c != '-')
104
9948
        .filter(|t| t.starts_with("ISS-") && t.len() > 4)
105
8
        .map(str::to_owned)
106
        .collect()
107
8
}
108

            
109
/// The owner cell may carry a branch-conditional pair (`4 (A) / 7 (B)`) or a
110
/// parenthesised note. A stage owns the row when any alternative names it.
111
900
fn owning_stages(owner: &str) -> BTreeSet<String> {
112
900
    owner
113
900
        .split('/')
114
912
        .flat_map(|alt| alt.split('+'))
115
920
        .filter_map(|alt| {
116
920
            let digits: String = alt
117
920
                .trim()
118
920
                .chars()
119
920
                .take_while(char::is_ascii_digit)
120
920
                .collect();
121
920
            (!digits.is_empty()).then_some(digits)
122
920
        })
123
        .collect()
124
900
}
125

            
126
#[test]
127
1
fn every_issue_id_appears_once_in_the_ledger() {
128
1
    let plan = plan();
129
1
    let mut seen: BTreeMap<String, usize> = BTreeMap::new();
130
1
    for row in ledger_rows(&plan) {
131
225
        *seen.entry(row.id).or_default() += 1;
132
    }
133
1
    let duplicated: Vec<_> = seen
134
1
        .iter()
135
225
        .filter(|(_, n)| **n > 1)
136
        .map(|(id, n)| format!("{id} x{n}"))
137
        .collect();
138
1
    assert!(
139
1
        duplicated.is_empty(),
140
        "ledger rows duplicated: {}",
141
        duplicated.join(", ")
142
    );
143
1
    assert!(
144
1
        seen.len() > 100,
145
        "ledger looks truncated: {} rows",
146
        seen.len()
147
    );
148
1
}
149

            
150
#[test]
151
1
fn every_issue_a_stage_closes_has_a_ledger_row() {
152
1
    let plan = plan();
153
225
    let rows: BTreeSet<String> = ledger_rows(&plan).into_iter().map(|r| r.id).collect();
154
1
    let dangling: Vec<String> = OPEN_STAGES
155
1
        .iter()
156
4
        .flat_map(|stage| {
157
4
            closes(&plan, stage)
158
4
                .into_iter()
159
105
                .filter(|id| !rows.contains(id))
160
                .map(move |id| format!("Stage {stage}: {id}"))
161
4
        })
162
        .collect();
163
1
    assert!(
164
1
        dangling.is_empty(),
165
        "a stage closes an issue with no ledger row — a missing row, or an owner cell \
166
         that no longer parses as one ({} ids):\n{}",
167
        dangling.len(),
168
        dangling.join("\n")
169
    );
170
1
}
171

            
172
/// The stage-switch gate: a stage's `Closes:` list indexes every row it owns.
173
/// A row covered by an existing slice is still listed, with the covering
174
/// slice named in its provenance — otherwise the coverage is invisible here.
175
#[test]
176
1
fn an_open_stage_closes_every_row_it_owns() {
177
1
    let plan = plan();
178
1
    let rows = ledger_rows(&plan);
179
1
    let mut unplanned: Vec<String> = Vec::new();
180

            
181
1
    for stage in OPEN_STAGES {
182
4
        let named = closes(&plan, stage);
183
4
        let owned: BTreeSet<String> = rows
184
4
            .iter()
185
900
            .filter(|r| owning_stages(&r.owner).contains(stage))
186
89
            .map(|r| r.id.clone())
187
            .collect();
188
4
        unplanned.extend(
189
4
            owned
190
4
                .difference(&named)
191
                .map(|id| format!("Stage {stage}: {id}")),
192
        );
193
    }
194

            
195
1
    assert!(
196
1
        unplanned.is_empty(),
197
        "ledger rows owned by an open stage but absent from its Closes list \
198
         ({} rows) — reconcile at the stage switch:\n{}",
199
        unplanned.len(),
200
        unplanned.join("\n")
201
    );
202
1
}