]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_ast/src/util/comments.rs
New upstream version 1.69.0+dfsg1
[rustc.git] / compiler / rustc_ast / src / util / comments.rs
CommitLineData
5099ac24 1use crate::token::CommentKind;
dfeec247 2use rustc_span::source_map::SourceMap;
3dfed10e 3use rustc_span::{BytePos, CharPos, FileName, Pos, Symbol};
60c5eb7d 4
416331ca
XL
5#[cfg(test)]
6mod tests;
7
c30ab7b3 8#[derive(Clone, Copy, PartialEq, Debug)]
1a4d82fc
JJ
9pub 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)]
21pub struct Comment {
22 pub style: CommentStyle,
23 pub lines: Vec<String>,
24 pub pos: BytePos,
25}
26
04454e1e
FG
27/// A fast conservative estimate on whether the string can contain documentation links.
28/// A pair of square brackets `[]` must exist in the string, but we only search for the
29/// opening bracket because brackets always go in pairs in practice.
30#[inline]
31pub fn may_have_doc_links(s: &str) -> bool {
32 s.contains('[')
33}
34
3dfed10e
XL
35/// Makes a doc string more presentable to users.
36/// Used by rustdoc and perhaps other tools, but not by rustc.
5099ac24 37pub fn beautify_doc_string(data: Symbol, kind: CommentKind) -> Symbol {
fc512014 38 fn get_vertical_trim(lines: &[&str]) -> Option<(usize, usize)> {
85aaf69f 39 let mut i = 0;
1a4d82fc
JJ
40 let mut j = lines.len();
41 // first line of all-stars should be omitted
9cc50fc6 42 if !lines.is_empty() && lines[0].chars().all(|c| c == '*') {
1a4d82fc
JJ
43 i += 1;
44 }
b7449926 45
1a4d82fc 46 // like the first, a last line of all stars should be omitted
3c0e092e 47 if j > i && !lines[j - 1].is_empty() && lines[j - 1].chars().all(|c| c == '*') {
1a4d82fc
JJ
48 j -= 1;
49 }
b7449926 50
fc512014 51 if i != 0 || j != lines.len() { Some((i, j)) } else { None }
1a4d82fc
JJ
52 }
53
9c376795 54 fn get_horizontal_trim(lines: &[&str], kind: CommentKind) -> Option<String> {
85aaf69f 55 let mut i = usize::MAX;
1a4d82fc 56 let mut first = true;
b7449926 57
5099ac24
FG
58 // In case we have doc comments like `/**` or `/*!`, we want to remove stars if they are
59 // present. However, we first need to strip the empty lines so they don't get in the middle
60 // when we try to compute the "horizontal trim".
9ffffee4
FG
61 let lines = match kind {
62 CommentKind::Block => {
63 // Whatever happens, we skip the first line.
64 let mut i = lines
65 .get(0)
66 .map(|l| if l.trim_start().starts_with('*') { 0 } else { 1 })
67 .unwrap_or(0);
68 let mut j = lines.len();
5099ac24 69
9ffffee4
FG
70 while i < j && lines[i].trim().is_empty() {
71 i += 1;
72 }
73 while j > i && lines[j - 1].trim().is_empty() {
74 j -= 1;
75 }
76 &lines[i..j]
5099ac24 77 }
9ffffee4 78 CommentKind::Line => lines,
5099ac24
FG
79 };
80
fc512014 81 for line in lines {
1a4d82fc 82 for (j, c) in line.chars().enumerate() {
c34b1796 83 if j > i || !"* \t".contains(c) {
fc512014 84 return None;
1a4d82fc
JJ
85 }
86 if c == '*' {
87 if first {
88 i = j;
89 first = false;
90 } else if i != j {
fc512014 91 return None;
1a4d82fc
JJ
92 }
93 break;
94 }
95 }
2c00a5a8 96 if i >= line.len() {
fc512014 97 return None;
1a4d82fc
JJ
98 }
99 }
5099ac24 100 if lines.is_empty() { None } else { Some(lines[0][..i].into()) }
fc512014 101 }
1a4d82fc 102
fc512014
XL
103 let data_s = data.as_str();
104 if data_s.contains('\n') {
105 let mut lines = data_s.lines().collect::<Vec<&str>>();
106 let mut changes = false;
107 let lines = if let Some((i, j)) = get_vertical_trim(&lines) {
108 changes = true;
109 // remove whitespace-only lines from the start/end of lines
110 &mut lines[i..j]
1a4d82fc 111 } else {
fc512014
XL
112 &mut lines
113 };
487cf647 114 if let Some(horizontal) = get_horizontal_trim(lines, kind) {
fc512014
XL
115 changes = true;
116 // remove a "[ \t]*\*" block from each line, if possible
117 for line in lines.iter_mut() {
5099ac24
FG
118 if let Some(tmp) = line.strip_prefix(&horizontal) {
119 *line = tmp;
120 if kind == CommentKind::Block
121 && (*line == "*" || line.starts_with("* ") || line.starts_with("**"))
122 {
123 *line = &line[1..];
124 }
125 }
fc512014
XL
126 }
127 }
128 if changes {
129 return Symbol::intern(&lines.join("\n"));
1a4d82fc
JJ
130 }
131 }
fc512014 132 data
1a4d82fc
JJ
133}
134
9fa01778
XL
135/// Returns `None` if the first `col` chars of `s` contain a non-whitespace char.
136/// Otherwise returns `Some(k)` where `k` is first char offset after that leading
137/// whitespace. Note that `k` may be outside bounds of `s`.
85aaf69f 138fn all_whitespace(s: &str, col: CharPos) -> Option<usize> {
0731742a
XL
139 let mut idx = 0;
140 for (i, ch) in s.char_indices().take(col.to_usize()) {
c34b1796 141 if !ch.is_whitespace() {
1a4d82fc
JJ
142 return None;
143 }
0731742a 144 idx = i + ch.len_utf8();
1a4d82fc 145 }
0731742a 146 Some(idx)
1a4d82fc
JJ
147}
148
416331ca 149fn trim_whitespace_prefix(s: &str, col: CharPos) -> &str {
1a4d82fc 150 let len = s.len();
487cf647 151 match all_whitespace(s, col) {
dfeec247
XL
152 Some(col) => {
153 if col < len {
154 &s[col..]
155 } else {
156 ""
157 }
158 }
1a4d82fc 159 None => s,
1a4d82fc 160 }
1a4d82fc
JJ
161}
162
dfeec247 163fn split_block_comment_into_lines(text: &str, col: CharPos) -> Vec<String> {
416331ca
XL
164 let mut res: Vec<String> = vec![];
165 let mut lines = text.lines();
166 // just push the first line
167 res.extend(lines.next().map(|it| it.to_string()));
168 // for other lines, strip common whitespace prefix
169 for line in lines {
170 res.push(trim_whitespace_prefix(line, col).to_string())
171 }
172 res
1a4d82fc
JJ
173}
174
1a4d82fc
JJ
175// it appears this function is called only from pprust... that's
176// probably not a good thing.
74b04a01
XL
177pub fn gather_comments(sm: &SourceMap, path: FileName, src: String) -> Vec<Comment> {
178 let sm = SourceMap::new(sm.path_mapping().clone());
179 let source_file = sm.new_source_file(path, src);
416331ca 180 let text = (*source_file.src.as_ref().unwrap()).clone();
1a4d82fc 181
416331ca
XL
182 let text: &str = text.as_str();
183 let start_bpos = source_file.start_pos;
184 let mut pos = 0;
1a4d82fc 185 let mut comments: Vec<Comment> = Vec::new();
416331ca 186 let mut code_to_the_left = false;
b7449926 187
416331ca
XL
188 if let Some(shebang_len) = rustc_lexer::strip_shebang(text) {
189 comments.push(Comment {
3dfed10e 190 style: CommentStyle::Isolated,
416331ca
XL
191 lines: vec![text[..shebang_len].to_string()],
192 pos: start_bpos,
193 });
194 pos += shebang_len;
195 }
196
197 for token in rustc_lexer::tokenize(&text[pos..]) {
064997fb 198 let token_text = &text[pos..pos + token.len as usize];
416331ca
XL
199 match token.kind {
200 rustc_lexer::TokenKind::Whitespace => {
201 if let Some(mut idx) = token_text.find('\n') {
202 code_to_the_left = false;
203 while let Some(next_newline) = &token_text[idx + 1..].find('\n') {
3c0e092e 204 idx += 1 + next_newline;
416331ca 205 comments.push(Comment {
3dfed10e 206 style: CommentStyle::BlankLine,
416331ca
XL
207 lines: vec![],
208 pos: start_bpos + BytePos((pos + idx) as u32),
209 });
210 }
211 }
212 }
3dfed10e
XL
213 rustc_lexer::TokenKind::BlockComment { doc_style, .. } => {
214 if doc_style.is_none() {
064997fb
FG
215 let code_to_the_right = !matches!(
216 text[pos + token.len as usize..].chars().next(),
217 Some('\r' | '\n')
218 );
416331ca 219 let style = match (code_to_the_left, code_to_the_right) {
3dfed10e
XL
220 (_, true) => CommentStyle::Mixed,
221 (false, false) => CommentStyle::Isolated,
222 (true, false) => CommentStyle::Trailing,
416331ca
XL
223 };
224
225 // Count the number of chars since the start of the line by rescanning.
226 let pos_in_file = start_bpos + BytePos(pos as u32);
227 let line_begin_in_file = source_file.line_begin_pos(pos_in_file);
228 let line_begin_pos = (line_begin_in_file - start_bpos).to_usize();
229 let col = CharPos(text[line_begin_pos..pos].chars().count());
230
231 let lines = split_block_comment_into_lines(token_text, col);
232 comments.push(Comment { style, lines, pos: pos_in_file })
c30ab7b3 233 }
1a4d82fc 234 }
3dfed10e
XL
235 rustc_lexer::TokenKind::LineComment { doc_style } => {
236 if doc_style.is_none() {
416331ca 237 comments.push(Comment {
3dfed10e
XL
238 style: if code_to_the_left {
239 CommentStyle::Trailing
240 } else {
241 CommentStyle::Isolated
242 },
416331ca
XL
243 lines: vec![token_text.to_string()],
244 pos: start_bpos + BytePos(pos as u32),
245 })
246 }
247 }
248 _ => {
249 code_to_the_left = true;
1a4d82fc 250 }
1a4d82fc 251 }
064997fb 252 pos += token.len as usize;
1a4d82fc
JJ
253 }
254
48663c56 255 comments
1a4d82fc 256}