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 fn is_custom_comment(comment: &str) -> bool {
24 if !comment.starts_with("//") {
27 if let Some(c) = comment.chars().nth(2) {
28 !c.is_alphanumeric() && !c.is_whitespace()
35 pub fn rewrite_comment(orig: &str,
40 // If there are lines without a starting sigil, we won't format them correctly
41 // so in that case we won't even re-align (if !config.normalize_comments) and
42 // we should stop now.
43 let num_bare_lines = orig.lines()
44 .map(|line| line.trim())
45 .filter(|l| !(l.starts_with('*') || l.starts_with("//") || l.starts_with("/*")))
47 if num_bare_lines > 0 && !config.normalize_comments {
48 return Some(orig.to_owned());
51 if !config.normalize_comments && !config.wrap_comments {
52 return light_rewrite_comment(orig, shape.indent, config);
55 let (opener, closer, line_start) =
58 } else if !config.normalize_comments {
59 if orig.starts_with("/**") && !orig.starts_with("/**/") {
60 ("/** ", " **/", " ** ")
61 } else if orig.starts_with("/*!") {
62 ("/*! ", " */", " * ")
63 } else if orig.starts_with("/*") {
65 } else if orig.starts_with("///") {
67 } else if orig.starts_with("//!") {
72 } else if orig.starts_with("///") ||
73 (orig.starts_with("/**") && !orig.starts_with("/**/")) {
75 } else if orig.starts_with("//!") || orig.starts_with("/*!") {
77 } else if is_custom_comment(orig) {
78 if orig.chars().nth(3) == Some(' ') {
79 (&orig[0..4], "", &orig[0..4])
81 (&orig[0..3], "", &orig[0..3])
89 .checked_sub(closer.len() + opener.len())
91 let indent_str = shape.indent.to_string(config);
92 let fmt = StringFormat {
95 line_start: line_start,
97 shape: Shape::legacy(max_chars, shape.indent + (opener.len() - line_start.len())),
102 let line_breaks = orig.trim_right().chars().filter(|&c| c == '\n').count();
103 let lines = orig.lines()
105 .map(|(i, mut line)| {
108 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
109 line = &line[..(line.len() - 2)].trim_right();
114 .map(left_trim_comment_line)
115 .map(|line| if orig.starts_with("/*") && line_breaks == 0 {
121 let mut result = opener.to_owned();
123 if result == opener {
129 result.push_str(&indent_str);
130 result.push_str(line_start);
133 if config.wrap_comments && line.len() > max_chars {
134 let rewrite = rewrite_string(line, &fmt).unwrap_or(line.to_owned());
135 result.push_str(&rewrite);
138 // Remove space if this is an empty comment or a doc comment.
141 result.push_str(line);
145 result.push_str(closer);
146 if result == opener {
154 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
155 fn light_rewrite_comment(orig: &str, offset: Indent, config: &Config) -> Option<String> {
156 let lines: Vec<&str> = orig.lines()
158 // This is basically just l.trim(), but in the case that a line starts
159 // with `*` we want to leave one space before it, so it aligns with the
161 let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
162 if let Some(fnw) = first_non_whitespace {
163 if l.as_bytes()[fnw] == '*' as u8 && fnw > 0 {
174 Some(lines.join(&format!("\n{}", offset.to_string(config))))
177 /// Trims comment characters and possibly a single space from the left of a string.
178 /// Does not trim all whitespace.
179 fn left_trim_comment_line(line: &str) -> &str {
180 if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") ||
181 line.starts_with("/** ") {
183 } else if is_custom_comment(line) {
184 if line.len() > 3 && line.chars().nth(3) == Some(' ') {
189 } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!") ||
190 line.starts_with("///") ||
191 line.starts_with("** ") || line.starts_with("/*!") ||
192 (line.starts_with("/**") && !line.starts_with("/**/")) {
194 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") ||
195 line.starts_with("**") {
197 } else if line.starts_with('*') {
204 pub trait FindUncommented {
205 fn find_uncommented(&self, pat: &str) -> Option<usize>;
208 impl FindUncommented for str {
209 fn find_uncommented(&self, pat: &str) -> Option<usize> {
210 let mut needle_iter = pat.chars();
211 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
212 match needle_iter.next() {
214 return Some(i - pat.len());
218 FullCodeCharKind::Normal if b == c => {}
220 needle_iter = pat.chars();
227 // Handle case where the pattern is a suffix of the search string
228 match needle_iter.next() {
230 None => Some(self.len() - pat.len()),
235 // Returns the first byte position after the first comment. The given string
236 // is expected to be prefixed by a comment, including delimiters.
237 // Good: "/* /* inner */ outer */ code();"
238 // Bad: "code(); // hello\n world!"
239 pub fn find_comment_end(s: &str) -> Option<usize> {
240 let mut iter = CharClasses::new(s.char_indices());
241 for (kind, (i, _c)) in &mut iter {
242 if kind == FullCodeCharKind::Normal {
247 // Handle case where the comment ends at the end of s.
248 if iter.status == CharClassesStatus::Normal {
255 /// Returns true if text contains any comment.
256 pub fn contains_comment(text: &str) -> bool {
257 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
260 struct CharClasses<T>
264 base: iter::Peekable<T>,
265 status: CharClassesStatus,
269 fn get_char(&self) -> char;
272 impl RichChar for char {
273 fn get_char(&self) -> char {
278 impl RichChar for (usize, char) {
279 fn get_char(&self) -> char {
284 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
285 enum CharClassesStatus {
291 // The u32 is the nesting deepness of the comment
293 // Status when the '/' has been consumed, but not yet the '*', deepness is
294 // the new deepness (after the comment opening).
295 BlockCommentOpening(u32),
296 // Status when the '*' has been consumed, but not yet the '/', deepness is
297 // the new deepness (after the comment closing).
298 BlockCommentClosing(u32),
302 /// Distinguish between functional part of code and comments
303 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
304 pub enum CodeCharKind {
309 /// Distinguish between functional part of code and comments,
310 /// describing opening and closing of comments for ease when chunking
311 /// code from tagged characters
312 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
313 enum FullCodeCharKind {
315 /// The first character of a comment, there is only one for a comment (always '/')
317 /// Any character inside a comment including the second character of comment
318 /// marks ("//", "/*")
320 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
324 impl FullCodeCharKind {
325 fn is_comment(&self) -> bool {
327 FullCodeCharKind::Normal => false,
328 FullCodeCharKind::StartComment |
329 FullCodeCharKind::InComment |
330 FullCodeCharKind::EndComment => true,
334 fn to_codecharkind(&self) -> CodeCharKind {
335 if self.is_comment() {
336 CodeCharKind::Comment
343 impl<T> CharClasses<T>
347 fn new(base: T) -> CharClasses<T> {
349 base: base.peekable(),
350 status: CharClassesStatus::Normal,
355 impl<T> Iterator for CharClasses<T>
359 type Item = (FullCodeCharKind, T::Item);
361 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
362 let item = try_opt!(self.base.next());
363 let chr = item.get_char();
364 self.status = match self.status {
365 CharClassesStatus::LitString => {
367 '"' => CharClassesStatus::Normal,
368 '\\' => CharClassesStatus::LitStringEscape,
369 _ => CharClassesStatus::LitString,
372 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
373 CharClassesStatus::LitChar => {
375 '\\' => CharClassesStatus::LitCharEscape,
376 '\'' => CharClassesStatus::Normal,
377 _ => CharClassesStatus::LitChar,
380 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
381 CharClassesStatus::Normal => {
383 '"' => CharClassesStatus::LitString,
384 '\'' => CharClassesStatus::LitChar,
386 match self.base.peek() {
387 Some(next) if next.get_char() == '*' => {
388 self.status = CharClassesStatus::BlockCommentOpening(1);
389 return Some((FullCodeCharKind::StartComment, item));
391 Some(next) if next.get_char() == '/' => {
392 self.status = CharClassesStatus::LineComment;
393 return Some((FullCodeCharKind::StartComment, item));
395 _ => CharClassesStatus::Normal,
398 _ => CharClassesStatus::Normal,
401 CharClassesStatus::BlockComment(deepness) => {
402 assert!(deepness != 0);
403 self.status = match self.base.peek() {
404 Some(next) if next.get_char() == '/' && chr == '*' => {
405 CharClassesStatus::BlockCommentClosing(deepness - 1)
407 Some(next) if next.get_char() == '*' && chr == '/' => {
408 CharClassesStatus::BlockCommentOpening(deepness + 1)
410 _ => CharClassesStatus::BlockComment(deepness),
412 return Some((FullCodeCharKind::InComment, item));
414 CharClassesStatus::BlockCommentOpening(deepness) => {
415 assert_eq!(chr, '*');
416 self.status = CharClassesStatus::BlockComment(deepness);
417 return Some((FullCodeCharKind::InComment, item));
419 CharClassesStatus::BlockCommentClosing(deepness) => {
420 assert_eq!(chr, '/');
422 self.status = CharClassesStatus::Normal;
423 return Some((FullCodeCharKind::EndComment, item));
425 self.status = CharClassesStatus::BlockComment(deepness);
426 return Some((FullCodeCharKind::InComment, item));
429 CharClassesStatus::LineComment => {
432 self.status = CharClassesStatus::Normal;
433 return Some((FullCodeCharKind::EndComment, item));
436 self.status = CharClassesStatus::LineComment;
437 return Some((FullCodeCharKind::InComment, item));
442 Some((FullCodeCharKind::Normal, item))
446 /// Iterator over functional and commented parts of a string. Any part of a string is either
447 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
448 /// comments is functional code. Line comments contain their ending newlines.
449 struct UngroupedCommentCodeSlices<'a> {
451 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
454 impl<'a> UngroupedCommentCodeSlices<'a> {
455 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
456 UngroupedCommentCodeSlices {
458 iter: CharClasses::new(code.char_indices()).peekable(),
463 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
464 type Item = (CodeCharKind, usize, &'a str);
466 fn next(&mut self) -> Option<Self::Item> {
467 let (kind, (start_idx, _)) = try_opt!(self.iter.next());
469 FullCodeCharKind::Normal => {
470 // Consume all the Normal code
471 while let Some(&(FullCodeCharKind::Normal, (_, _))) = self.iter.peek() {
472 let _ = self.iter.next();
475 FullCodeCharKind::StartComment => {
476 // Consume the whole comment
477 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
481 let slice = match self.iter.peek() {
482 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
483 None => &self.slice[start_idx..],
485 Some((if kind.is_comment() {
486 CodeCharKind::Comment
498 /// Iterator over an alternating sequence of functional and commented parts of
499 /// a string. The first item is always a, possibly zero length, subslice of
500 /// functional text. Line style comments contain their ending newlines.
501 pub struct CommentCodeSlices<'a> {
503 last_slice_kind: CodeCharKind,
504 last_slice_end: usize,
507 impl<'a> CommentCodeSlices<'a> {
508 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
511 last_slice_kind: CodeCharKind::Comment,
517 impl<'a> Iterator for CommentCodeSlices<'a> {
518 type Item = (CodeCharKind, usize, &'a str);
520 fn next(&mut self) -> Option<Self::Item> {
521 if self.last_slice_end == self.slice.len() {
525 let mut sub_slice_end = self.last_slice_end;
526 let mut first_whitespace = None;
527 let subslice = &self.slice[self.last_slice_end..];
528 let mut iter = CharClasses::new(subslice.char_indices());
530 for (kind, (i, c)) in &mut iter {
531 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
532 &subslice[..2] == "//" &&
533 [' ', '\t'].contains(&c);
535 if is_comment_connector && first_whitespace.is_none() {
536 first_whitespace = Some(i);
539 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
540 let last_index = match first_whitespace {
544 sub_slice_end = self.last_slice_end + last_index;
548 if !is_comment_connector {
549 first_whitespace = None;
553 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
554 // This was the last subslice.
555 sub_slice_end = match first_whitespace {
556 Some(i) => self.last_slice_end + i,
557 None => self.slice.len(),
561 let kind = match self.last_slice_kind {
562 CodeCharKind::Comment => CodeCharKind::Normal,
563 CodeCharKind::Normal => CodeCharKind::Comment,
565 let res = (kind, self.last_slice_end, &self.slice[self.last_slice_end..sub_slice_end]);
566 self.last_slice_end = sub_slice_end;
567 self.last_slice_kind = kind;
573 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
574 /// (if it fits in the width/offset, else return None), else return `new`
575 pub fn recover_comment_removed(new: String,
577 context: &RewriteContext,
580 let snippet = context.snippet(span);
581 if changed_comment_content(&snippet, &new) {
582 // We missed some comments
583 // Keep previous formatting if it satisfies the constrains
584 wrap_str(snippet, context.config.max_width, shape)
590 /// Return true if the two strings of code have the same payload of comments.
591 /// The payload of comments is everything in the string except:
592 /// - actual code (not comments)
593 /// - comment start/end marks
595 /// - '*' at the beginning of lines in block comments
596 fn changed_comment_content(orig: &str, new: &str) -> bool {
597 // Cannot write this as a fn since we cannot return types containing closures
598 let code_comment_content = |code| {
599 let slices = UngroupedCommentCodeSlices::new(code);
601 .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
602 .flat_map(|(_, _, s)| CommentReducer::new(s))
604 let res = code_comment_content(orig).ne(code_comment_content(new));
605 debug!("comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
609 code_comment_content(orig).collect::<String>(),
610 code_comment_content(new).collect::<String>());
615 /// Iterator over the 'payload' characters of a comment.
616 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
617 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
619 struct CommentReducer<'a> {
622 iter: std::str::Chars<'a>,
625 impl<'a> CommentReducer<'a> {
626 fn new(comment: &'a str) -> CommentReducer<'a> {
627 let is_block = comment.starts_with("/*");
628 let comment = remove_comment_header(comment);
631 at_start_line: false, // There are no supplementary '*' on the first line
632 iter: comment.chars(),
637 impl<'a> Iterator for CommentReducer<'a> {
639 fn next(&mut self) -> Option<Self::Item> {
641 let mut c = try_opt!(self.iter.next());
642 if self.is_block && self.at_start_line {
643 while c.is_whitespace() {
644 c = try_opt!(self.iter.next());
646 // Ignore leading '*'
648 c = try_opt!(self.iter.next());
652 self.at_start_line = true;
655 if !c.is_whitespace() {
663 fn remove_comment_header(comment: &str) -> &str {
664 if comment.starts_with("///") || comment.starts_with("//!") {
666 } else if comment.starts_with("//") {
668 } else if (comment.starts_with("/**") && !comment.starts_with("/**/")) ||
669 comment.starts_with("/*!") {
670 &comment[3..comment.len() - 2]
672 assert!(comment.starts_with("/*"),
673 format!("string '{}' is not a comment", comment));
674 &comment[2..comment.len() - 2]
680 use super::{CharClasses, CodeCharKind, FullCodeCharKind, contains_comment, rewrite_comment,
681 FindUncommented, CommentCodeSlices};
686 let mut iter = CharClasses::new("//\n\n".chars());
688 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
689 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
690 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
691 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
692 assert_eq!(None, iter.next());
696 fn comment_code_slices() {
697 let input = "code(); /* test */ 1 + 1";
698 let mut iter = CommentCodeSlices::new(input);
700 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
701 assert_eq!((CodeCharKind::Comment, 8, "/* test */"),
702 iter.next().unwrap());
703 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
704 assert_eq!(None, iter.next());
708 fn comment_code_slices_two() {
709 let input = "// comment\n test();";
710 let mut iter = CommentCodeSlices::new(input);
712 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
713 assert_eq!((CodeCharKind::Comment, 0, "// comment\n"),
714 iter.next().unwrap());
715 assert_eq!((CodeCharKind::Normal, 11, " test();"),
716 iter.next().unwrap());
717 assert_eq!(None, iter.next());
721 fn comment_code_slices_three() {
722 let input = "1 // comment\n // comment2\n\n";
723 let mut iter = CommentCodeSlices::new(input);
725 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
726 assert_eq!((CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
727 iter.next().unwrap());
728 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
729 assert_eq!(None, iter.next());
733 #[cfg_attr(rustfmt, rustfmt_skip)]
734 fn format_comments() {
735 let mut config: ::config::Config = Default::default();
736 config.wrap_comments = true;
737 config.normalize_comments = true;
739 let comment = rewrite_comment(" //test",
741 Shape::legacy(100, Indent::new(0, 100)),
743 assert_eq!("/* test */", comment);
745 let comment = rewrite_comment("// comment on a",
747 Shape::legacy(10, Indent::empty()),
749 assert_eq!("// comment\n// on a", comment);
751 let comment = rewrite_comment("// A multi line comment\n // between args.",
753 Shape::legacy(60, Indent::new(0, 12)),
755 assert_eq!("// A multi line comment\n // between args.", comment);
757 let input = "// comment";
760 let comment = rewrite_comment(input,
762 Shape::legacy(9, Indent::new(0, 69)),
764 assert_eq!(expected, comment);
766 let comment = rewrite_comment("/* trimmed */",
768 Shape::legacy(100, Indent::new(0, 100)),
770 assert_eq!("/* trimmed */", comment);
773 // This is probably intended to be a non-test fn, but it is not used. I'm
774 // keeping it around unless it helps us test stuff.
775 fn uncommented(text: &str) -> String {
776 CharClasses::new(text.chars())
777 .filter_map(|(s, c)| match s {
778 FullCodeCharKind::Normal => Some(c),
785 fn test_uncommented() {
786 assert_eq!(&uncommented("abc/*...*/"), "abc");
787 assert_eq!(&uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
789 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
793 fn test_contains_comment() {
794 assert_eq!(contains_comment("abc"), false);
795 assert_eq!(contains_comment("abc // qsdf"), true);
796 assert_eq!(contains_comment("abc /* kqsdf"), true);
797 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
801 fn test_find_uncommented() {
802 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
803 assert_eq!(expected, haystack.find_uncommented(needle));
806 check("/*/ */test", "test", Some(6));
807 check("//test\ntest", "test", Some(7));
808 check("/* comment only */", "whatever", None);
809 check("/* comment */ some text /* more commentary */ result",
812 check("sup // sup", "p", Some(2));
813 check("sup", "x", None);
814 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
815 check("/*sup yo? \n sup*/ sup", "p", Some(20));
816 check("hel/*lohello*/lo", "hello", None);
817 check("acb", "ab", None);
818 check(",/*A*/ ", ",", Some(0));
819 check("abc", "abc", Some(0));
820 check("/* abc */", "abc", None);
821 check("/**/abc/* */", "abc", Some(4));
822 check("\"/* abc */\"", "abc", Some(4));
823 check("\"/* abc", "abc", Some(4));