1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Formatting and tools for comments.
13 use std::{self, iter};
15 use syntax::codemap::Span;
19 use rewrite::RewriteContext;
20 use string::{StringFormat, rewrite_string};
23 pub fn rewrite_comment(orig: &str,
31 // Edge case: block comments. Let's not trim their lines (for now).
32 let (opener, closer, line_start) = if block_style {
34 } else if !config.normalize_comments {
35 if orig.starts_with("/**") {
36 ("/** ", " **/", " ** ")
37 } else if orig.starts_with("/*!") {
38 ("/*! ", " */", " * ")
39 } else if orig.starts_with("/*") {
41 } else if orig.starts_with("///") {
43 } else if orig.starts_with("//!") {
48 } else if orig.starts_with("///") || orig.starts_with("/**") {
50 } else if orig.starts_with("//!") || orig.starts_with("/*!") {
56 let max_chars = width.checked_sub(closer.len() + opener.len()).unwrap_or(1);
58 let fmt = StringFormat {
61 line_start: line_start,
64 offset: offset + (opener.len() - line_start.len()),
69 let indent_str = offset.to_string(config);
70 let line_breaks = s.chars().filter(|&c| c == '\n').count();
74 .map(|(i, mut line)| {
77 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
78 line = &line[..(line.len() - 2)];
83 .map(left_trim_comment_line)
85 if orig.starts_with("/*") && line_breaks == 0 {
92 let mut result = opener.to_owned();
100 result.push_str(&indent_str);
101 result.push_str(line_start);
104 if config.wrap_comments && line.len() > max_chars {
105 let rewrite = rewrite_string(line, &fmt).unwrap_or(line.to_owned());
106 result.push_str(&rewrite);
109 // Remove space if this is an empty comment or a doc comment.
112 result.push_str(line);
116 result.push_str(closer);
117 if result == opener {
125 fn left_trim_comment_line(line: &str) -> &str {
126 if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") ||
127 line.starts_with("/** ") {
129 } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!") ||
130 line.starts_with("///") || line.starts_with("** ") || line.starts_with("/*!") ||
131 line.starts_with("/**") {
133 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") ||
134 line.starts_with("**") {
136 } else if line.starts_with("*") {
143 pub trait FindUncommented {
144 fn find_uncommented(&self, pat: &str) -> Option<usize>;
147 impl FindUncommented for str {
148 fn find_uncommented(&self, pat: &str) -> Option<usize> {
149 let mut needle_iter = pat.chars();
150 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
151 match needle_iter.next() {
153 return Some(i - pat.len());
157 FullCodeCharKind::Normal if b == c => {}
159 needle_iter = pat.chars();
166 // Handle case where the pattern is a suffix of the search string
167 match needle_iter.next() {
169 None => Some(self.len() - pat.len()),
174 // Returns the first byte position after the first comment. The given string
175 // is expected to be prefixed by a comment, including delimiters.
176 // Good: "/* /* inner */ outer */ code();"
177 // Bad: "code(); // hello\n world!"
178 pub fn find_comment_end(s: &str) -> Option<usize> {
179 let mut iter = CharClasses::new(s.char_indices());
180 for (kind, (i, _c)) in &mut iter {
181 if kind == FullCodeCharKind::Normal {
186 // Handle case where the comment ends at the end of s.
187 if iter.status == CharClassesStatus::Normal {
194 /// Returns true if text contains any comment.
195 pub fn contains_comment(text: &str) -> bool {
196 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
199 struct CharClasses<T>
203 base: iter::Peekable<T>,
204 status: CharClassesStatus,
208 fn get_char(&self) -> char;
211 impl RichChar for char {
212 fn get_char(&self) -> char {
217 impl RichChar for (usize, char) {
218 fn get_char(&self) -> char {
223 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
224 enum CharClassesStatus {
230 // The u32 is the nesting deepness of the comment
232 // Status when the '/' has been consumed, but not yet the '*', deepness is
233 // the new deepness (after the comment opening).
234 BlockCommentOpening(u32),
235 // Status when the '*' has been consumed, but not yet the '/', deepness is
236 // the new deepness (after the comment closing).
237 BlockCommentClosing(u32),
241 /// Distinguish between functionnal part of code and comments
242 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
243 pub enum CodeCharKind {
248 /// Distinguish between functionnal part of code and comments,
249 /// describing opening and closing of comments for ease when chunking
250 /// code from tagged characters
251 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
252 enum FullCodeCharKind {
254 /// The first character of a comment, there is only one for a comment (always '/')
256 /// Any character inside a comment including the second character of comment
257 /// marks ("//", "/*")
259 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
263 impl FullCodeCharKind {
264 fn is_comment(&self) -> bool {
266 FullCodeCharKind::Normal => false,
267 FullCodeCharKind::StartComment |
268 FullCodeCharKind::InComment |
269 FullCodeCharKind::EndComment => true,
273 fn to_codecharkind(&self) -> CodeCharKind {
274 if self.is_comment() {
275 CodeCharKind::Comment
282 impl<T> CharClasses<T>
286 fn new(base: T) -> CharClasses<T> {
288 base: base.peekable(),
289 status: CharClassesStatus::Normal,
294 impl<T> Iterator for CharClasses<T>
298 type Item = (FullCodeCharKind, T::Item);
300 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
301 let item = try_opt!(self.base.next());
302 let chr = item.get_char();
303 self.status = match self.status {
304 CharClassesStatus::LitString => {
306 '"' => CharClassesStatus::Normal,
307 '\\' => CharClassesStatus::LitStringEscape,
308 _ => CharClassesStatus::LitString,
311 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
312 CharClassesStatus::LitChar => {
314 '\\' => CharClassesStatus::LitCharEscape,
315 '\'' => CharClassesStatus::Normal,
316 _ => CharClassesStatus::LitChar,
319 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
320 CharClassesStatus::Normal => {
322 '"' => CharClassesStatus::LitString,
323 '\'' => CharClassesStatus::LitChar,
325 match self.base.peek() {
326 Some(next) if next.get_char() == '*' => {
327 self.status = CharClassesStatus::BlockCommentOpening(1);
328 return Some((FullCodeCharKind::StartComment, item));
330 Some(next) if next.get_char() == '/' => {
331 self.status = CharClassesStatus::LineComment;
332 return Some((FullCodeCharKind::StartComment, item));
334 _ => CharClassesStatus::Normal,
337 _ => CharClassesStatus::Normal,
340 CharClassesStatus::BlockComment(deepness) => {
341 assert!(deepness != 0);
342 self.status = match self.base.peek() {
343 Some(next) if next.get_char() == '/' && chr == '*' => {
344 CharClassesStatus::BlockCommentClosing(deepness - 1)
346 Some(next) if next.get_char() == '*' && chr == '/' => {
347 CharClassesStatus::BlockCommentOpening(deepness + 1)
349 _ => CharClassesStatus::BlockComment(deepness),
351 return Some((FullCodeCharKind::InComment, item));
353 CharClassesStatus::BlockCommentOpening(deepness) => {
354 assert_eq!(chr, '*');
355 self.status = CharClassesStatus::BlockComment(deepness);
356 return Some((FullCodeCharKind::InComment, item));
358 CharClassesStatus::BlockCommentClosing(deepness) => {
359 assert_eq!(chr, '/');
361 self.status = CharClassesStatus::Normal;
362 return Some((FullCodeCharKind::EndComment, item));
364 self.status = CharClassesStatus::BlockComment(deepness);
365 return Some((FullCodeCharKind::InComment, item));
368 CharClassesStatus::LineComment => {
371 self.status = CharClassesStatus::Normal;
372 return Some((FullCodeCharKind::EndComment, item));
375 self.status = CharClassesStatus::LineComment;
376 return Some((FullCodeCharKind::InComment, item));
381 Some((FullCodeCharKind::Normal, item))
385 /// Iterator over functional and commented parts of a string. Any part of a string is either
386 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
387 /// comments is functional code. Line comments contain their ending newlines.
388 struct UngroupedCommentCodeSlices<'a> {
390 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
393 impl<'a> UngroupedCommentCodeSlices<'a> {
394 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
395 UngroupedCommentCodeSlices {
397 iter: CharClasses::new(code.char_indices()).peekable(),
402 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
403 type Item = (CodeCharKind, usize, &'a str);
405 fn next(&mut self) -> Option<Self::Item> {
406 let (kind, (start_idx, _)) = try_opt!(self.iter.next());
408 FullCodeCharKind::Normal => {
409 // Consume all the Normal code
410 while let Some(&(FullCodeCharKind::Normal, (_, _))) = self.iter.peek() {
411 let _ = self.iter.next();
414 FullCodeCharKind::StartComment => {
415 // Consume the whole comment
416 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
420 let slice = match self.iter.peek() {
421 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
422 None => &self.slice[start_idx..],
424 Some((if kind.is_comment() {
425 CodeCharKind::Comment
437 /// Iterator over an alternating sequence of functional and commented parts of
438 /// a string. The first item is always a, possibly zero length, subslice of
439 /// functional text. Line style comments contain their ending newlines.
440 pub struct CommentCodeSlices<'a> {
442 last_slice_kind: CodeCharKind,
443 last_slice_end: usize,
446 impl<'a> CommentCodeSlices<'a> {
447 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
450 last_slice_kind: CodeCharKind::Comment,
456 impl<'a> Iterator for CommentCodeSlices<'a> {
457 type Item = (CodeCharKind, usize, &'a str);
459 fn next(&mut self) -> Option<Self::Item> {
460 if self.last_slice_end == self.slice.len() {
464 let mut sub_slice_end = self.last_slice_end;
465 let mut first_whitespace = None;
466 let subslice = &self.slice[self.last_slice_end..];
467 let mut iter = CharClasses::new(subslice.char_indices());
469 for (kind, (i, c)) in &mut iter {
470 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
471 &subslice[..2] == "//" &&
472 [' ', '\t'].contains(&c);
474 if is_comment_connector && first_whitespace.is_none() {
475 first_whitespace = Some(i);
478 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
479 let last_index = match first_whitespace {
483 sub_slice_end = self.last_slice_end + last_index;
487 if !is_comment_connector {
488 first_whitespace = None;
492 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
493 // This was the last subslice.
494 sub_slice_end = match first_whitespace {
495 Some(i) => self.last_slice_end + i,
496 None => self.slice.len(),
500 let kind = match self.last_slice_kind {
501 CodeCharKind::Comment => CodeCharKind::Normal,
502 CodeCharKind::Normal => CodeCharKind::Comment,
504 let res = (kind, self.last_slice_end, &self.slice[self.last_slice_end..sub_slice_end]);
505 self.last_slice_end = sub_slice_end;
506 self.last_slice_kind = kind;
512 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
513 /// (if it fits in the width/offset, else return None), else return `new`
514 pub fn recover_comment_removed(new: String,
516 context: &RewriteContext,
520 let snippet = context.snippet(span);
521 if changed_comment_content(&snippet, &new) {
522 // We missed some comments
523 // Keep previous formatting if it satisfies the constrains
524 return wrap_str(snippet, context.config.max_width, width, offset);
530 /// Return true if the two strings of code have the same payload of comments.
531 /// The payload of comments is everything in the string except:
532 /// - actual code (not comments)
533 /// - comment start/end marks
535 /// - '*' at the beginning of lines in block comments
536 fn changed_comment_content(orig: &str, new: &str) -> bool {
537 // Cannot write this as a fn since we cannot return types containing closures
538 let code_comment_content = |code| {
539 let slices = UngroupedCommentCodeSlices::new(code);
540 slices.filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
541 .flat_map(|(_, _, s)| CommentReducer::new(s))
543 let res = code_comment_content(orig).ne(code_comment_content(new));
544 debug!("comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
548 code_comment_content(orig).collect::<String>(),
549 code_comment_content(new).collect::<String>());
554 /// Iterator over the 'payload' characters of a comment.
555 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
556 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
558 struct CommentReducer<'a> {
561 iter: std::str::Chars<'a>,
564 impl<'a> CommentReducer<'a> {
565 fn new(comment: &'a str) -> CommentReducer<'a> {
566 let is_block = comment.starts_with("/*");
567 let comment = remove_comment_header(comment);
570 at_start_line: false, // There are no supplementary '*' on the first line
571 iter: comment.chars(),
576 impl<'a> Iterator for CommentReducer<'a> {
578 fn next(&mut self) -> Option<Self::Item> {
580 let mut c = try_opt!(self.iter.next());
581 if self.is_block && self.at_start_line {
582 while c.is_whitespace() {
583 c = try_opt!(self.iter.next());
585 // Ignore leading '*'
587 c = try_opt!(self.iter.next());
591 self.at_start_line = true;
594 if !c.is_whitespace() {
602 fn remove_comment_header(comment: &str) -> &str {
603 if comment.starts_with("///") || comment.starts_with("//!") {
605 } else if comment.starts_with("//") {
607 } else if comment.starts_with("/**") || comment.starts_with("/*!") {
608 &comment[3..comment.len() - 2]
610 assert!(comment.starts_with("/*"),
611 format!("string '{}' is not a comment", comment));
612 &comment[2..comment.len() - 2]
618 use super::{CharClasses, CodeCharKind, FullCodeCharKind, contains_comment, rewrite_comment,
619 FindUncommented, CommentCodeSlices};
624 let mut iter = CharClasses::new("//\n\n".chars());
626 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
627 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
628 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
629 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
630 assert_eq!(None, iter.next());
634 fn comment_code_slices() {
635 let input = "code(); /* test */ 1 + 1";
636 let mut iter = CommentCodeSlices::new(input);
638 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
639 assert_eq!((CodeCharKind::Comment, 8, "/* test */"),
640 iter.next().unwrap());
641 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
642 assert_eq!(None, iter.next());
646 fn comment_code_slices_two() {
647 let input = "// comment\n test();";
648 let mut iter = CommentCodeSlices::new(input);
650 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
651 assert_eq!((CodeCharKind::Comment, 0, "// comment\n"),
652 iter.next().unwrap());
653 assert_eq!((CodeCharKind::Normal, 11, " test();"),
654 iter.next().unwrap());
655 assert_eq!(None, iter.next());
659 fn comment_code_slices_three() {
660 let input = "1 // comment\n // comment2\n\n";
661 let mut iter = CommentCodeSlices::new(input);
663 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
664 assert_eq!((CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
665 iter.next().unwrap());
666 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
667 assert_eq!(None, iter.next());
671 #[cfg_attr(rustfmt, rustfmt_skip)]
672 fn format_comments() {
673 let mut config: ::config::Config = Default::default();
674 config.wrap_comments = true;
676 let comment = rewrite_comment(" //test", true, 100, Indent::new(0, 100), &config).unwrap();
677 assert_eq!("/* test */", comment);
679 let comment = rewrite_comment("// comment on a",
684 assert_eq!("// comment\n// on a", comment);
686 let comment = rewrite_comment("// A multi line comment\n // between args.",
691 assert_eq!("// A multi line comment\n // between args.", comment);
693 let input = "// comment";
696 let comment = rewrite_comment(input, true, 9, Indent::new(0, 69), &config).unwrap();
697 assert_eq!(expected, comment);
699 let comment = rewrite_comment("/* trimmed */",
704 assert_eq!("/* trimmed */", comment);
707 // This is probably intended to be a non-test fn, but it is not used. I'm
708 // keeping it around unless it helps us test stuff.
709 fn uncommented(text: &str) -> String {
710 CharClasses::new(text.chars())
711 .filter_map(|(s, c)| {
713 FullCodeCharKind::Normal => Some(c),
721 fn test_uncommented() {
722 assert_eq!(&uncommented("abc/*...*/"), "abc");
723 assert_eq!(&uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
725 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
729 fn test_contains_comment() {
730 assert_eq!(contains_comment("abc"), false);
731 assert_eq!(contains_comment("abc // qsdf"), true);
732 assert_eq!(contains_comment("abc /* kqsdf"), true);
733 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
737 fn test_find_uncommented() {
738 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
739 assert_eq!(expected, haystack.find_uncommented(needle));
742 check("/*/ */test", "test", Some(6));
743 check("//test\ntest", "test", Some(7));
744 check("/* comment only */", "whatever", None);
745 check("/* comment */ some text /* more commentary */ result",
748 check("sup // sup", "p", Some(2));
749 check("sup", "x", None);
750 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
751 check("/*sup yo? \n sup*/ sup", "p", Some(20));
752 check("hel/*lohello*/lo", "hello", None);
753 check("acb", "ab", None);
754 check(",/*A*/ ", ",", Some(0));
755 check("abc", "abc", Some(0));
756 check("/* abc */", "abc", None);
757 check("/**/abc/* */", "abc", Some(4));
758 check("\"/* abc */\"", "abc", Some(4));
759 check("\"/* abc", "abc", Some(4));