]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast/src/util/comments.rs
Move `{core,std}::stream::Stream` to `{core,std}::async_iter::AsyncIterator`.
[rust.git] / compiler / rustc_ast / src / util / comments.rs
1 use crate::token::CommentKind;
2 use rustc_span::source_map::SourceMap;
3 use rustc_span::{BytePos, CharPos, FileName, Pos, Symbol};
4
5 #[cfg(test)]
6 mod tests;
7
8 #[derive(Clone, Copy, PartialEq, Debug)]
9 pub enum CommentStyle {
10     /// No code on either side of each line of the comment
11     Isolated,
12     /// Code exists to the left of the comment
13     Trailing,
14     /// Code before /* foo */ and after the comment
15     Mixed,
16     /// Just a manual blank line "\n\n", for layout
17     BlankLine,
18 }
19
20 #[derive(Clone)]
21 pub struct Comment {
22     pub style: CommentStyle,
23     pub lines: Vec<String>,
24     pub pos: BytePos,
25 }
26
27 /// Makes a doc string more presentable to users.
28 /// Used by rustdoc and perhaps other tools, but not by rustc.
29 pub fn beautify_doc_string(data: Symbol, kind: CommentKind) -> Symbol {
30     fn get_vertical_trim(lines: &[&str]) -> Option<(usize, usize)> {
31         let mut i = 0;
32         let mut j = lines.len();
33         // first line of all-stars should be omitted
34         if !lines.is_empty() && lines[0].chars().all(|c| c == '*') {
35             i += 1;
36         }
37
38         // like the first, a last line of all stars should be omitted
39         if j > i && !lines[j - 1].is_empty() && lines[j - 1].chars().all(|c| c == '*') {
40             j -= 1;
41         }
42
43         if i != 0 || j != lines.len() { Some((i, j)) } else { None }
44     }
45
46     fn get_horizontal_trim(lines: &[&str], kind: CommentKind) -> Option<usize> {
47         let mut i = usize::MAX;
48         let mut first = true;
49
50         // In case we have doc comments like `/**` or `/*!`, we want to remove stars if they are
51         // present. However, we first need to strip the empty lines so they don't get in the middle
52         // when we try to compute the "horizontal trim".
53         let lines = if kind == CommentKind::Block {
54             let mut i = 0;
55             let mut j = lines.len();
56
57             while i < j && lines[i].trim().is_empty() {
58                 i += 1;
59             }
60             while j > i && lines[j - 1].trim().is_empty() {
61                 j -= 1;
62             }
63             &lines[i..j]
64         } else {
65             lines
66         };
67
68         for line in lines {
69             for (j, c) in line.chars().enumerate() {
70                 if j > i || !"* \t".contains(c) {
71                     return None;
72                 }
73                 if c == '*' {
74                     if first {
75                         i = j;
76                         first = false;
77                     } else if i != j {
78                         return None;
79                     }
80                     break;
81                 }
82             }
83             if i >= line.len() {
84                 return None;
85             }
86         }
87         Some(i)
88     }
89
90     let data_s = data.as_str();
91     if data_s.contains('\n') {
92         let mut lines = data_s.lines().collect::<Vec<&str>>();
93         let mut changes = false;
94         let lines = if let Some((i, j)) = get_vertical_trim(&lines) {
95             changes = true;
96             // remove whitespace-only lines from the start/end of lines
97             &mut lines[i..j]
98         } else {
99             &mut lines
100         };
101         if let Some(horizontal) = get_horizontal_trim(&lines, kind) {
102             changes = true;
103             // remove a "[ \t]*\*" block from each line, if possible
104             for line in lines.iter_mut() {
105                 if horizontal + 1 < line.len() {
106                     *line = &line[horizontal + 1..];
107                 }
108             }
109         }
110         if changes {
111             return Symbol::intern(&lines.join("\n"));
112         }
113     }
114     data
115 }
116
117 /// Returns `None` if the first `col` chars of `s` contain a non-whitespace char.
118 /// Otherwise returns `Some(k)` where `k` is first char offset after that leading
119 /// whitespace. Note that `k` may be outside bounds of `s`.
120 fn all_whitespace(s: &str, col: CharPos) -> Option<usize> {
121     let mut idx = 0;
122     for (i, ch) in s.char_indices().take(col.to_usize()) {
123         if !ch.is_whitespace() {
124             return None;
125         }
126         idx = i + ch.len_utf8();
127     }
128     Some(idx)
129 }
130
131 fn trim_whitespace_prefix(s: &str, col: CharPos) -> &str {
132     let len = s.len();
133     match all_whitespace(&s, col) {
134         Some(col) => {
135             if col < len {
136                 &s[col..]
137             } else {
138                 ""
139             }
140         }
141         None => s,
142     }
143 }
144
145 fn split_block_comment_into_lines(text: &str, col: CharPos) -> Vec<String> {
146     let mut res: Vec<String> = vec![];
147     let mut lines = text.lines();
148     // just push the first line
149     res.extend(lines.next().map(|it| it.to_string()));
150     // for other lines, strip common whitespace prefix
151     for line in lines {
152         res.push(trim_whitespace_prefix(line, col).to_string())
153     }
154     res
155 }
156
157 // it appears this function is called only from pprust... that's
158 // probably not a good thing.
159 pub fn gather_comments(sm: &SourceMap, path: FileName, src: String) -> Vec<Comment> {
160     let sm = SourceMap::new(sm.path_mapping().clone());
161     let source_file = sm.new_source_file(path, src);
162     let text = (*source_file.src.as_ref().unwrap()).clone();
163
164     let text: &str = text.as_str();
165     let start_bpos = source_file.start_pos;
166     let mut pos = 0;
167     let mut comments: Vec<Comment> = Vec::new();
168     let mut code_to_the_left = false;
169
170     if let Some(shebang_len) = rustc_lexer::strip_shebang(text) {
171         comments.push(Comment {
172             style: CommentStyle::Isolated,
173             lines: vec![text[..shebang_len].to_string()],
174             pos: start_bpos,
175         });
176         pos += shebang_len;
177     }
178
179     for token in rustc_lexer::tokenize(&text[pos..]) {
180         let token_text = &text[pos..pos + token.len];
181         match token.kind {
182             rustc_lexer::TokenKind::Whitespace => {
183                 if let Some(mut idx) = token_text.find('\n') {
184                     code_to_the_left = false;
185                     while let Some(next_newline) = &token_text[idx + 1..].find('\n') {
186                         idx += 1 + next_newline;
187                         comments.push(Comment {
188                             style: CommentStyle::BlankLine,
189                             lines: vec![],
190                             pos: start_bpos + BytePos((pos + idx) as u32),
191                         });
192                     }
193                 }
194             }
195             rustc_lexer::TokenKind::BlockComment { doc_style, .. } => {
196                 if doc_style.is_none() {
197                     let code_to_the_right =
198                         !matches!(text[pos + token.len..].chars().next(), Some('\r' | '\n'));
199                     let style = match (code_to_the_left, code_to_the_right) {
200                         (_, true) => CommentStyle::Mixed,
201                         (false, false) => CommentStyle::Isolated,
202                         (true, false) => CommentStyle::Trailing,
203                     };
204
205                     // Count the number of chars since the start of the line by rescanning.
206                     let pos_in_file = start_bpos + BytePos(pos as u32);
207                     let line_begin_in_file = source_file.line_begin_pos(pos_in_file);
208                     let line_begin_pos = (line_begin_in_file - start_bpos).to_usize();
209                     let col = CharPos(text[line_begin_pos..pos].chars().count());
210
211                     let lines = split_block_comment_into_lines(token_text, col);
212                     comments.push(Comment { style, lines, pos: pos_in_file })
213                 }
214             }
215             rustc_lexer::TokenKind::LineComment { doc_style } => {
216                 if doc_style.is_none() {
217                     comments.push(Comment {
218                         style: if code_to_the_left {
219                             CommentStyle::Trailing
220                         } else {
221                             CommentStyle::Isolated
222                         },
223                         lines: vec![token_text.to_string()],
224                         pos: start_bpos + BytePos(pos as u32),
225                     })
226                 }
227             }
228             _ => {
229                 code_to_the_left = true;
230             }
231         }
232         pos += token.len;
233     }
234
235     comments
236 }