]> git.lizzy.rs Git - rust.git/blob - src/librustc_ast/util/comments.rs
Auto merge of #69482 - lqd:poloniusup, r=nikomatsakis
[rust.git] / src / librustc_ast / util / comments.rs
1 pub use CommentStyle::*;
2
3 use crate::ast;
4 use rustc_span::source_map::SourceMap;
5 use rustc_span::{BytePos, CharPos, FileName, Pos};
6
7 use log::debug;
8 use std::usize;
9
10 #[cfg(test)]
11 mod tests;
12
13 #[derive(Clone, Copy, PartialEq, Debug)]
14 pub enum CommentStyle {
15     /// No code on either side of each line of the comment
16     Isolated,
17     /// Code exists to the left of the comment
18     Trailing,
19     /// Code before /* foo */ and after the comment
20     Mixed,
21     /// Just a manual blank line "\n\n", for layout
22     BlankLine,
23 }
24
25 #[derive(Clone)]
26 pub struct Comment {
27     pub style: CommentStyle,
28     pub lines: Vec<String>,
29     pub pos: BytePos,
30 }
31
32 pub fn is_line_doc_comment(s: &str) -> bool {
33     let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/')
34         || s.starts_with("//!");
35     debug!("is {:?} a doc comment? {}", s, res);
36     res
37 }
38
39 pub fn is_block_doc_comment(s: &str) -> bool {
40     // Prevent `/**/` from being parsed as a doc comment
41     let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*')
42         || s.starts_with("/*!"))
43         && s.len() >= 5;
44     debug!("is {:?} a doc comment? {}", s, res);
45     res
46 }
47
48 // FIXME(#64197): Try to privatize this again.
49 pub fn is_doc_comment(s: &str) -> bool {
50     (s.starts_with("///") && is_line_doc_comment(s))
51         || s.starts_with("//!")
52         || (s.starts_with("/**") && is_block_doc_comment(s))
53         || s.starts_with("/*!")
54 }
55
56 pub fn doc_comment_style(comment: &str) -> ast::AttrStyle {
57     assert!(is_doc_comment(comment));
58     if comment.starts_with("//!") || comment.starts_with("/*!") {
59         ast::AttrStyle::Inner
60     } else {
61         ast::AttrStyle::Outer
62     }
63 }
64
65 pub fn strip_doc_comment_decoration(comment: &str) -> String {
66     /// remove whitespace-only lines from the start/end of lines
67     fn vertical_trim(lines: Vec<String>) -> Vec<String> {
68         let mut i = 0;
69         let mut j = lines.len();
70         // first line of all-stars should be omitted
71         if !lines.is_empty() && lines[0].chars().all(|c| c == '*') {
72             i += 1;
73         }
74
75         while i < j && lines[i].trim().is_empty() {
76             i += 1;
77         }
78         // like the first, a last line of all stars should be omitted
79         if j > i && lines[j - 1].chars().skip(1).all(|c| c == '*') {
80             j -= 1;
81         }
82
83         while j > i && lines[j - 1].trim().is_empty() {
84             j -= 1;
85         }
86
87         lines[i..j].to_vec()
88     }
89
90     /// remove a "[ \t]*\*" block from each line, if possible
91     fn horizontal_trim(lines: Vec<String>) -> Vec<String> {
92         let mut i = usize::MAX;
93         let mut can_trim = true;
94         let mut first = true;
95
96         for line in &lines {
97             for (j, c) in line.chars().enumerate() {
98                 if j > i || !"* \t".contains(c) {
99                     can_trim = false;
100                     break;
101                 }
102                 if c == '*' {
103                     if first {
104                         i = j;
105                         first = false;
106                     } else if i != j {
107                         can_trim = false;
108                     }
109                     break;
110                 }
111             }
112             if i >= line.len() {
113                 can_trim = false;
114             }
115             if !can_trim {
116                 break;
117             }
118         }
119
120         if can_trim {
121             lines.iter().map(|line| (&line[i + 1..line.len()]).to_string()).collect()
122         } else {
123             lines
124         }
125     }
126
127     // one-line comments lose their prefix
128     const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
129
130     for prefix in ONELINERS {
131         if comment.starts_with(*prefix) {
132             return (&comment[prefix.len()..]).to_string();
133         }
134     }
135
136     if comment.starts_with("/*") {
137         let lines =
138             comment[3..comment.len() - 2].lines().map(|s| s.to_string()).collect::<Vec<String>>();
139
140         let lines = vertical_trim(lines);
141         let lines = horizontal_trim(lines);
142
143         return lines.join("\n");
144     }
145
146     panic!("not a doc-comment: {}", comment);
147 }
148
149 /// Returns `None` if the first `col` chars of `s` contain a non-whitespace char.
150 /// Otherwise returns `Some(k)` where `k` is first char offset after that leading
151 /// whitespace. Note that `k` may be outside bounds of `s`.
152 fn all_whitespace(s: &str, col: CharPos) -> Option<usize> {
153     let mut idx = 0;
154     for (i, ch) in s.char_indices().take(col.to_usize()) {
155         if !ch.is_whitespace() {
156             return None;
157         }
158         idx = i + ch.len_utf8();
159     }
160     Some(idx)
161 }
162
163 fn trim_whitespace_prefix(s: &str, col: CharPos) -> &str {
164     let len = s.len();
165     match all_whitespace(&s, col) {
166         Some(col) => {
167             if col < len {
168                 &s[col..]
169             } else {
170                 ""
171             }
172         }
173         None => s,
174     }
175 }
176
177 fn split_block_comment_into_lines(text: &str, col: CharPos) -> Vec<String> {
178     let mut res: Vec<String> = vec![];
179     let mut lines = text.lines();
180     // just push the first line
181     res.extend(lines.next().map(|it| it.to_string()));
182     // for other lines, strip common whitespace prefix
183     for line in lines {
184         res.push(trim_whitespace_prefix(line, col).to_string())
185     }
186     res
187 }
188
189 // it appears this function is called only from pprust... that's
190 // probably not a good thing.
191 pub fn gather_comments(sm: &SourceMap, path: FileName, src: String) -> Vec<Comment> {
192     let sm = SourceMap::new(sm.path_mapping().clone());
193     let source_file = sm.new_source_file(path, src);
194     let text = (*source_file.src.as_ref().unwrap()).clone();
195
196     let text: &str = text.as_str();
197     let start_bpos = source_file.start_pos;
198     let mut pos = 0;
199     let mut comments: Vec<Comment> = Vec::new();
200     let mut code_to_the_left = false;
201
202     if let Some(shebang_len) = rustc_lexer::strip_shebang(text) {
203         comments.push(Comment {
204             style: Isolated,
205             lines: vec![text[..shebang_len].to_string()],
206             pos: start_bpos,
207         });
208         pos += shebang_len;
209     }
210
211     for token in rustc_lexer::tokenize(&text[pos..]) {
212         let token_text = &text[pos..pos + token.len];
213         match token.kind {
214             rustc_lexer::TokenKind::Whitespace => {
215                 if let Some(mut idx) = token_text.find('\n') {
216                     code_to_the_left = false;
217                     while let Some(next_newline) = &token_text[idx + 1..].find('\n') {
218                         idx = idx + 1 + next_newline;
219                         comments.push(Comment {
220                             style: BlankLine,
221                             lines: vec![],
222                             pos: start_bpos + BytePos((pos + idx) as u32),
223                         });
224                     }
225                 }
226             }
227             rustc_lexer::TokenKind::BlockComment { terminated: _ } => {
228                 if !is_block_doc_comment(token_text) {
229                     let code_to_the_right = match text[pos + token.len..].chars().next() {
230                         Some('\r') | Some('\n') => false,
231                         _ => true,
232                     };
233                     let style = match (code_to_the_left, code_to_the_right) {
234                         (true, true) | (false, true) => Mixed,
235                         (false, false) => Isolated,
236                         (true, false) => Trailing,
237                     };
238
239                     // Count the number of chars since the start of the line by rescanning.
240                     let pos_in_file = start_bpos + BytePos(pos as u32);
241                     let line_begin_in_file = source_file.line_begin_pos(pos_in_file);
242                     let line_begin_pos = (line_begin_in_file - start_bpos).to_usize();
243                     let col = CharPos(text[line_begin_pos..pos].chars().count());
244
245                     let lines = split_block_comment_into_lines(token_text, col);
246                     comments.push(Comment { style, lines, pos: pos_in_file })
247                 }
248             }
249             rustc_lexer::TokenKind::LineComment => {
250                 if !is_doc_comment(token_text) {
251                     comments.push(Comment {
252                         style: if code_to_the_left { Trailing } else { Isolated },
253                         lines: vec![token_text.to_string()],
254                         pos: start_bpos + BytePos(pos as u32),
255                     })
256                 }
257             }
258             _ => {
259                 code_to_the_left = true;
260             }
261         }
262         pos += token.len;
263     }
264
265     comments
266 }