foundry_common/comments/
mod.rs

1mod comment;
2
3use comment::{Comment, CommentStyle};
4use solar_parse::{
5    ast::{CommentKind, Span},
6    interface::{BytePos, CharPos, SourceMap, source_map::SourceFile},
7    lexer::token::RawTokenKind as TokenKind,
8};
9use std::fmt;
10
11pub struct Comments {
12    comments: std::vec::IntoIter<Comment>,
13}
14
15impl fmt::Debug for Comments {
16    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17        f.write_str("Comments")?;
18        f.debug_list().entries(self.iter()).finish()
19    }
20}
21
22/// Returns `None` if the first `col` chars of `s` contain a non-whitespace char.
23/// Otherwise returns `Some(k)` where `k` is first char offset after that leading
24/// whitespace. Note that `k` may be outside bounds of `s`.
25fn all_whitespace(s: &str, col: CharPos) -> Option<usize> {
26    let mut idx = 0;
27    for (i, ch) in s.char_indices().take(col.to_usize()) {
28        if !ch.is_whitespace() {
29            return None;
30        }
31        idx = i + ch.len_utf8();
32    }
33    Some(idx)
34}
35
36fn trim_whitespace_prefix(s: &str, col: CharPos) -> &str {
37    let len = s.len();
38    match all_whitespace(s, col) {
39        Some(col) => {
40            if col < len {
41                &s[col..]
42            } else {
43                ""
44            }
45        }
46        None => s,
47    }
48}
49
50fn split_block_comment_into_lines(text: &str, col: CharPos) -> Vec<String> {
51    let mut res: Vec<String> = vec![];
52    let mut lines = text.lines();
53    // just push the first line
54    res.extend(lines.next().map(|it| it.to_string()));
55    // for other lines, strip common whitespace prefix
56    for line in lines {
57        res.push(trim_whitespace_prefix(line, col).to_string())
58    }
59    res
60}
61
62/// Returns the `BytePos` of the beginning of the current line.
63fn line_begin_pos(sf: &SourceFile, pos: BytePos) -> BytePos {
64    let pos = sf.relative_position(pos);
65    let line_index = sf.lookup_line(pos).unwrap();
66    let line_start_pos = sf.lines()[line_index];
67    sf.absolute_position(line_start_pos)
68}
69
70fn gather_comments(sf: &SourceFile) -> Vec<Comment> {
71    let text = sf.src.as_str();
72    let start_bpos = sf.start_pos;
73    let mut pos = 0;
74    let mut comments: Vec<Comment> = Vec::new();
75    let mut code_to_the_left = false;
76
77    let make_span = |range: std::ops::Range<usize>| {
78        Span::new(start_bpos + range.start as u32, start_bpos + range.end as u32)
79    };
80
81    /*
82    if let Some(shebang_len) = strip_shebang(text) {
83        comments.push(Comment {
84            style: CommentStyle::Isolated,
85            lines: vec![text[..shebang_len].to_string()],
86            pos: start_bpos,
87        });
88        pos += shebang_len;
89    }
90    */
91
92    for token in solar_parse::Cursor::new(&text[pos..]) {
93        let token_range = pos..pos + token.len as usize;
94        let span = make_span(token_range.clone());
95        let token_text = &text[token_range];
96        match token.kind {
97            TokenKind::Whitespace => {
98                if let Some(mut idx) = token_text.find('\n') {
99                    code_to_the_left = false;
100
101                    // NOTE(dani): this used to be `while`, but we want only a single blank line.
102                    if let Some(next_newline) = token_text[idx + 1..].find('\n') {
103                        idx += 1 + next_newline;
104                        let pos = pos + idx;
105                        comments.push(Comment {
106                            is_doc: false,
107                            kind: CommentKind::Line,
108                            style: CommentStyle::BlankLine,
109                            lines: vec![],
110                            span: make_span(pos..pos),
111                        });
112                    }
113                }
114            }
115            TokenKind::BlockComment { is_doc, .. } => {
116                let code_to_the_right =
117                    !matches!(text[pos + token.len as usize..].chars().next(), Some('\r' | '\n'));
118                let style = match (code_to_the_left, code_to_the_right) {
119                    (_, true) => CommentStyle::Mixed,
120                    (false, false) => CommentStyle::Isolated,
121                    (true, false) => CommentStyle::Trailing,
122                };
123                let kind = CommentKind::Block;
124
125                // Count the number of chars since the start of the line by rescanning.
126                let pos_in_file = start_bpos + BytePos(pos as u32);
127                let line_begin_in_file = line_begin_pos(sf, pos_in_file);
128                let line_begin_pos = (line_begin_in_file - start_bpos).to_usize();
129                let col = CharPos(text[line_begin_pos..pos].chars().count());
130
131                let lines = split_block_comment_into_lines(token_text, col);
132                comments.push(Comment { is_doc, kind, style, lines, span })
133            }
134            TokenKind::LineComment { is_doc } => {
135                comments.push(Comment {
136                    is_doc,
137                    kind: CommentKind::Line,
138                    style: if code_to_the_left {
139                        CommentStyle::Trailing
140                    } else {
141                        CommentStyle::Isolated
142                    },
143                    lines: vec![token_text.to_string()],
144                    span,
145                });
146            }
147            _ => {
148                code_to_the_left = true;
149            }
150        }
151        pos += token.len as usize;
152    }
153
154    comments
155}
156
157impl Comments {
158    pub fn new(sf: &SourceFile) -> Self {
159        Self { comments: gather_comments(sf).into_iter() }
160    }
161
162    pub fn peek(&self) -> Option<&Comment> {
163        self.comments.as_slice().first()
164    }
165
166    #[allow(clippy::should_implement_trait)]
167    pub fn next(&mut self) -> Option<Comment> {
168        self.comments.next()
169    }
170
171    pub fn iter(&self) -> impl Iterator<Item = &Comment> {
172        self.comments.as_slice().iter()
173    }
174
175    pub fn trailing_comment(
176        &mut self,
177        sm: &SourceMap,
178        span: Span,
179        next_pos: Option<BytePos>,
180    ) -> Option<Comment> {
181        if let Some(cmnt) = self.peek() {
182            if cmnt.style != CommentStyle::Trailing {
183                return None;
184            }
185            let span_line = sm.lookup_char_pos(span.hi());
186            let comment_line = sm.lookup_char_pos(cmnt.pos());
187            let next = next_pos.unwrap_or_else(|| cmnt.pos() + BytePos(1));
188            if span.hi() < cmnt.pos() && cmnt.pos() < next && span_line.line == comment_line.line {
189                return Some(self.next().unwrap());
190            }
191        }
192
193        None
194    }
195}