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) =
35 } else if !config.normalize_comments {
36 if orig.starts_with("/**") && !orig.starts_with("/**/") {
37 ("/** ", " **/", " ** ")
38 } else if orig.starts_with("/*!") {
39 ("/*! ", " */", " * ")
40 } else if orig.starts_with("/*") {
42 } else if orig.starts_with("///") {
44 } else if orig.starts_with("//!") {
49 } else if orig.starts_with("///") ||
50 (orig.starts_with("/**") && !orig.starts_with("/**/")) {
52 } else if orig.starts_with("//!") || orig.starts_with("/*!") {
58 let max_chars = width.checked_sub(closer.len() + opener.len()).unwrap_or(1);
60 let fmt = StringFormat {
63 line_start: line_start,
66 offset: offset + (opener.len() - line_start.len()),
71 let indent_str = offset.to_string(config);
72 let line_breaks = s.chars().filter(|&c| c == '\n').count();
74 let num_bare_lines = s.lines()
76 .map(|(_, line)| line.trim())
77 .filter(|l| !(l.starts_with('*') || l.starts_with("//") || l.starts_with("/*")))
80 if num_bare_lines > 0 && !config.normalize_comments {
81 return Some(orig.to_owned());
86 .map(|(i, mut line)| {
89 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
90 line = &line[..(line.len() - 2)];
95 .map(left_trim_comment_line)
97 if orig.starts_with("/*") && line_breaks == 0 {
104 let mut result = opener.to_owned();
106 if result == opener {
112 result.push_str(&indent_str);
113 result.push_str(line_start);
116 if config.wrap_comments && line.len() > max_chars {
117 let rewrite = rewrite_string(line, &fmt).unwrap_or(line.to_owned());
118 result.push_str(&rewrite);
121 // Remove space if this is an empty comment or a doc comment.
124 result.push_str(line);
128 result.push_str(closer);
129 if result == opener {
137 fn left_trim_comment_line(line: &str) -> &str {
138 if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") ||
139 line.starts_with("/** ") {
141 } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!") ||
142 line.starts_with("///") ||
143 line.starts_with("** ") || line.starts_with("/*!") ||
144 (line.starts_with("/**") && !line.starts_with("/**/")) {
146 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") ||
147 line.starts_with("**") {
149 } else if line.starts_with('*') {
156 pub trait FindUncommented {
157 fn find_uncommented(&self, pat: &str) -> Option<usize>;
160 impl FindUncommented for str {
161 fn find_uncommented(&self, pat: &str) -> Option<usize> {
162 let mut needle_iter = pat.chars();
163 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
164 match needle_iter.next() {
166 return Some(i - pat.len());
170 FullCodeCharKind::Normal if b == c => {}
172 needle_iter = pat.chars();
179 // Handle case where the pattern is a suffix of the search string
180 match needle_iter.next() {
182 None => Some(self.len() - pat.len()),
187 // Returns the first byte position after the first comment. The given string
188 // is expected to be prefixed by a comment, including delimiters.
189 // Good: "/* /* inner */ outer */ code();"
190 // Bad: "code(); // hello\n world!"
191 pub fn find_comment_end(s: &str) -> Option<usize> {
192 let mut iter = CharClasses::new(s.char_indices());
193 for (kind, (i, _c)) in &mut iter {
194 if kind == FullCodeCharKind::Normal {
199 // Handle case where the comment ends at the end of s.
200 if iter.status == CharClassesStatus::Normal {
207 /// Returns true if text contains any comment.
208 pub fn contains_comment(text: &str) -> bool {
209 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
212 struct CharClasses<T>
216 base: iter::Peekable<T>,
217 status: CharClassesStatus,
221 fn get_char(&self) -> char;
224 impl RichChar for char {
225 fn get_char(&self) -> char {
230 impl RichChar for (usize, char) {
231 fn get_char(&self) -> char {
236 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
237 enum CharClassesStatus {
243 // The u32 is the nesting deepness of the comment
245 // Status when the '/' has been consumed, but not yet the '*', deepness is
246 // the new deepness (after the comment opening).
247 BlockCommentOpening(u32),
248 // Status when the '*' has been consumed, but not yet the '/', deepness is
249 // the new deepness (after the comment closing).
250 BlockCommentClosing(u32),
254 /// Distinguish between functionnal part of code and comments
255 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
256 pub enum CodeCharKind {
261 /// Distinguish between functionnal part of code and comments,
262 /// describing opening and closing of comments for ease when chunking
263 /// code from tagged characters
264 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
265 enum FullCodeCharKind {
267 /// The first character of a comment, there is only one for a comment (always '/')
269 /// Any character inside a comment including the second character of comment
270 /// marks ("//", "/*")
272 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
276 impl FullCodeCharKind {
277 fn is_comment(&self) -> bool {
279 FullCodeCharKind::Normal => false,
280 FullCodeCharKind::StartComment |
281 FullCodeCharKind::InComment |
282 FullCodeCharKind::EndComment => true,
286 fn to_codecharkind(&self) -> CodeCharKind {
287 if self.is_comment() {
288 CodeCharKind::Comment
295 impl<T> CharClasses<T>
299 fn new(base: T) -> CharClasses<T> {
301 base: base.peekable(),
302 status: CharClassesStatus::Normal,
307 impl<T> Iterator for CharClasses<T>
311 type Item = (FullCodeCharKind, T::Item);
313 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
314 let item = try_opt!(self.base.next());
315 let chr = item.get_char();
316 self.status = match self.status {
317 CharClassesStatus::LitString => {
319 '"' => CharClassesStatus::Normal,
320 '\\' => CharClassesStatus::LitStringEscape,
321 _ => CharClassesStatus::LitString,
324 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
325 CharClassesStatus::LitChar => {
327 '\\' => CharClassesStatus::LitCharEscape,
328 '\'' => CharClassesStatus::Normal,
329 _ => CharClassesStatus::LitChar,
332 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
333 CharClassesStatus::Normal => {
335 '"' => CharClassesStatus::LitString,
336 '\'' => CharClassesStatus::LitChar,
338 match self.base.peek() {
339 Some(next) if next.get_char() == '*' => {
340 self.status = CharClassesStatus::BlockCommentOpening(1);
341 return Some((FullCodeCharKind::StartComment, item));
343 Some(next) if next.get_char() == '/' => {
344 self.status = CharClassesStatus::LineComment;
345 return Some((FullCodeCharKind::StartComment, item));
347 _ => CharClassesStatus::Normal,
350 _ => CharClassesStatus::Normal,
353 CharClassesStatus::BlockComment(deepness) => {
354 assert!(deepness != 0);
355 self.status = match self.base.peek() {
356 Some(next) if next.get_char() == '/' && chr == '*' => {
357 CharClassesStatus::BlockCommentClosing(deepness - 1)
359 Some(next) if next.get_char() == '*' && chr == '/' => {
360 CharClassesStatus::BlockCommentOpening(deepness + 1)
362 _ => CharClassesStatus::BlockComment(deepness),
364 return Some((FullCodeCharKind::InComment, item));
366 CharClassesStatus::BlockCommentOpening(deepness) => {
367 assert_eq!(chr, '*');
368 self.status = CharClassesStatus::BlockComment(deepness);
369 return Some((FullCodeCharKind::InComment, item));
371 CharClassesStatus::BlockCommentClosing(deepness) => {
372 assert_eq!(chr, '/');
374 self.status = CharClassesStatus::Normal;
375 return Some((FullCodeCharKind::EndComment, item));
377 self.status = CharClassesStatus::BlockComment(deepness);
378 return Some((FullCodeCharKind::InComment, item));
381 CharClassesStatus::LineComment => {
384 self.status = CharClassesStatus::Normal;
385 return Some((FullCodeCharKind::EndComment, item));
388 self.status = CharClassesStatus::LineComment;
389 return Some((FullCodeCharKind::InComment, item));
394 Some((FullCodeCharKind::Normal, item))
398 /// Iterator over functional and commented parts of a string. Any part of a string is either
399 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
400 /// comments is functional code. Line comments contain their ending newlines.
401 struct UngroupedCommentCodeSlices<'a> {
403 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
406 impl<'a> UngroupedCommentCodeSlices<'a> {
407 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
408 UngroupedCommentCodeSlices {
410 iter: CharClasses::new(code.char_indices()).peekable(),
415 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
416 type Item = (CodeCharKind, usize, &'a str);
418 fn next(&mut self) -> Option<Self::Item> {
419 let (kind, (start_idx, _)) = try_opt!(self.iter.next());
421 FullCodeCharKind::Normal => {
422 // Consume all the Normal code
423 while let Some(&(FullCodeCharKind::Normal, (_, _))) = self.iter.peek() {
424 let _ = self.iter.next();
427 FullCodeCharKind::StartComment => {
428 // Consume the whole comment
429 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
433 let slice = match self.iter.peek() {
434 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
435 None => &self.slice[start_idx..],
437 Some((if kind.is_comment() {
438 CodeCharKind::Comment
450 /// Iterator over an alternating sequence of functional and commented parts of
451 /// a string. The first item is always a, possibly zero length, subslice of
452 /// functional text. Line style comments contain their ending newlines.
453 pub struct CommentCodeSlices<'a> {
455 last_slice_kind: CodeCharKind,
456 last_slice_end: usize,
459 impl<'a> CommentCodeSlices<'a> {
460 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
463 last_slice_kind: CodeCharKind::Comment,
469 impl<'a> Iterator for CommentCodeSlices<'a> {
470 type Item = (CodeCharKind, usize, &'a str);
472 fn next(&mut self) -> Option<Self::Item> {
473 if self.last_slice_end == self.slice.len() {
477 let mut sub_slice_end = self.last_slice_end;
478 let mut first_whitespace = None;
479 let subslice = &self.slice[self.last_slice_end..];
480 let mut iter = CharClasses::new(subslice.char_indices());
482 for (kind, (i, c)) in &mut iter {
483 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
484 &subslice[..2] == "//" &&
485 [' ', '\t'].contains(&c);
487 if is_comment_connector && first_whitespace.is_none() {
488 first_whitespace = Some(i);
491 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
492 let last_index = match first_whitespace {
496 sub_slice_end = self.last_slice_end + last_index;
500 if !is_comment_connector {
501 first_whitespace = None;
505 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
506 // This was the last subslice.
507 sub_slice_end = match first_whitespace {
508 Some(i) => self.last_slice_end + i,
509 None => self.slice.len(),
513 let kind = match self.last_slice_kind {
514 CodeCharKind::Comment => CodeCharKind::Normal,
515 CodeCharKind::Normal => CodeCharKind::Comment,
517 let res = (kind, self.last_slice_end, &self.slice[self.last_slice_end..sub_slice_end]);
518 self.last_slice_end = sub_slice_end;
519 self.last_slice_kind = kind;
525 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
526 /// (if it fits in the width/offset, else return None), else return `new`
527 pub fn recover_comment_removed(new: String,
529 context: &RewriteContext,
533 let snippet = context.snippet(span);
534 if changed_comment_content(&snippet, &new) {
535 // We missed some comments
536 // Keep previous formatting if it satisfies the constrains
537 wrap_str(snippet, context.config.max_width, width, offset)
543 /// Return true if the two strings of code have the same payload of comments.
544 /// The payload of comments is everything in the string except:
545 /// - actual code (not comments)
546 /// - comment start/end marks
548 /// - '*' at the beginning of lines in block comments
549 fn changed_comment_content(orig: &str, new: &str) -> bool {
550 // Cannot write this as a fn since we cannot return types containing closures
551 let code_comment_content = |code| {
552 let slices = UngroupedCommentCodeSlices::new(code);
553 slices.filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
554 .flat_map(|(_, _, s)| CommentReducer::new(s))
556 let res = code_comment_content(orig).ne(code_comment_content(new));
557 debug!("comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
561 code_comment_content(orig).collect::<String>(),
562 code_comment_content(new).collect::<String>());
567 /// Iterator over the 'payload' characters of a comment.
568 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
569 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
571 struct CommentReducer<'a> {
574 iter: std::str::Chars<'a>,
577 impl<'a> CommentReducer<'a> {
578 fn new(comment: &'a str) -> CommentReducer<'a> {
579 let is_block = comment.starts_with("/*");
580 let comment = remove_comment_header(comment);
583 at_start_line: false, // There are no supplementary '*' on the first line
584 iter: comment.chars(),
589 impl<'a> Iterator for CommentReducer<'a> {
591 fn next(&mut self) -> Option<Self::Item> {
593 let mut c = try_opt!(self.iter.next());
594 if self.is_block && self.at_start_line {
595 while c.is_whitespace() {
596 c = try_opt!(self.iter.next());
598 // Ignore leading '*'
600 c = try_opt!(self.iter.next());
604 self.at_start_line = true;
607 if !c.is_whitespace() {
615 fn remove_comment_header(comment: &str) -> &str {
616 if comment.starts_with("///") || comment.starts_with("//!") {
618 } else if comment.starts_with("//") {
620 } else if (comment.starts_with("/**") && !comment.starts_with("/**/")) ||
621 comment.starts_with("/*!") {
622 &comment[3..comment.len() - 2]
624 assert!(comment.starts_with("/*"),
625 format!("string '{}' is not a comment", comment));
626 &comment[2..comment.len() - 2]
632 use super::{CharClasses, CodeCharKind, FullCodeCharKind, contains_comment, rewrite_comment,
633 FindUncommented, CommentCodeSlices};
638 let mut iter = CharClasses::new("//\n\n".chars());
640 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
641 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
642 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
643 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
644 assert_eq!(None, iter.next());
648 fn comment_code_slices() {
649 let input = "code(); /* test */ 1 + 1";
650 let mut iter = CommentCodeSlices::new(input);
652 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
653 assert_eq!((CodeCharKind::Comment, 8, "/* test */"),
654 iter.next().unwrap());
655 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
656 assert_eq!(None, iter.next());
660 fn comment_code_slices_two() {
661 let input = "// comment\n test();";
662 let mut iter = CommentCodeSlices::new(input);
664 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
665 assert_eq!((CodeCharKind::Comment, 0, "// comment\n"),
666 iter.next().unwrap());
667 assert_eq!((CodeCharKind::Normal, 11, " test();"),
668 iter.next().unwrap());
669 assert_eq!(None, iter.next());
673 fn comment_code_slices_three() {
674 let input = "1 // comment\n // comment2\n\n";
675 let mut iter = CommentCodeSlices::new(input);
677 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
678 assert_eq!((CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
679 iter.next().unwrap());
680 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
681 assert_eq!(None, iter.next());
685 #[cfg_attr(rustfmt, rustfmt_skip)]
686 fn format_comments() {
687 let mut config: ::config::Config = Default::default();
688 config.wrap_comments = true;
690 let comment = rewrite_comment(" //test", true, 100, Indent::new(0, 100), &config).unwrap();
691 assert_eq!("/* test */", comment);
693 let comment = rewrite_comment("// comment on a",
698 assert_eq!("// comment\n// on a", comment);
700 let comment = rewrite_comment("// A multi line comment\n // between args.",
705 assert_eq!("// A multi line comment\n // between args.", comment);
707 let input = "// comment";
710 let comment = rewrite_comment(input, true, 9, Indent::new(0, 69), &config).unwrap();
711 assert_eq!(expected, comment);
713 let comment = rewrite_comment("/* trimmed */",
718 assert_eq!("/* trimmed */", comment);
721 // This is probably intended to be a non-test fn, but it is not used. I'm
722 // keeping it around unless it helps us test stuff.
723 fn uncommented(text: &str) -> String {
724 CharClasses::new(text.chars())
725 .filter_map(|(s, c)| {
727 FullCodeCharKind::Normal => Some(c),
735 fn test_uncommented() {
736 assert_eq!(&uncommented("abc/*...*/"), "abc");
737 assert_eq!(&uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
739 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
743 fn test_contains_comment() {
744 assert_eq!(contains_comment("abc"), false);
745 assert_eq!(contains_comment("abc // qsdf"), true);
746 assert_eq!(contains_comment("abc /* kqsdf"), true);
747 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
751 fn test_find_uncommented() {
752 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
753 assert_eq!(expected, haystack.find_uncommented(needle));
756 check("/*/ */test", "test", Some(6));
757 check("//test\ntest", "test", Some(7));
758 check("/* comment only */", "whatever", None);
759 check("/* comment */ some text /* more commentary */ result",
762 check("sup // sup", "p", Some(2));
763 check("sup", "x", None);
764 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
765 check("/*sup yo? \n sup*/ sup", "p", Some(20));
766 check("hel/*lohello*/lo", "hello", None);
767 check("acb", "ab", None);
768 check(",/*A*/ ", ",", Some(0));
769 check("abc", "abc", Some(0));
770 check("/* abc */", "abc", None);
771 check("/**/abc/* */", "abc", Some(4));
772 check("\"/* abc */\"", "abc", Some(4));
773 check("\"/* abc", "abc", Some(4));