domainforge_core/formatter/
comments.rs1use std::collections::BTreeMap;
7
8#[derive(Debug, Clone, PartialEq)]
10pub struct Comment {
11 pub text: String,
13 pub line: usize,
15 pub is_trailing: bool,
17}
18
19pub fn extract_comments(source: &str) -> BTreeMap<usize, Vec<Comment>> {
24 let mut comments: BTreeMap<usize, Vec<Comment>> = BTreeMap::new();
25
26 #[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 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
118pub 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 let mut decl_lines = declaration_lines.to_vec();
130 decl_lines.sort();
131
132 for &decl_line in &decl_lines {
134 let mut leading_comments = Vec::new();
135
136 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 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 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#[derive(Debug, Clone)]
171pub struct CommentedSource {
172 pub source: String,
174 pub comments: BTreeMap<usize, Vec<Comment>>,
176 pub file_header_comments: Vec<Comment>,
178}
179
180impl CommentedSource {
181 pub fn new(source: &str) -> Self {
183 let comments = extract_comments(source);
184
185 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 break;
202 }
203 }
204
205 Self {
206 source: source.to_string(),
207 comments,
208 file_header_comments,
209 }
210 }
211
212 pub fn leading_comments_for(&self, line: usize) -> Vec<&Comment> {
214 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 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}