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