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,
41 // If there are lines without a starting sigil, we won't format them correctly
42 // so in that case we won't even re-align (if !config.normalize_comments) and
43 // we should stop now.
44 let num_bare_lines = orig.lines()
45 .map(|line| line.trim())
46 .filter(|l| !(l.starts_with('*') || l.starts_with("//") || l.starts_with("/*")))
48 if num_bare_lines > 0 && !config.normalize_comments {
49 return Some(orig.to_owned());
52 if !config.normalize_comments && !config.wrap_comments {
53 return light_rewrite_comment(orig, offset, config);
56 let (opener, closer, line_start) =
59 } else if !config.normalize_comments {
60 if orig.starts_with("/**") && !orig.starts_with("/**/") {
61 ("/** ", " **/", " ** ")
62 } else if orig.starts_with("/*!") {
63 ("/*! ", " */", " * ")
64 } else if orig.starts_with("/*") {
66 } else if orig.starts_with("///") {
68 } else if orig.starts_with("//!") {
73 } else if orig.starts_with("///") ||
74 (orig.starts_with("/**") && !orig.starts_with("/**/")) {
76 } else if orig.starts_with("//!") || orig.starts_with("/*!") {
78 } else if is_custom_comment(orig) {
79 if orig.chars().nth(3) == Some(' ') {
80 (&orig[0..4], "", &orig[0..4])
82 (&orig[0..3], "", &orig[0..3])
88 let max_chars = width.checked_sub(closer.len() + opener.len()).unwrap_or(1);
89 let indent_str = offset.to_string(config);
90 let fmt = StringFormat {
93 line_start: line_start,
96 offset: offset + (opener.len() - line_start.len()),
101 let line_breaks = orig.trim_right().chars().filter(|&c| c == '\n').count();
102 let lines = orig.lines()
104 .map(|(i, mut line)| {
107 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
108 line = &line[..(line.len() - 2)].trim_right();
113 .map(left_trim_comment_line)
114 .map(|line| if orig.starts_with("/*") && line_breaks == 0 {
120 let mut result = opener.to_owned();
122 if result == opener {
128 result.push_str(&indent_str);
129 result.push_str(line_start);
132 if config.wrap_comments && line.len() > max_chars {
133 let rewrite = rewrite_string(line, &fmt).unwrap_or(line.to_owned());
134 result.push_str(&rewrite);
137 // Remove space if this is an empty comment or a doc comment.
140 result.push_str(line);
144 result.push_str(closer);
145 if result == opener {
153 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
154 fn light_rewrite_comment(orig: &str, offset: Indent, config: &Config) -> Option<String> {
155 let lines: Vec<&str> = orig.lines()
157 // This is basically just l.trim(), but in the case that a line starts
158 // with `*` we want to leave one space before it, so it aligns with the
160 let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
161 if let Some(fnw) = first_non_whitespace {
162 if l.as_bytes()[fnw] == '*' as u8 && fnw > 0 {
173 Some(lines.join(&format!("\n{}", offset.to_string(config))))
176 /// Trims comment characters and possibly a single space from the left of a string.
177 /// Does not trim all whitespace.
178 fn left_trim_comment_line(line: &str) -> &str {
179 if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") ||
180 line.starts_with("/** ") {
182 } else if is_custom_comment(line) {
183 if line.len() > 3 && line.chars().nth(3) == Some(' ') {
188 } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!") ||
189 line.starts_with("///") ||
190 line.starts_with("** ") || line.starts_with("/*!") ||
191 (line.starts_with("/**") && !line.starts_with("/**/")) {
193 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") ||
194 line.starts_with("**") {
196 } else if line.starts_with('*') {
203 pub trait FindUncommented {
204 fn find_uncommented(&self, pat: &str) -> Option<usize>;
207 impl FindUncommented for str {
208 fn find_uncommented(&self, pat: &str) -> Option<usize> {
209 let mut needle_iter = pat.chars();
210 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
211 match needle_iter.next() {
213 return Some(i - pat.len());
217 FullCodeCharKind::Normal if b == c => {}
219 needle_iter = pat.chars();
226 // Handle case where the pattern is a suffix of the search string
227 match needle_iter.next() {
229 None => Some(self.len() - pat.len()),
234 // Returns the first byte position after the first comment. The given string
235 // is expected to be prefixed by a comment, including delimiters.
236 // Good: "/* /* inner */ outer */ code();"
237 // Bad: "code(); // hello\n world!"
238 pub fn find_comment_end(s: &str) -> Option<usize> {
239 let mut iter = CharClasses::new(s.char_indices());
240 for (kind, (i, _c)) in &mut iter {
241 if kind == FullCodeCharKind::Normal {
246 // Handle case where the comment ends at the end of s.
247 if iter.status == CharClassesStatus::Normal {
254 /// Returns true if text contains any comment.
255 pub fn contains_comment(text: &str) -> bool {
256 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
259 struct CharClasses<T>
263 base: iter::Peekable<T>,
264 status: CharClassesStatus,
268 fn get_char(&self) -> char;
271 impl RichChar for char {
272 fn get_char(&self) -> char {
277 impl RichChar for (usize, char) {
278 fn get_char(&self) -> char {
283 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
284 enum CharClassesStatus {
290 // The u32 is the nesting deepness of the comment
292 // Status when the '/' has been consumed, but not yet the '*', deepness is
293 // the new deepness (after the comment opening).
294 BlockCommentOpening(u32),
295 // Status when the '*' has been consumed, but not yet the '/', deepness is
296 // the new deepness (after the comment closing).
297 BlockCommentClosing(u32),
301 /// Distinguish between functional part of code and comments
302 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
303 pub enum CodeCharKind {
308 /// Distinguish between functional part of code and comments,
309 /// describing opening and closing of comments for ease when chunking
310 /// code from tagged characters
311 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
312 enum FullCodeCharKind {
314 /// The first character of a comment, there is only one for a comment (always '/')
316 /// Any character inside a comment including the second character of comment
317 /// marks ("//", "/*")
319 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
323 impl FullCodeCharKind {
324 fn is_comment(&self) -> bool {
326 FullCodeCharKind::Normal => false,
327 FullCodeCharKind::StartComment |
328 FullCodeCharKind::InComment |
329 FullCodeCharKind::EndComment => true,
333 fn to_codecharkind(&self) -> CodeCharKind {
334 if self.is_comment() {
335 CodeCharKind::Comment
342 impl<T> CharClasses<T>
346 fn new(base: T) -> CharClasses<T> {
348 base: base.peekable(),
349 status: CharClassesStatus::Normal,
354 impl<T> Iterator for CharClasses<T>
358 type Item = (FullCodeCharKind, T::Item);
360 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
361 let item = try_opt!(self.base.next());
362 let chr = item.get_char();
363 self.status = match self.status {
364 CharClassesStatus::LitString => {
366 '"' => CharClassesStatus::Normal,
367 '\\' => CharClassesStatus::LitStringEscape,
368 _ => CharClassesStatus::LitString,
371 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
372 CharClassesStatus::LitChar => {
374 '\\' => CharClassesStatus::LitCharEscape,
375 '\'' => CharClassesStatus::Normal,
376 _ => CharClassesStatus::LitChar,
379 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
380 CharClassesStatus::Normal => {
382 '"' => CharClassesStatus::LitString,
383 '\'' => CharClassesStatus::LitChar,
385 match self.base.peek() {
386 Some(next) if next.get_char() == '*' => {
387 self.status = CharClassesStatus::BlockCommentOpening(1);
388 return Some((FullCodeCharKind::StartComment, item));
390 Some(next) if next.get_char() == '/' => {
391 self.status = CharClassesStatus::LineComment;
392 return Some((FullCodeCharKind::StartComment, item));
394 _ => CharClassesStatus::Normal,
397 _ => CharClassesStatus::Normal,
400 CharClassesStatus::BlockComment(deepness) => {
401 assert!(deepness != 0);
402 self.status = match self.base.peek() {
403 Some(next) if next.get_char() == '/' && chr == '*' => {
404 CharClassesStatus::BlockCommentClosing(deepness - 1)
406 Some(next) if next.get_char() == '*' && chr == '/' => {
407 CharClassesStatus::BlockCommentOpening(deepness + 1)
409 _ => CharClassesStatus::BlockComment(deepness),
411 return Some((FullCodeCharKind::InComment, item));
413 CharClassesStatus::BlockCommentOpening(deepness) => {
414 assert_eq!(chr, '*');
415 self.status = CharClassesStatus::BlockComment(deepness);
416 return Some((FullCodeCharKind::InComment, item));
418 CharClassesStatus::BlockCommentClosing(deepness) => {
419 assert_eq!(chr, '/');
421 self.status = CharClassesStatus::Normal;
422 return Some((FullCodeCharKind::EndComment, item));
424 self.status = CharClassesStatus::BlockComment(deepness);
425 return Some((FullCodeCharKind::InComment, item));
428 CharClassesStatus::LineComment => {
431 self.status = CharClassesStatus::Normal;
432 return Some((FullCodeCharKind::EndComment, item));
435 self.status = CharClassesStatus::LineComment;
436 return Some((FullCodeCharKind::InComment, item));
441 Some((FullCodeCharKind::Normal, item))
445 /// Iterator over functional and commented parts of a string. Any part of a string is either
446 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
447 /// comments is functional code. Line comments contain their ending newlines.
448 struct UngroupedCommentCodeSlices<'a> {
450 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
453 impl<'a> UngroupedCommentCodeSlices<'a> {
454 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
455 UngroupedCommentCodeSlices {
457 iter: CharClasses::new(code.char_indices()).peekable(),
462 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
463 type Item = (CodeCharKind, usize, &'a str);
465 fn next(&mut self) -> Option<Self::Item> {
466 let (kind, (start_idx, _)) = try_opt!(self.iter.next());
468 FullCodeCharKind::Normal => {
469 // Consume all the Normal code
470 while let Some(&(FullCodeCharKind::Normal, (_, _))) = self.iter.peek() {
471 let _ = self.iter.next();
474 FullCodeCharKind::StartComment => {
475 // Consume the whole comment
476 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
480 let slice = match self.iter.peek() {
481 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
482 None => &self.slice[start_idx..],
484 Some((if kind.is_comment() {
485 CodeCharKind::Comment
497 /// Iterator over an alternating sequence of functional and commented parts of
498 /// a string. The first item is always a, possibly zero length, subslice of
499 /// functional text. Line style comments contain their ending newlines.
500 pub struct CommentCodeSlices<'a> {
502 last_slice_kind: CodeCharKind,
503 last_slice_end: usize,
506 impl<'a> CommentCodeSlices<'a> {
507 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
510 last_slice_kind: CodeCharKind::Comment,
516 impl<'a> Iterator for CommentCodeSlices<'a> {
517 type Item = (CodeCharKind, usize, &'a str);
519 fn next(&mut self) -> Option<Self::Item> {
520 if self.last_slice_end == self.slice.len() {
524 let mut sub_slice_end = self.last_slice_end;
525 let mut first_whitespace = None;
526 let subslice = &self.slice[self.last_slice_end..];
527 let mut iter = CharClasses::new(subslice.char_indices());
529 for (kind, (i, c)) in &mut iter {
530 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
531 &subslice[..2] == "//" &&
532 [' ', '\t'].contains(&c);
534 if is_comment_connector && first_whitespace.is_none() {
535 first_whitespace = Some(i);
538 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
539 let last_index = match first_whitespace {
543 sub_slice_end = self.last_slice_end + last_index;
547 if !is_comment_connector {
548 first_whitespace = None;
552 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
553 // This was the last subslice.
554 sub_slice_end = match first_whitespace {
555 Some(i) => self.last_slice_end + i,
556 None => self.slice.len(),
560 let kind = match self.last_slice_kind {
561 CodeCharKind::Comment => CodeCharKind::Normal,
562 CodeCharKind::Normal => CodeCharKind::Comment,
564 let res = (kind, self.last_slice_end, &self.slice[self.last_slice_end..sub_slice_end]);
565 self.last_slice_end = sub_slice_end;
566 self.last_slice_kind = kind;
572 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
573 /// (if it fits in the width/offset, else return None), else return `new`
574 pub fn recover_comment_removed(new: String,
576 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, width, offset)
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);
600 slices.filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
601 .flat_map(|(_, _, s)| CommentReducer::new(s))
603 let res = code_comment_content(orig).ne(code_comment_content(new));
604 debug!("comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
608 code_comment_content(orig).collect::<String>(),
609 code_comment_content(new).collect::<String>());
614 /// Iterator over the 'payload' characters of a comment.
615 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
616 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
618 struct CommentReducer<'a> {
621 iter: std::str::Chars<'a>,
624 impl<'a> CommentReducer<'a> {
625 fn new(comment: &'a str) -> CommentReducer<'a> {
626 let is_block = comment.starts_with("/*");
627 let comment = remove_comment_header(comment);
630 at_start_line: false, // There are no supplementary '*' on the first line
631 iter: comment.chars(),
636 impl<'a> Iterator for CommentReducer<'a> {
638 fn next(&mut self) -> Option<Self::Item> {
640 let mut c = try_opt!(self.iter.next());
641 if self.is_block && self.at_start_line {
642 while c.is_whitespace() {
643 c = try_opt!(self.iter.next());
645 // Ignore leading '*'
647 c = try_opt!(self.iter.next());
651 self.at_start_line = true;
654 if !c.is_whitespace() {
662 fn remove_comment_header(comment: &str) -> &str {
663 if comment.starts_with("///") || comment.starts_with("//!") {
665 } else if comment.starts_with("//") {
667 } else if (comment.starts_with("/**") && !comment.starts_with("/**/")) ||
668 comment.starts_with("/*!") {
669 &comment[3..comment.len() - 2]
671 assert!(comment.starts_with("/*"),
672 format!("string '{}' is not a comment", comment));
673 &comment[2..comment.len() - 2]
679 use super::{CharClasses, CodeCharKind, FullCodeCharKind, contains_comment, rewrite_comment,
680 FindUncommented, CommentCodeSlices};
685 let mut iter = CharClasses::new("//\n\n".chars());
687 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
688 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
689 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
690 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
691 assert_eq!(None, iter.next());
695 fn comment_code_slices() {
696 let input = "code(); /* test */ 1 + 1";
697 let mut iter = CommentCodeSlices::new(input);
699 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
700 assert_eq!((CodeCharKind::Comment, 8, "/* test */"),
701 iter.next().unwrap());
702 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
703 assert_eq!(None, iter.next());
707 fn comment_code_slices_two() {
708 let input = "// comment\n test();";
709 let mut iter = CommentCodeSlices::new(input);
711 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
712 assert_eq!((CodeCharKind::Comment, 0, "// comment\n"),
713 iter.next().unwrap());
714 assert_eq!((CodeCharKind::Normal, 11, " test();"),
715 iter.next().unwrap());
716 assert_eq!(None, iter.next());
720 fn comment_code_slices_three() {
721 let input = "1 // comment\n // comment2\n\n";
722 let mut iter = CommentCodeSlices::new(input);
724 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
725 assert_eq!((CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
726 iter.next().unwrap());
727 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
728 assert_eq!(None, iter.next());
732 #[cfg_attr(rustfmt, rustfmt_skip)]
733 fn format_comments() {
734 let mut config: ::config::Config = Default::default();
735 config.wrap_comments = true;
736 config.normalize_comments = true;
738 let comment = rewrite_comment(" //test", true, 100, Indent::new(0, 100), &config).unwrap();
739 assert_eq!("/* test */", comment);
741 let comment = rewrite_comment("// comment on a",
746 assert_eq!("// comment\n// on a", comment);
748 let comment = rewrite_comment("// A multi line comment\n // between args.",
753 assert_eq!("// A multi line comment\n // between args.", comment);
755 let input = "// comment";
758 let comment = rewrite_comment(input, true, 9, Indent::new(0, 69), &config).unwrap();
759 assert_eq!(expected, comment);
761 let comment = rewrite_comment("/* trimmed */",
766 assert_eq!("/* trimmed */", comment);
769 // This is probably intended to be a non-test fn, but it is not used. I'm
770 // keeping it around unless it helps us test stuff.
771 fn uncommented(text: &str) -> String {
772 CharClasses::new(text.chars())
773 .filter_map(|(s, c)| match s {
774 FullCodeCharKind::Normal => Some(c),
781 fn test_uncommented() {
782 assert_eq!(&uncommented("abc/*...*/"), "abc");
783 assert_eq!(&uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
785 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
789 fn test_contains_comment() {
790 assert_eq!(contains_comment("abc"), false);
791 assert_eq!(contains_comment("abc // qsdf"), true);
792 assert_eq!(contains_comment("abc /* kqsdf"), true);
793 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
797 fn test_find_uncommented() {
798 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
799 assert_eq!(expected, haystack.find_uncommented(needle));
802 check("/*/ */test", "test", Some(6));
803 check("//test\ntest", "test", Some(7));
804 check("/* comment only */", "whatever", None);
805 check("/* comment */ some text /* more commentary */ result",
808 check("sup // sup", "p", Some(2));
809 check("sup", "x", None);
810 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
811 check("/*sup yo? \n sup*/ sup", "p", Some(20));
812 check("hel/*lohello*/lo", "hello", None);
813 check("acb", "ab", None);
814 check(",/*A*/ ", ",", Some(0));
815 check("abc", "abc", Some(0));
816 check("/* abc */", "abc", None);
817 check("/**/abc/* */", "abc", Some(4));
818 check("\"/* abc */\"", "abc", Some(4));
819 check("\"/* abc", "abc", Some(4));