1 pub use CommentStyle::*;
4 use rustc_span::source_map::SourceMap;
5 use rustc_span::{BytePos, CharPos, FileName, Pos};
13 #[derive(Clone, Copy, PartialEq, Debug)]
14 pub enum CommentStyle {
15 /// No code on either side of each line of the comment
17 /// Code exists to the left of the comment
19 /// Code before /* foo */ and after the comment
21 /// Just a manual blank line "\n\n", for layout
27 pub style: CommentStyle,
28 pub lines: Vec<String>,
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);
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("/*!"))
44 debug!("is {:?} a doc comment? {}", s, res);
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("/*!")
56 pub fn doc_comment_style(comment: &str) -> ast::AttrStyle {
57 assert!(is_doc_comment(comment));
58 if comment.starts_with("//!") || comment.starts_with("/*!") {
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> {
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 == '*') {
75 while i < j && lines[i].trim().is_empty() {
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 == '*') {
83 while j > i && lines[j - 1].trim().is_empty() {
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;
97 for (j, c) in line.chars().enumerate() {
98 if j > i || !"* \t".contains(c) {
121 lines.iter().map(|line| (&line[i + 1..line.len()]).to_string()).collect()
127 // one-line comments lose their prefix
128 const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
130 for prefix in ONELINERS {
131 if comment.starts_with(*prefix) {
132 return (&comment[prefix.len()..]).to_string();
136 if comment.starts_with("/*") {
138 comment[3..comment.len() - 2].lines().map(|s| s.to_string()).collect::<Vec<String>>();
140 let lines = vertical_trim(lines);
141 let lines = horizontal_trim(lines);
143 return lines.join("\n");
146 panic!("not a doc-comment: {}", comment);
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> {
154 for (i, ch) in s.char_indices().take(col.to_usize()) {
155 if !ch.is_whitespace() {
158 idx = i + ch.len_utf8();
163 fn trim_whitespace_prefix(s: &str, col: CharPos) -> &str {
165 match all_whitespace(&s, col) {
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
184 res.push(trim_whitespace_prefix(line, col).to_string())
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();
196 let text: &str = text.as_str();
197 let start_bpos = source_file.start_pos;
199 let mut comments: Vec<Comment> = Vec::new();
200 let mut code_to_the_left = false;
202 if let Some(shebang_len) = rustc_lexer::strip_shebang(text) {
203 comments.push(Comment {
205 lines: vec![text[..shebang_len].to_string()],
211 for token in rustc_lexer::tokenize(&text[pos..]) {
212 let token_text = &text[pos..pos + token.len];
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 {
222 pos: start_bpos + BytePos((pos + idx) as u32),
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,
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,
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());
245 let lines = split_block_comment_into_lines(token_text, col);
246 comments.push(Comment { style, lines, pos: pos_in_file })
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),
259 code_to_the_left = true;