Skip to main content

carve/includes/
regions.rs

1use super::*;
2
3pub(super) fn source_lines(source: &str) -> Vec<&str> {
4    let bytes = source.as_bytes();
5    let mut lines = Vec::new();
6    let mut start = 0;
7    let mut i = 0;
8    while i < bytes.len() {
9        if matches!(bytes[i], b'\r' | b'\n') {
10            lines.push(&source[start..i]);
11            if bytes[i] == b'\r' && bytes.get(i + 1) == Some(&b'\n') {
12                i += 1;
13            }
14            start = i + 1;
15        }
16        i += 1;
17    }
18    if start < source.len() {
19        lines.push(&source[start..]);
20    }
21    lines
22}
23
24/// Physical lines in a file. A leading U+FEFF is not content, so a file
25/// holding only one has no lines.
26pub(super) fn content_line_count(source: &str) -> usize {
27    source_lines(source.strip_prefix('\u{FEFF}').unwrap_or(source)).len()
28}
29
30pub(super) fn slice_lines(source: &str, range: (usize, usize)) -> String {
31    let lines = source_lines(source);
32    let start = range.0.saturating_sub(1);
33    let end = range.1.min(lines.len());
34    if start >= end {
35        return String::new();
36    }
37    lines[start..end].join("\n")
38}
39
40/// Which marker set a region lookup uses (spec I1b).
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum IncludeRegionMode {
43    /// A Carve include: only `%% #region` / `%% #endregion` are markers.
44    Carve,
45    /// A `@code` include: the source-comment forms are markers too.
46    Code,
47}
48
49/// The 1-based, inclusive content lines of a region. The opening marker is on
50/// `start - 1`; an empty region has `end == start - 1`.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct IncludeRegion {
53    /// First content line.
54    pub start: usize,
55    /// Last content line.
56    pub end: usize,
57}
58
59/// The region is missing, or a marker in the file is malformed or unpaired.
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub struct IncludeRegionError;
62
63impl IncludeRegionError {
64    /// The warning rule expansion reports for this failure.
65    pub fn rule(&self) -> &'static str {
66        "include-region-invalid"
67    }
68}
69
70/// Resolve `@region:name` in a file's text exactly as [`expand_includes`] does,
71/// so a host (an editor jumping to a region) follows the engine's marker rules.
72pub fn select_include_region(
73    source: &str,
74    name: &str,
75    mode: IncludeRegionMode,
76) -> Result<IncludeRegion, IncludeRegionError> {
77    region_range(source, name, matches!(mode, IncludeRegionMode::Code))
78        .map(|(start, end)| IncludeRegion { start, end })
79        .ok_or(IncludeRegionError)
80}
81
82pub(super) enum Marker<'a> {
83    /// Not a marker line.
84    None,
85    Malformed,
86    Region {
87        closing: bool,
88        name: &'a str,
89    },
90}
91
92/// Reads one physical line against the I1b marker grammar. Without `code`,
93/// only `%%` lines are markers.
94pub(super) fn region_marker(raw_line: &str, code: bool) -> Marker<'_> {
95    let line = raw_line.trim_start_matches([' ', '\t']);
96    let (body, closer) = if line.starts_with("%%") && !line.starts_with("%%%") {
97        (&line[2..], "")
98    } else if !code {
99        return Marker::None;
100    } else if line.starts_with("//") || line.starts_with("--") {
101        (&line[2..], "")
102    } else if let Some(body) = line.strip_prefix("/*") {
103        (body, "*/")
104    } else if let Some(body) = line.strip_prefix("<!--") {
105        (body, "-->")
106    } else {
107        (line, "")
108    };
109    let body = body.trim_start_matches([' ', '\t']);
110    let (closing, rest) = if let Some(rest) = body.strip_prefix("#endregion") {
111        (true, rest)
112    } else if let Some(rest) = body.strip_prefix("#region") {
113        (false, rest)
114    } else {
115        return Marker::None;
116    };
117    if rest
118        .as_bytes()
119        .first()
120        .is_some_and(|c| c.is_ascii_alphanumeric() || *c == b'_')
121    {
122        return Marker::None;
123    }
124    let rest = rest.trim_end_matches([' ', '\t']);
125    let Some(rest) = (if closer.is_empty() {
126        Some(rest)
127    } else {
128        rest.strip_suffix(closer)
129            .map(|rest| rest.trim_end_matches([' ', '\t']))
130    }) else {
131        return Marker::Malformed;
132    };
133    if rest.is_empty() {
134        return Marker::Region { closing, name: "" };
135    }
136    let Some(name) = rest.strip_prefix([' ', '\t']) else {
137        return Marker::Malformed;
138    };
139    let name = name.trim_start_matches([' ', '\t']);
140    if name.is_empty()
141        || !name.chars().next().is_some_and(is_ident_start)
142        || !name.chars().all(is_ident_rest)
143    {
144        return Marker::Malformed;
145    }
146    Marker::Region { closing, name }
147}
148
149/// A `{table}` include drops a record that is a well-formed marker line (I1d).
150/// `#region` without a name is no well-formed opener, so it stays a record.
151pub(crate) fn is_table_record_marker(line: &str) -> bool {
152    match region_marker(line.strip_suffix('\r').unwrap_or(line), true) {
153        Marker::Region { closing, name } => closing || !name.is_empty(),
154        _ => false,
155    }
156}
157
158pub(super) fn region_range(source: &str, selected: &str, code: bool) -> Option<(usize, usize)> {
159    // I1b: the file's leading U+FEFF is not content, so it cannot hide a line-1 marker.
160    let source = source.strip_prefix('\u{FEFF}').unwrap_or(source);
161    let mut seen = HashSet::new();
162    let mut stack: Vec<(&str, usize)> = Vec::new();
163    let mut range = None;
164    for (index, raw_line) in source_lines(source).into_iter().enumerate() {
165        let (closing, name) = match region_marker(raw_line, code) {
166            Marker::None => continue,
167            Marker::Malformed => return None,
168            Marker::Region { closing, name } => (closing, name),
169        };
170        if closing {
171            let (open_name, open_index) = stack.pop()?;
172            if !name.is_empty() && name != open_name {
173                return None;
174            }
175            if open_name == selected {
176                range = Some((open_index + 2, index));
177            }
178        } else {
179            if name.is_empty() || !seen.insert(name) {
180                return None;
181            }
182            stack.push((name, index));
183        }
184    }
185    if stack.is_empty() {
186        range
187    } else {
188        None
189    }
190}