use std::collections::BTreeMap;
#[derive(Debug, Clone, PartialEq)]
pub struct Comment {
pub text: String,
pub line: usize,
pub is_trailing: bool,
}
pub fn extract_comments(source: &str) -> BTreeMap<usize, Vec<Comment>> {
let mut comments: BTreeMap<usize, Vec<Comment>> = BTreeMap::new();
#[derive(PartialEq)]
enum State {
Normal,
InString,
InMultilineString,
}
let chars: Vec<char> = source.chars().collect();
let len = chars.len();
let mut i = 0usize;
let mut line_num = 1usize;
let mut line_start = 0usize;
let mut state = State::Normal;
let is_triple_quote = |chars: &[char], at: usize| -> bool {
at + 2 < len && chars[at] == '"' && chars[at + 1] == '"' && chars[at + 2] == '"'
};
while i < len {
let c = chars[i];
match state {
State::Normal => match c {
'"' if is_triple_quote(&chars, i) => {
state = State::InMultilineString;
i += 3;
}
'"' => {
state = State::InString;
i += 1;
}
'/' if i + 1 < len && chars[i + 1] == '/' => {
let comment_start = i;
let mut j = i + 2;
while j < len && chars[j] != '\n' {
j += 1;
}
let text: String = chars[i + 2..j].iter().collect::<String>();
let before: String = chars[line_start..comment_start].iter().collect();
let is_trailing = !before.trim().is_empty();
comments.entry(line_num).or_default().push(Comment {
text: text.trim().to_string(),
line: line_num,
is_trailing,
});
i = j;
}
'\n' => {
line_num += 1;
i += 1;
line_start = i;
}
_ => i += 1,
},
State::InString => match c {
'\\' if i + 1 < len => i += 2,
'"' => {
state = State::Normal;
i += 1;
}
'\n' => {
line_num += 1;
i += 1;
line_start = i;
}
_ => i += 1,
},
State::InMultilineString => {
if is_triple_quote(&chars, i) {
state = State::Normal;
i += 3;
} else if c == '\n' {
line_num += 1;
i += 1;
line_start = i;
} else {
i += 1;
}
}
}
}
comments
}
pub fn associate_comments_with_lines(
comments: &BTreeMap<usize, Vec<Comment>>,
declaration_lines: &[usize],
) -> BTreeMap<usize, Vec<Comment>> {
let mut associated: BTreeMap<usize, Vec<Comment>> = BTreeMap::new();
let mut decl_lines = declaration_lines.to_vec();
decl_lines.sort();
for &decl_line in &decl_lines {
let mut leading_comments = Vec::new();
let mut check_line = decl_line.saturating_sub(1);
while check_line > 0 {
if let Some(line_comments) = comments.get(&check_line) {
let non_trailing: Vec<_> = line_comments
.iter()
.filter(|c| !c.is_trailing)
.cloned()
.collect();
if non_trailing.is_empty() {
break;
}
for c in non_trailing.into_iter().rev() {
leading_comments.insert(0, c);
}
check_line -= 1;
} else {
break;
}
}
if !leading_comments.is_empty() {
associated.insert(decl_line, leading_comments);
}
}
associated
}
#[derive(Debug, Clone)]
pub struct CommentedSource {
pub source: String,
pub comments: BTreeMap<usize, Vec<Comment>>,
pub file_header_comments: Vec<Comment>,
}
impl CommentedSource {
pub fn new(source: &str) -> Self {
let comments = extract_comments(source);
let mut file_header_comments = Vec::new();
for (line_idx, line) in source.lines().enumerate() {
let line_num = line_idx + 1;
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
if trimmed.starts_with("//") {
if let Some(line_comments) = comments.get(&line_num) {
file_header_comments.extend(line_comments.iter().cloned());
}
} else {
break;
}
}
Self {
source: source.to_string(),
comments,
file_header_comments,
}
}
pub fn leading_comments_for(&self, line: usize) -> Vec<&Comment> {
let mut result = Vec::new();
let mut check_line = line.saturating_sub(1);
while check_line > 0 {
if let Some(comments) = self.comments.get(&check_line) {
let non_trailing: Vec<_> = comments.iter().filter(|c| !c.is_trailing).collect();
if non_trailing.is_empty() {
break;
}
for c in non_trailing.into_iter().rev() {
result.insert(0, c);
}
check_line -= 1;
} else {
break;
}
}
result
}
pub fn has_comments(&self) -> bool {
!self.comments.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_extract_line_comments() {
let source = r#"
// This is a comment
Entity "Foo"
"#;
let comments = extract_comments(source);
assert_eq!(comments.len(), 1);
let line2_comments = comments.get(&2).unwrap();
assert_eq!(line2_comments[0].text, "This is a comment");
assert!(!line2_comments[0].is_trailing);
}
#[test]
fn test_extract_trailing_comments() {
let source = r#"Entity "Foo" // trailing comment
"#;
let comments = extract_comments(source);
let line1_comments = comments.get(&1).unwrap();
assert_eq!(line1_comments[0].text, "trailing comment");
assert!(line1_comments[0].is_trailing);
}
#[test]
fn test_multiple_comments() {
let source = r#"
// Comment 1
// Comment 2
Entity "Foo"
"#;
let comments = extract_comments(source);
assert_eq!(comments.len(), 2);
assert!(comments.contains_key(&2));
assert!(comments.contains_key(&3));
}
#[test]
fn test_commented_source() {
let source = r#"// File header comment
Entity "Foo"
"#;
let cs = CommentedSource::new(source);
assert_eq!(cs.file_header_comments.len(), 1);
assert_eq!(cs.file_header_comments[0].text, "File header comment");
}
}