]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast/src/util/comments.rs
Auto merge of #90253 - Kobzol:hash-stable-sort-index-map, r=cjgillot
[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<'a>(lines: &'a [&str], kind: CommentKind) -> Option<String> {
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             // Whatever happens, we skip the first line.
55             let mut i = if lines[0].trim_start().starts_with('*') { 0 } else { 1 };
56             let mut j = lines.len();
57
58             while i < j && lines[i].trim().is_empty() {
59                 i += 1;
60             }
61             while j > i && lines[j - 1].trim().is_empty() {
62                 j -= 1;
63             }
64             &lines[i..j]
65         } else {
66             lines
67         };
68
69         for line in lines {
70             for (j, c) in line.chars().enumerate() {
71                 if j > i || !"* \t".contains(c) {
72                     return None;
73                 }
74                 if c == '*' {
75                     if first {
76                         i = j;
77                         first = false;
78                     } else if i != j {
79                         return None;
80                     }
81                     break;
82                 }
83             }
84             if i >= line.len() {
85                 return None;
86             }
87         }
88         if lines.is_empty() { None } else { Some(lines[0][..i].into()) }
89     }
90
91     let data_s = data.as_str();
92     if data_s.contains('\n') {
93         let mut lines = data_s.lines().collect::<Vec<&str>>();
94         let mut changes = false;
95         let lines = if let Some((i, j)) = get_vertical_trim(&lines) {
96             changes = true;
97             // remove whitespace-only lines from the start/end of lines
98             &mut lines[i..j]
99         } else {
100             &mut lines
101         };
102         if let Some(horizontal) = get_horizontal_trim(&lines, kind) {
103             changes = true;
104             // remove a "[ \t]*\*" block from each line, if possible
105             for line in lines.iter_mut() {
106                 if let Some(tmp) = line.strip_prefix(&horizontal) {
107                     *line = tmp;
108                     if kind == CommentKind::Block
109                         && (*line == "*" || line.starts_with("* ") || line.starts_with("**"))
110                     {
111                         *line = &line[1..];
112                     }
113                 }
114             }
115         }
116         if changes {
117             return Symbol::intern(&lines.join("\n"));
118         }
119     }
120     data
121 }
122
123 /// Returns `None` if the first `col` chars of `s` contain a non-whitespace char.
124 /// Otherwise returns `Some(k)` where `k` is first char offset after that leading
125 /// whitespace. Note that `k` may be outside bounds of `s`.
126 fn all_whitespace(s: &str, col: CharPos) -> Option<usize> {
127     let mut idx = 0;
128     for (i, ch) in s.char_indices().take(col.to_usize()) {
129         if !ch.is_whitespace() {
130             return None;
131         }
132         idx = i + ch.len_utf8();
133     }
134     Some(idx)
135 }
136
137 fn trim_whitespace_prefix(s: &str, col: CharPos) -> &str {
138     let len = s.len();
139     match all_whitespace(&s, col) {
140         Some(col) => {
141             if col < len {
142                 &s[col..]
143             } else {
144                 ""
145             }
146         }
147         None => s,
148     }
149 }
150
151 fn split_block_comment_into_lines(text: &str, col: CharPos) -> Vec<String> {
152     let mut res: Vec<String> = vec![];
153     let mut lines = text.lines();
154     // just push the first line
155     res.extend(lines.next().map(|it| it.to_string()));
156     // for other lines, strip common whitespace prefix
157     for line in lines {
158         res.push(trim_whitespace_prefix(line, col).to_string())
159     }
160     res
161 }
162
163 // it appears this function is called only from pprust... that's
164 // probably not a good thing.
165 pub fn gather_comments(sm: &SourceMap, path: FileName, src: String) -> Vec<Comment> {
166     let sm = SourceMap::new(sm.path_mapping().clone());
167     let source_file = sm.new_source_file(path, src);
168     let text = (*source_file.src.as_ref().unwrap()).clone();
169
170     let text: &str = text.as_str();
171     let start_bpos = source_file.start_pos;
172     let mut pos = 0;
173     let mut comments: Vec<Comment> = Vec::new();
174     let mut code_to_the_left = false;
175
176     if let Some(shebang_len) = rustc_lexer::strip_shebang(text) {
177         comments.push(Comment {
178             style: CommentStyle::Isolated,
179             lines: vec![text[..shebang_len].to_string()],
180             pos: start_bpos,
181         });
182         pos += shebang_len;
183     }
184
185     for token in rustc_lexer::tokenize(&text[pos..]) {
186         let token_text = &text[pos..pos + token.len];
187         match token.kind {
188             rustc_lexer::TokenKind::Whitespace => {
189                 if let Some(mut idx) = token_text.find('\n') {
190                     code_to_the_left = false;
191                     while let Some(next_newline) = &token_text[idx + 1..].find('\n') {
192                         idx += 1 + next_newline;
193                         comments.push(Comment {
194                             style: CommentStyle::BlankLine,
195                             lines: vec![],
196                             pos: start_bpos + BytePos((pos + idx) as u32),
197                         });
198                     }
199                 }
200             }
201             rustc_lexer::TokenKind::BlockComment { doc_style, .. } => {
202                 if doc_style.is_none() {
203                     let code_to_the_right =
204                         !matches!(text[pos + token.len..].chars().next(), Some('\r' | '\n'));
205                     let style = match (code_to_the_left, code_to_the_right) {
206                         (_, true) => CommentStyle::Mixed,
207                         (false, false) => CommentStyle::Isolated,
208                         (true, false) => CommentStyle::Trailing,
209                     };
210
211                     // Count the number of chars since the start of the line by rescanning.
212                     let pos_in_file = start_bpos + BytePos(pos as u32);
213                     let line_begin_in_file = source_file.line_begin_pos(pos_in_file);
214                     let line_begin_pos = (line_begin_in_file - start_bpos).to_usize();
215                     let col = CharPos(text[line_begin_pos..pos].chars().count());
216
217                     let lines = split_block_comment_into_lines(token_text, col);
218                     comments.push(Comment { style, lines, pos: pos_in_file })
219                 }
220             }
221             rustc_lexer::TokenKind::LineComment { doc_style } => {
222                 if doc_style.is_none() {
223                     comments.push(Comment {
224                         style: if code_to_the_left {
225                             CommentStyle::Trailing
226                         } else {
227                             CommentStyle::Isolated
228                         },
229                         lines: vec![token_text.to_string()],
230                         pos: start_bpos + BytePos(pos as u32),
231                     })
232                 }
233             }
234             _ => {
235                 code_to_the_left = true;
236             }
237         }
238         pos += token.len;
239     }
240
241     comments
242 }