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<'a>(lines: &'a [&str], kind: CommentKind) -> Option<String> {
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 {
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();
58 while i < j && lines[i].trim().is_empty() {
61 while j > i && lines[j - 1].trim().is_empty() {
70 for (j, c) in line.chars().enumerate() {
71 if j > i || !"* \t".contains(c) {
88 if lines.is_empty() { None } else { Some(lines[0][..i].into()) }
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) {
97 // remove whitespace-only lines from the start/end of lines
102 if let Some(horizontal) = get_horizontal_trim(&lines, kind) {
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) {
108 if kind == CommentKind::Block
109 && (*line == "*" || line.starts_with("* ") || line.starts_with("**"))
117 return Symbol::intern(&lines.join("\n"));
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> {
128 for (i, ch) in s.char_indices().take(col.to_usize()) {
129 if !ch.is_whitespace() {
132 idx = i + ch.len_utf8();
137 fn trim_whitespace_prefix(s: &str, col: CharPos) -> &str {
139 match all_whitespace(&s, col) {
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
158 res.push(trim_whitespace_prefix(line, col).to_string())
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();
170 let text: &str = text.as_str();
171 let start_bpos = source_file.start_pos;
173 let mut comments: Vec<Comment> = Vec::new();
174 let mut code_to_the_left = false;
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()],
185 for token in rustc_lexer::tokenize(&text[pos..]) {
186 let token_text = &text[pos..pos + token.len];
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,
196 pos: start_bpos + BytePos((pos + idx) as u32),
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,
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());
217 let lines = split_block_comment_into_lines(token_text, col);
218 comments.push(Comment { style, lines, pos: pos_in_file })
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
227 CommentStyle::Isolated
229 lines: vec![token_text.to_string()],
230 pos: start_bpos + BytePos(pos as u32),
235 code_to_the_left = true;