Skip to main content

sokf_core/include/
region.rs

1//! This module extracts the named regions of a repository file. Section 9.3
2//! of the format specification defines them.
3
4/// A `RegionError` reports a region marker that breaks the pairing of `begin`
5/// and `end` markers (`SOKF_FORMAT_95`, `SOKF_FORMAT_112`), and gives the name of
6/// the region and the number of the line.
7#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
8pub enum RegionError {
9    /// A `begin` marker opens a region that is already open.
10    #[error("region `{name}` begins again at line {line} while it is still open")]
11    AlreadyOpen {
12        /// The name of the region.
13        name: String,
14        /// The line of the marker, counted from 1.
15        line: usize,
16    },
17    /// An `end` marker closes a region that isn't open.
18    #[error("region `{name}` ends at line {line} without a matching `begin` marker")]
19    NotOpen {
20        /// The name of the region.
21        name: String,
22        /// The line of the marker, counted from 1.
23        line: usize,
24    },
25    /// A `begin` marker has no matching `end` marker.
26    #[error("region `{name}` begins at line {line} but never ends")]
27    NeverClosed {
28        /// The name of the region.
29        name: String,
30        /// The line of the marker, counted from 1.
31        line: usize,
32    },
33}
34
35impl RegionError {
36    /// `line` returns the line of the marker that breaks the pairing.
37    pub fn line(&self) -> usize {
38        match self {
39            RegionError::AlreadyOpen { line, .. }
40            | RegionError::NotOpen { line, .. }
41            | RegionError::NeverClosed { line, .. } => *line,
42        }
43    }
44}
45
46enum Marker<'a> {
47    Begin(&'a str),
48    End(&'a str),
49}
50
51fn is_name(s: &str) -> bool {
52    !s.is_empty()
53        && s.bytes()
54            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
55}
56
57/// `marker` returns the marker on a line, `sokf:begin <name>` or
58/// `sokf:end <name>`, found anywhere in the line. The name is the next word
59/// after the prefix, and it must match `[A-Za-z0-9_-]+`.
60fn marker(line: &str) -> Option<Marker<'_>> {
61    for (prefix, begin) in [("sokf:begin ", true), ("sokf:end ", false)] {
62        if let Some(i) = line.find(prefix) {
63            let rest = &line[i + prefix.len()..];
64            let name = rest.split_whitespace().next().unwrap_or("");
65            if is_name(name) {
66                return Some(if begin {
67                    Marker::Begin(name)
68                } else {
69                    Marker::End(name)
70                });
71            }
72        }
73    }
74    None
75}
76
77/// `extract` returns the lines of `region` in `text`, or of the whole file
78/// when `region` is `None`, with every marker line stripped. It returns
79/// `Ok(None)` when no region has that name. It joins regions that share a
80/// name in file order.
81// sokf-implements: SOKF_FORMAT_85
82// sokf-implements: SOKF_FORMAT_95
83// sokf-implements: SOKF_FORMAT_128
84// sokf-implements: SOKF_FORMAT_136
85// sokf-implements: SOKF_FORMAT_137
86// sokf-implements: SOKF_FORMAT_112
87pub fn extract(text: &str, region: Option<&str>) -> Result<Option<String>, RegionError> {
88    Ok(extract_lines(text, region)?.map(|e| e.text))
89}
90
91/// An `Extraction` is the text that `extract` returns, with the line of the
92/// file, counted from 1, of each of its lines.
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct Extraction {
95    /// The text, each line with its newline.
96    pub text: String,
97    /// The line of the file of each line of `text`, in order.
98    pub lines: Vec<u32>,
99}
100
101impl Extraction {
102    /// `range` returns the lines of the file that the extraction holds as
103    /// one run of whole lines with no line left out, from its first line to
104    /// before its end, or `None` when the extraction is empty or leaves out
105    /// a line of that run, such as a marker or a line between two regions of
106    /// one name.
107    pub fn range(&self) -> Option<std::ops::Range<u32>> {
108        let first = *self.lines.first()?;
109        let contiguous = self
110            .lines
111            .iter()
112            .enumerate()
113            .all(|(i, &line)| u32::try_from(i).is_ok_and(|i| line == first + i));
114        contiguous.then(|| first..self.lines[self.lines.len() - 1] + 1)
115    }
116}
117
118/// `extract_lines` returns what `extract` returns, with the line of the
119/// file of each line of the text.
120pub fn extract_lines(text: &str, region: Option<&str>) -> Result<Option<Extraction>, RegionError> {
121    let mut open: Vec<(String, usize)> = Vec::new();
122    let mut out = String::new();
123    let mut lines: Vec<u32> = Vec::new();
124    let mut found = region.is_none();
125    for (i, line) in text.lines().enumerate() {
126        let line_no = i + 1;
127        match marker(line) {
128            Some(Marker::Begin(name)) => {
129                if open.iter().any(|(n, _)| n == name) {
130                    return Err(RegionError::AlreadyOpen {
131                        name: name.to_string(),
132                        line: line_no,
133                    });
134                }
135                if Some(name) == region {
136                    found = true;
137                }
138                open.push((name.to_string(), line_no));
139            }
140            Some(Marker::End(name)) => {
141                let Some(pos) = open.iter().position(|(n, _)| n == name) else {
142                    return Err(RegionError::NotOpen {
143                        name: name.to_string(),
144                        line: line_no,
145                    });
146                };
147                open.remove(pos);
148            }
149            None => {
150                let inside = match region {
151                    None => true,
152                    Some(r) => open.iter().any(|(n, _)| n == r),
153                };
154                if inside {
155                    out.push_str(line);
156                    out.push('\n');
157                    lines.push(u32::try_from(line_no).unwrap_or(u32::MAX));
158                }
159            }
160        }
161    }
162    if let Some((name, line)) = open.into_iter().next() {
163        return Err(RegionError::NeverClosed { name, line });
164    }
165    Ok(found.then_some(Extraction { text: out, lines }))
166}
167
168#[cfg(test)]
169mod tests {
170    use std::fmt::Write as _;
171
172    use proptest::prelude::*;
173
174    use super::*;
175
176    const FILE: &str = "use x;\n// sokf:begin cli\nfn a() {}\n# sokf:begin other\nfn b() {}\n// sokf:end cli\nfn c() {}\n// sokf:end other\n<!-- sokf:begin cli -->\nfn d() {}\n<!-- sokf:end cli -->\n";
177
178    // sokf-tests: SOKF_FORMAT_136
179    // sokf-tests: SOKF_FORMAT_137
180    #[test]
181    fn extracts_regions_and_whole_files() {
182        assert_eq!(
183            extract(FILE, Some("cli")).unwrap().unwrap(),
184            "fn a() {}\nfn b() {}\nfn d() {}\n"
185        );
186        assert_eq!(
187            extract(FILE, Some("other")).unwrap().unwrap(),
188            "fn b() {}\nfn c() {}\n"
189        );
190        assert_eq!(
191            extract(FILE, None).unwrap().unwrap(),
192            "use x;\nfn a() {}\nfn b() {}\nfn c() {}\nfn d() {}\n"
193        );
194        assert_eq!(extract(FILE, Some("nope")).unwrap(), None);
195        assert_eq!(extract("", None).unwrap().unwrap(), "");
196        assert_eq!(
197            extract("// sokf:begin e\n// sokf:end e\n", Some("e"))
198                .unwrap()
199                .unwrap(),
200            ""
201        );
202    }
203
204    #[test]
205    fn an_extraction_gives_the_line_of_each_of_its_lines() {
206        let cli = extract_lines(FILE, Some("cli")).unwrap().unwrap();
207        assert_eq!(cli.lines, vec![3, 5, 10]);
208        assert_eq!(cli.range(), None);
209        let other = extract_lines(FILE, Some("other")).unwrap().unwrap();
210        assert_eq!(other.lines, vec![5, 7]);
211        assert_eq!(other.range(), None);
212        let one = extract_lines("a\n// sokf:begin r\nb\nc\n// sokf:end r\n", Some("r"))
213            .unwrap()
214            .unwrap();
215        assert_eq!(one.range(), Some(3..5));
216        let whole = extract_lines("a\nb\n", None).unwrap().unwrap();
217        assert_eq!(whole.range(), Some(1..3));
218        let empty = extract_lines("// sokf:begin e\n// sokf:end e\n", Some("e"))
219            .unwrap()
220            .unwrap();
221        assert_eq!(empty.range(), None);
222    }
223
224    #[test]
225    fn non_markers_are_content() {
226        let text =
227            "sokf:begin\nsokf:begin x:y\nsokf:end\n<!-- sokf:begin ok -->\n<!-- sokf:end ok -->\n";
228        assert_eq!(
229            extract(text, None).unwrap().unwrap(),
230            "sokf:begin\nsokf:begin x:y\nsokf:end\n"
231        );
232        assert_eq!(extract(text, Some("ok")).unwrap(), Some(String::new()));
233        assert_eq!(extract(text, Some("x")).unwrap(), None);
234    }
235
236    #[test]
237    fn region_errors_name_the_line() {
238        assert_eq!(
239            extract("// sokf:begin a\n// sokf:begin a\n", Some("a")).unwrap_err(),
240            RegionError::AlreadyOpen {
241                name: "a".into(),
242                line: 2
243            }
244        );
245        assert_eq!(
246            extract("// sokf:end a\n", None).unwrap_err(),
247            RegionError::NotOpen {
248                name: "a".into(),
249                line: 1
250            }
251        );
252        assert_eq!(
253            extract("x\n// sokf:begin a\n", Some("b")).unwrap_err(),
254            RegionError::NeverClosed {
255                name: "a".into(),
256                line: 2
257            }
258        );
259        assert!(
260            RegionError::NotOpen {
261                name: "a".into(),
262                line: 1
263            }
264            .to_string()
265            .contains("line 1")
266        );
267    }
268
269    fn arb_file() -> impl Strategy<Value = (String, Vec<(String, Vec<String>)>)> {
270        // The strategy builds a file of plain lines and regions, some of which
271        // share a name. It returns the file with the lines that extraction
272        // should return for each region name.
273        prop::collection::vec(
274            (
275                prop::sample::select(vec!["r1", "r2", "r3"]),
276                prop::collection::vec("[a-z ]{0,8}", 0..4),
277            ),
278            0..5,
279        )
280        .prop_map(|regions| {
281            let mut text = String::from("head\n");
282            let mut expected: Vec<(String, Vec<String>)> = Vec::new();
283            for (name, lines) in regions {
284                let _ = writeln!(text, "// sokf:begin {name}");
285                for l in &lines {
286                    text.push_str(l);
287                    text.push('\n');
288                }
289                let _ = writeln!(text, "// sokf:end {name}");
290                match expected.iter_mut().find(|(n, _)| *n == name) {
291                    Some((_, acc)) => acc.extend(lines),
292                    None => expected.push((name.to_string(), lines)),
293                }
294            }
295            text.push_str("tail\n");
296            (text, expected)
297        })
298    }
299
300    // sokf-tests: FORMAT_P-6
301    proptest! {
302        #![proptest_config(crate::proptest_cases::cases(256))]
303
304        #[test]
305        fn extraction_concatenates_same_named_regions_and_strips_markers((text, expected) in arb_file()) {
306            for (name, lines) in &expected {
307                let want = lines.iter().fold(String::new(), |mut out, l| {
308                    let _ = writeln!(out, "{l}");
309                    out
310                });
311                prop_assert_eq!(extract(&text, Some(name)).unwrap().unwrap(), want);
312            }
313            prop_assert_eq!(extract(&text, Some("absent")).unwrap(), None);
314            let whole = extract(&text, None).unwrap().unwrap();
315            prop_assert!(!whole.contains("sokf:begin") && !whole.contains("sokf:end"));
316            let all_lines: usize = expected.iter().map(|(_, l)| l.len()).sum();
317            prop_assert_eq!(whole.lines().count(), all_lines + 2);
318        }
319    }
320}