1 use crate::token::CommentKind;
2 use rustc_span::source_map::SourceMap;
3 use rustc_span::{BytePos, CharPos, FileName, Pos, Symbol};
8 #[derive(Clone, Copy, PartialEq, Debug)]
9 pub enum CommentStyle {
10 /// No code on either side of each line of the comment
12 /// Code exists to the left of the comment
14 /// Code before /* foo */ and after the comment
16 /// Just a manual blank line "\n\n", for layout
22 pub style: CommentStyle,
23 pub lines: Vec<String>,
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)> {
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 == '*') {
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 == '*') {
43 if i != 0 || j != lines.len() { Some((i, j)) } else { None }
46 fn get_horizontal_trim(lines: &[&str], kind: CommentKind) -> Option<usize> {
47 let mut i = usize::MAX;
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 {
55 let mut j = lines.len();
57 while i < j && lines[i].trim().is_empty() {
60 while j > i && lines[j - 1].trim().is_empty() {
69 for (j, c) in line.chars().enumerate() {
70 if j > i || !"* \t".contains(c) {
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) {
96 // remove whitespace-only lines from the start/end of lines
101 if let Some(horizontal) = get_horizontal_trim(&lines, kind) {
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..];
111 return Symbol::intern(&lines.join("\n"));
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> {
122 for (i, ch) in s.char_indices().take(col.to_usize()) {
123 if !ch.is_whitespace() {
126 idx = i + ch.len_utf8();
131 fn trim_whitespace_prefix(s: &str, col: CharPos) -> &str {
133 match all_whitespace(&s, col) {
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
152 res.push(trim_whitespace_prefix(line, col).to_string())
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();
164 let text: &str = text.as_str();
165 let start_bpos = source_file.start_pos;
167 let mut comments: Vec<Comment> = Vec::new();
168 let mut code_to_the_left = false;
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()],
179 for token in rustc_lexer::tokenize(&text[pos..]) {
180 let token_text = &text[pos..pos + token.len];
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,
190 pos: start_bpos + BytePos((pos + idx) as u32),
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,
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());
211 let lines = split_block_comment_into_lines(token_text, col);
212 comments.push(Comment { style, lines, pos: pos_in_file })
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
221 CommentStyle::Isolated
223 lines: vec![token_text.to_string()],
224 pos: start_bpos + BytePos(pos as u32),
229 code_to_the_left = true;