1 use rustc_span::source_map::SourceMap;
2 use rustc_span::{BytePos, CharPos, FileName, Pos, Symbol};
7 #[derive(Clone, Copy, PartialEq, Debug)]
8 pub enum CommentStyle {
9 /// No code on either side of each line of the comment
11 /// Code exists to the left of the comment
13 /// Code before /* foo */ and after the comment
15 /// Just a manual blank line "\n\n", for layout
21 pub style: CommentStyle,
22 pub lines: Vec<String>,
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> {
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 while i < j && lines[i].trim().is_empty() {
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 == '*') {
46 while j > i && lines[j - 1].trim().is_empty() {
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;
60 for (j, c) in line.chars().enumerate() {
61 if j > i || !"* \t".contains(c) {
84 lines.iter().map(|line| (&line[i + 1..line.len()]).to_string()).collect()
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);
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> {
106 for (i, ch) in s.char_indices().take(col.to_usize()) {
107 if !ch.is_whitespace() {
110 idx = i + ch.len_utf8();
115 fn trim_whitespace_prefix(s: &str, col: CharPos) -> &str {
117 match all_whitespace(&s, col) {
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
136 res.push(trim_whitespace_prefix(line, col).to_string())
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();
148 let text: &str = text.as_str();
149 let start_bpos = source_file.start_pos;
151 let mut comments: Vec<Comment> = Vec::new();
152 let mut code_to_the_left = false;
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()],
163 for token in rustc_lexer::tokenize(&text[pos..]) {
164 let token_text = &text[pos..pos + token.len];
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,
174 pos: start_bpos + BytePos((pos + idx) as u32),
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,
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,
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());
197 let lines = split_block_comment_into_lines(token_text, col);
198 comments.push(Comment { style, lines, pos: pos_in_file })
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
207 CommentStyle::Isolated
209 lines: vec![token_text.to_string()],
210 pos: start_bpos + BytePos(pos as u32),
215 code_to_the_left = true;