1 pub use CommentStyle::*;
4 use crate::sess::ParseSess;
6 use rustc_span::source_map::SourceMap;
7 use rustc_span::{BytePos, CharPos, FileName, Pos};
16 #[derive(Clone, Copy, PartialEq, Debug)]
17 pub enum CommentStyle {
18 /// No code on either side of each line of the comment
20 /// Code exists to the left of the comment
22 /// Code before /* foo */ and after the comment
24 /// Just a manual blank line "\n\n", for layout
30 pub style: CommentStyle,
31 pub lines: Vec<String>,
35 pub fn is_line_doc_comment(s: &str) -> bool {
36 let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/')
37 || s.starts_with("//!");
38 debug!("is {:?} a doc comment? {}", s, res);
42 pub fn is_block_doc_comment(s: &str) -> bool {
43 // Prevent `/**/` from being parsed as a doc comment
44 let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*')
45 || s.starts_with("/*!"))
47 debug!("is {:?} a doc comment? {}", s, res);
51 // FIXME(#64197): Try to privatize this again.
52 pub fn is_doc_comment(s: &str) -> bool {
53 (s.starts_with("///") && is_line_doc_comment(s))
54 || s.starts_with("//!")
55 || (s.starts_with("/**") && is_block_doc_comment(s))
56 || s.starts_with("/*!")
59 pub fn doc_comment_style(comment: &str) -> ast::AttrStyle {
60 assert!(is_doc_comment(comment));
61 if comment.starts_with("//!") || comment.starts_with("/*!") {
68 pub fn strip_doc_comment_decoration(comment: &str) -> String {
69 /// remove whitespace-only lines from the start/end of lines
70 fn vertical_trim(lines: Vec<String>) -> Vec<String> {
72 let mut j = lines.len();
73 // first line of all-stars should be omitted
74 if !lines.is_empty() && lines[0].chars().all(|c| c == '*') {
78 while i < j && lines[i].trim().is_empty() {
81 // like the first, a last line of all stars should be omitted
82 if j > i && lines[j - 1].chars().skip(1).all(|c| c == '*') {
86 while j > i && lines[j - 1].trim().is_empty() {
93 /// remove a "[ \t]*\*" block from each line, if possible
94 fn horizontal_trim(lines: Vec<String>) -> Vec<String> {
95 let mut i = usize::MAX;
96 let mut can_trim = true;
100 for (j, c) in line.chars().enumerate() {
101 if j > i || !"* \t".contains(c) {
124 lines.iter().map(|line| (&line[i + 1..line.len()]).to_string()).collect()
130 // one-line comments lose their prefix
131 const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
133 for prefix in ONELINERS {
134 if comment.starts_with(*prefix) {
135 return (&comment[prefix.len()..]).to_string();
139 if comment.starts_with("/*") {
141 comment[3..comment.len() - 2].lines().map(|s| s.to_string()).collect::<Vec<String>>();
143 let lines = vertical_trim(lines);
144 let lines = horizontal_trim(lines);
146 return lines.join("\n");
149 panic!("not a doc-comment: {}", comment);
152 /// Returns `None` if the first `col` chars of `s` contain a non-whitespace char.
153 /// Otherwise returns `Some(k)` where `k` is first char offset after that leading
154 /// whitespace. Note that `k` may be outside bounds of `s`.
155 fn all_whitespace(s: &str, col: CharPos) -> Option<usize> {
157 for (i, ch) in s.char_indices().take(col.to_usize()) {
158 if !ch.is_whitespace() {
161 idx = i + ch.len_utf8();
166 fn trim_whitespace_prefix(s: &str, col: CharPos) -> &str {
168 match all_whitespace(&s, col) {
180 fn split_block_comment_into_lines(text: &str, col: CharPos) -> Vec<String> {
181 let mut res: Vec<String> = vec![];
182 let mut lines = text.lines();
183 // just push the first line
184 res.extend(lines.next().map(|it| it.to_string()));
185 // for other lines, strip common whitespace prefix
187 res.push(trim_whitespace_prefix(line, col).to_string())
192 // it appears this function is called only from pprust... that's
193 // probably not a good thing.
194 crate fn gather_comments(sess: &ParseSess, path: FileName, src: String) -> Vec<Comment> {
195 let cm = SourceMap::new(sess.source_map().path_mapping().clone());
196 let source_file = cm.new_source_file(path, src);
197 let text = (*source_file.src.as_ref().unwrap()).clone();
199 let text: &str = text.as_str();
200 let start_bpos = source_file.start_pos;
202 let mut comments: Vec<Comment> = Vec::new();
203 let mut code_to_the_left = false;
205 if let Some(shebang_len) = rustc_lexer::strip_shebang(text) {
206 comments.push(Comment {
208 lines: vec![text[..shebang_len].to_string()],
214 for token in rustc_lexer::tokenize(&text[pos..]) {
215 let token_text = &text[pos..pos + token.len];
217 rustc_lexer::TokenKind::Whitespace => {
218 if let Some(mut idx) = token_text.find('\n') {
219 code_to_the_left = false;
220 while let Some(next_newline) = &token_text[idx + 1..].find('\n') {
221 idx = idx + 1 + next_newline;
222 comments.push(Comment {
225 pos: start_bpos + BytePos((pos + idx) as u32),
230 rustc_lexer::TokenKind::BlockComment { terminated: _ } => {
231 if !is_block_doc_comment(token_text) {
232 let code_to_the_right = match text[pos + token.len..].chars().next() {
233 Some('\r') | Some('\n') => false,
236 let style = match (code_to_the_left, code_to_the_right) {
237 (true, true) | (false, true) => Mixed,
238 (false, false) => Isolated,
239 (true, false) => Trailing,
242 // Count the number of chars since the start of the line by rescanning.
243 let pos_in_file = start_bpos + BytePos(pos as u32);
244 let line_begin_in_file = source_file.line_begin_pos(pos_in_file);
245 let line_begin_pos = (line_begin_in_file - start_bpos).to_usize();
246 let col = CharPos(text[line_begin_pos..pos].chars().count());
248 let lines = split_block_comment_into_lines(token_text, col);
249 comments.push(Comment { style, lines, pos: pos_in_file })
252 rustc_lexer::TokenKind::LineComment => {
253 if !is_doc_comment(token_text) {
254 comments.push(Comment {
255 style: if code_to_the_left { Trailing } else { Isolated },
256 lines: vec![token_text.to_string()],
257 pos: start_bpos + BytePos(pos as u32),
262 code_to_the_left = true;