Skip to main content

domainforge_core/formatter/
comments.rs

1//! Comment extraction and preservation utilities.
2//!
3//! This module handles extracting comments from source code and associating
4//! them with their corresponding declarations.
5
6use std::collections::BTreeMap;
7
8/// A comment extracted from source code.
9#[derive(Debug, Clone, PartialEq)]
10pub struct Comment {
11    /// The comment text (without the leading //)
12    pub text: String,
13    /// Line number (1-indexed)
14    pub line: usize,
15    /// Whether this is a trailing comment (on same line as code)
16    pub is_trailing: bool,
17}
18
19/// Extracts comments from source code, preserving their positions.
20///
21/// Returns a map of line numbers to comments, where the line number
22/// indicates where the comment appears in the source.
23pub fn extract_comments(source: &str) -> BTreeMap<usize, Vec<Comment>> {
24    let mut comments: BTreeMap<usize, Vec<Comment>> = BTreeMap::new();
25
26    // A `//` inside a string literal (e.g. `"https://example.com"`) is not a
27    // comment start, so this scans char-by-char tracking whether we are
28    // inside a `"…"` string (with `\"` escapes) or a `"""…"""` multiline
29    // string (per `grammar/sea.pest`'s `string_literal`/`multiline_string`),
30    // rather than treating any `//` found on a line as a comment.
31    #[derive(PartialEq)]
32    enum State {
33        Normal,
34        InString,
35        InMultilineString,
36    }
37
38    let chars: Vec<char> = source.chars().collect();
39    let len = chars.len();
40    let mut i = 0usize;
41    let mut line_num = 1usize;
42    let mut line_start = 0usize;
43    let mut state = State::Normal;
44
45    let is_triple_quote = |chars: &[char], at: usize| -> bool {
46        at + 2 < len && chars[at] == '"' && chars[at + 1] == '"' && chars[at + 2] == '"'
47    };
48
49    while i < len {
50        let c = chars[i];
51        match state {
52            State::Normal => match c {
53                '"' if is_triple_quote(&chars, i) => {
54                    state = State::InMultilineString;
55                    i += 3;
56                }
57                '"' => {
58                    state = State::InString;
59                    i += 1;
60                }
61                '/' if i + 1 < len && chars[i + 1] == '/' => {
62                    let comment_start = i;
63                    let mut j = i + 2;
64                    while j < len && chars[j] != '\n' {
65                        j += 1;
66                    }
67                    let text: String = chars[i + 2..j].iter().collect::<String>();
68                    let before: String = chars[line_start..comment_start].iter().collect();
69                    let is_trailing = !before.trim().is_empty();
70
71                    comments.entry(line_num).or_default().push(Comment {
72                        text: text.trim().to_string(),
73                        line: line_num,
74                        is_trailing,
75                    });
76                    i = j;
77                }
78                '\n' => {
79                    line_num += 1;
80                    i += 1;
81                    line_start = i;
82                }
83                _ => i += 1,
84            },
85            State::InString => match c {
86                '\\' if i + 1 < len => i += 2,
87                '"' => {
88                    state = State::Normal;
89                    i += 1;
90                }
91                '\n' => {
92                    // Not valid per grammar (string literals don't span
93                    // lines), but stay conservative rather than panic.
94                    line_num += 1;
95                    i += 1;
96                    line_start = i;
97                }
98                _ => i += 1,
99            },
100            State::InMultilineString => {
101                if is_triple_quote(&chars, i) {
102                    state = State::Normal;
103                    i += 3;
104                } else if c == '\n' {
105                    line_num += 1;
106                    i += 1;
107                    line_start = i;
108                } else {
109                    i += 1;
110                }
111            }
112        }
113    }
114
115    comments
116}
117
118/// Groups comments with declarations.
119///
120/// Associates each leading comment block with the next declaration's line.
121/// Returns a map from declaration start line to its leading comments.
122pub fn associate_comments_with_lines(
123    comments: &BTreeMap<usize, Vec<Comment>>,
124    declaration_lines: &[usize],
125) -> BTreeMap<usize, Vec<Comment>> {
126    let mut associated: BTreeMap<usize, Vec<Comment>> = BTreeMap::new();
127
128    // Sort declaration lines
129    let mut decl_lines = declaration_lines.to_vec();
130    decl_lines.sort();
131
132    // For each declaration, find leading comments
133    for &decl_line in &decl_lines {
134        let mut leading_comments = Vec::new();
135
136        // Look backwards from the declaration for comment lines
137        let mut check_line = decl_line.saturating_sub(1);
138        while check_line > 0 {
139            if let Some(line_comments) = comments.get(&check_line) {
140                // Only consider non-trailing comments as leading
141                let non_trailing: Vec<_> = line_comments
142                    .iter()
143                    .filter(|c| !c.is_trailing)
144                    .cloned()
145                    .collect();
146
147                if non_trailing.is_empty() {
148                    break;
149                }
150
151                // Insert at beginning to maintain order
152                for c in non_trailing.into_iter().rev() {
153                    leading_comments.insert(0, c);
154                }
155                check_line -= 1;
156            } else {
157                break;
158            }
159        }
160
161        if !leading_comments.is_empty() {
162            associated.insert(decl_line, leading_comments);
163        }
164    }
165
166    associated
167}
168
169/// Represents a source file with comments tracked separately.
170#[derive(Debug, Clone)]
171pub struct CommentedSource {
172    /// The original source code
173    pub source: String,
174    /// Map of line numbers to comments
175    pub comments: BTreeMap<usize, Vec<Comment>>,
176    /// Leading comments to output before the file header
177    pub file_header_comments: Vec<Comment>,
178}
179
180impl CommentedSource {
181    /// Parse source code and extract comments.
182    pub fn new(source: &str) -> Self {
183        let comments = extract_comments(source);
184
185        // Find the first non-comment, non-empty line for header comments
186        let mut file_header_comments = Vec::new();
187        for (line_idx, line) in source.lines().enumerate() {
188            let line_num = line_idx + 1;
189            let trimmed = line.trim();
190
191            if trimmed.is_empty() {
192                continue;
193            }
194
195            if trimmed.starts_with("//") {
196                if let Some(line_comments) = comments.get(&line_num) {
197                    file_header_comments.extend(line_comments.iter().cloned());
198                }
199            } else {
200                // Found first non-comment line, stop
201                break;
202            }
203        }
204
205        Self {
206            source: source.to_string(),
207            comments,
208            file_header_comments,
209        }
210    }
211
212    /// Get leading comments for a specific line.
213    pub fn leading_comments_for(&self, line: usize) -> Vec<&Comment> {
214        // Look at previous lines for consecutive comments
215        let mut result = Vec::new();
216        let mut check_line = line.saturating_sub(1);
217
218        while check_line > 0 {
219            if let Some(comments) = self.comments.get(&check_line) {
220                let non_trailing: Vec<_> = comments.iter().filter(|c| !c.is_trailing).collect();
221
222                if non_trailing.is_empty() {
223                    break;
224                }
225
226                for c in non_trailing.into_iter().rev() {
227                    result.insert(0, c);
228                }
229                check_line -= 1;
230            } else {
231                break;
232            }
233        }
234
235        result
236    }
237
238    /// Check if there are any comments in the source.
239    pub fn has_comments(&self) -> bool {
240        !self.comments.is_empty()
241    }
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247
248    #[test]
249    fn test_extract_line_comments() {
250        let source = r#"
251// This is a comment
252Entity "Foo"
253"#;
254        let comments = extract_comments(source);
255        assert_eq!(comments.len(), 1);
256        let line2_comments = comments.get(&2).unwrap();
257        assert_eq!(line2_comments[0].text, "This is a comment");
258        assert!(!line2_comments[0].is_trailing);
259    }
260
261    #[test]
262    fn test_extract_trailing_comments() {
263        let source = r#"Entity "Foo" // trailing comment
264"#;
265        let comments = extract_comments(source);
266        let line1_comments = comments.get(&1).unwrap();
267        assert_eq!(line1_comments[0].text, "trailing comment");
268        assert!(line1_comments[0].is_trailing);
269    }
270
271    #[test]
272    fn test_multiple_comments() {
273        let source = r#"
274// Comment 1
275// Comment 2
276Entity "Foo"
277"#;
278        let comments = extract_comments(source);
279        assert_eq!(comments.len(), 2);
280        assert!(comments.contains_key(&2));
281        assert!(comments.contains_key(&3));
282    }
283
284    #[test]
285    fn test_commented_source() {
286        let source = r#"// File header comment
287Entity "Foo"
288"#;
289        let cs = CommentedSource::new(source);
290        assert_eq!(cs.file_header_comments.len(), 1);
291        assert_eq!(cs.file_header_comments[0].text, "File header comment");
292    }
293}