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,
43 // Edge case: block comments. Let's not trim their lines (for now).
44 let (opener, closer, line_start) =
47 } else if !config.normalize_comments {
48 if orig.starts_with("/**") && !orig.starts_with("/**/") {
49 ("/** ", " **/", " ** ")
50 } else if orig.starts_with("/*!") {
51 ("/*! ", " */", " * ")
52 } else if orig.starts_with("/*") {
54 } else if orig.starts_with("///") {
56 } else if orig.starts_with("//!") {
61 } else if orig.starts_with("///") ||
62 (orig.starts_with("/**") && !orig.starts_with("/**/")) {
64 } else if orig.starts_with("//!") || orig.starts_with("/*!") {
66 } else if is_custom_comment(orig) {
67 if orig.chars().nth(3) == Some(' ') {
68 (&orig[0..4], "", &orig[0..4])
70 (&orig[0..3], "", &orig[0..3])
76 let max_chars = width.checked_sub(closer.len() + opener.len()).unwrap_or(1);
78 let fmt = StringFormat {
81 line_start: line_start,
84 offset: offset + (opener.len() - line_start.len()),
89 let indent_str = offset.to_string(config);
90 let line_breaks = s.chars().filter(|&c| c == '\n').count();
92 let num_bare_lines = s.lines()
94 .map(|(_, line)| line.trim())
95 .filter(|l| !(l.starts_with('*') || l.starts_with("//") || l.starts_with("/*")))
98 if num_bare_lines > 0 && !config.normalize_comments {
99 return Some(orig.to_owned());
102 let lines = s.lines()
104 .map(|(i, mut line)| {
107 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
108 line = &line[..(line.len() - 2)];
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 fn left_trim_comment_line(line: &str) -> &str {
154 if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") ||
155 line.starts_with("/** ") {
157 } else if is_custom_comment(line) {
158 if line.len() > 3 && line.chars().nth(3) == Some(' ') {
163 } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!") ||
164 line.starts_with("///") ||
165 line.starts_with("** ") || line.starts_with("/*!") ||
166 (line.starts_with("/**") && !line.starts_with("/**/")) {
168 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") ||
169 line.starts_with("**") {
171 } else if line.starts_with('*') {
178 pub trait FindUncommented {
179 fn find_uncommented(&self, pat: &str) -> Option<usize>;
182 impl FindUncommented for str {
183 fn find_uncommented(&self, pat: &str) -> Option<usize> {
184 let mut needle_iter = pat.chars();
185 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
186 match needle_iter.next() {
188 return Some(i - pat.len());
192 FullCodeCharKind::Normal if b == c => {}
194 needle_iter = pat.chars();
201 // Handle case where the pattern is a suffix of the search string
202 match needle_iter.next() {
204 None => Some(self.len() - pat.len()),
209 // Returns the first byte position after the first comment. The given string
210 // is expected to be prefixed by a comment, including delimiters.
211 // Good: "/* /* inner */ outer */ code();"
212 // Bad: "code(); // hello\n world!"
213 pub fn find_comment_end(s: &str) -> Option<usize> {
214 let mut iter = CharClasses::new(s.char_indices());
215 for (kind, (i, _c)) in &mut iter {
216 if kind == FullCodeCharKind::Normal {
221 // Handle case where the comment ends at the end of s.
222 if iter.status == CharClassesStatus::Normal {
229 /// Returns true if text contains any comment.
230 pub fn contains_comment(text: &str) -> bool {
231 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
234 struct CharClasses<T>
238 base: iter::Peekable<T>,
239 status: CharClassesStatus,
243 fn get_char(&self) -> char;
246 impl RichChar for char {
247 fn get_char(&self) -> char {
252 impl RichChar for (usize, char) {
253 fn get_char(&self) -> char {
258 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
259 enum CharClassesStatus {
265 // The u32 is the nesting deepness of the comment
267 // Status when the '/' has been consumed, but not yet the '*', deepness is
268 // the new deepness (after the comment opening).
269 BlockCommentOpening(u32),
270 // Status when the '*' has been consumed, but not yet the '/', deepness is
271 // the new deepness (after the comment closing).
272 BlockCommentClosing(u32),
276 /// Distinguish between functional part of code and comments
277 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
278 pub enum CodeCharKind {
283 /// Distinguish between functional part of code and comments,
284 /// describing opening and closing of comments for ease when chunking
285 /// code from tagged characters
286 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
287 enum FullCodeCharKind {
289 /// The first character of a comment, there is only one for a comment (always '/')
291 /// Any character inside a comment including the second character of comment
292 /// marks ("//", "/*")
294 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
298 impl FullCodeCharKind {
299 fn is_comment(&self) -> bool {
301 FullCodeCharKind::Normal => false,
302 FullCodeCharKind::StartComment |
303 FullCodeCharKind::InComment |
304 FullCodeCharKind::EndComment => true,
308 fn to_codecharkind(&self) -> CodeCharKind {
309 if self.is_comment() {
310 CodeCharKind::Comment
317 impl<T> CharClasses<T>
321 fn new(base: T) -> CharClasses<T> {
323 base: base.peekable(),
324 status: CharClassesStatus::Normal,
329 impl<T> Iterator for CharClasses<T>
333 type Item = (FullCodeCharKind, T::Item);
335 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
336 let item = try_opt!(self.base.next());
337 let chr = item.get_char();
338 self.status = match self.status {
339 CharClassesStatus::LitString => {
341 '"' => CharClassesStatus::Normal,
342 '\\' => CharClassesStatus::LitStringEscape,
343 _ => CharClassesStatus::LitString,
346 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
347 CharClassesStatus::LitChar => {
349 '\\' => CharClassesStatus::LitCharEscape,
350 '\'' => CharClassesStatus::Normal,
351 _ => CharClassesStatus::LitChar,
354 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
355 CharClassesStatus::Normal => {
357 '"' => CharClassesStatus::LitString,
358 '\'' => CharClassesStatus::LitChar,
360 match self.base.peek() {
361 Some(next) if next.get_char() == '*' => {
362 self.status = CharClassesStatus::BlockCommentOpening(1);
363 return Some((FullCodeCharKind::StartComment, item));
365 Some(next) if next.get_char() == '/' => {
366 self.status = CharClassesStatus::LineComment;
367 return Some((FullCodeCharKind::StartComment, item));
369 _ => CharClassesStatus::Normal,
372 _ => CharClassesStatus::Normal,
375 CharClassesStatus::BlockComment(deepness) => {
376 assert!(deepness != 0);
377 self.status = match self.base.peek() {
378 Some(next) if next.get_char() == '/' && chr == '*' => {
379 CharClassesStatus::BlockCommentClosing(deepness - 1)
381 Some(next) if next.get_char() == '*' && chr == '/' => {
382 CharClassesStatus::BlockCommentOpening(deepness + 1)
384 _ => CharClassesStatus::BlockComment(deepness),
386 return Some((FullCodeCharKind::InComment, item));
388 CharClassesStatus::BlockCommentOpening(deepness) => {
389 assert_eq!(chr, '*');
390 self.status = CharClassesStatus::BlockComment(deepness);
391 return Some((FullCodeCharKind::InComment, item));
393 CharClassesStatus::BlockCommentClosing(deepness) => {
394 assert_eq!(chr, '/');
396 self.status = CharClassesStatus::Normal;
397 return Some((FullCodeCharKind::EndComment, item));
399 self.status = CharClassesStatus::BlockComment(deepness);
400 return Some((FullCodeCharKind::InComment, item));
403 CharClassesStatus::LineComment => {
406 self.status = CharClassesStatus::Normal;
407 return Some((FullCodeCharKind::EndComment, item));
410 self.status = CharClassesStatus::LineComment;
411 return Some((FullCodeCharKind::InComment, item));
416 Some((FullCodeCharKind::Normal, item))
420 /// Iterator over functional and commented parts of a string. Any part of a string is either
421 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
422 /// comments is functional code. Line comments contain their ending newlines.
423 struct UngroupedCommentCodeSlices<'a> {
425 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
428 impl<'a> UngroupedCommentCodeSlices<'a> {
429 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
430 UngroupedCommentCodeSlices {
432 iter: CharClasses::new(code.char_indices()).peekable(),
437 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
438 type Item = (CodeCharKind, usize, &'a str);
440 fn next(&mut self) -> Option<Self::Item> {
441 let (kind, (start_idx, _)) = try_opt!(self.iter.next());
443 FullCodeCharKind::Normal => {
444 // Consume all the Normal code
445 while let Some(&(FullCodeCharKind::Normal, (_, _))) = self.iter.peek() {
446 let _ = self.iter.next();
449 FullCodeCharKind::StartComment => {
450 // Consume the whole comment
451 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
455 let slice = match self.iter.peek() {
456 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
457 None => &self.slice[start_idx..],
459 Some((if kind.is_comment() {
460 CodeCharKind::Comment
472 /// Iterator over an alternating sequence of functional and commented parts of
473 /// a string. The first item is always a, possibly zero length, subslice of
474 /// functional text. Line style comments contain their ending newlines.
475 pub struct CommentCodeSlices<'a> {
477 last_slice_kind: CodeCharKind,
478 last_slice_end: usize,
481 impl<'a> CommentCodeSlices<'a> {
482 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
485 last_slice_kind: CodeCharKind::Comment,
491 impl<'a> Iterator for CommentCodeSlices<'a> {
492 type Item = (CodeCharKind, usize, &'a str);
494 fn next(&mut self) -> Option<Self::Item> {
495 if self.last_slice_end == self.slice.len() {
499 let mut sub_slice_end = self.last_slice_end;
500 let mut first_whitespace = None;
501 let subslice = &self.slice[self.last_slice_end..];
502 let mut iter = CharClasses::new(subslice.char_indices());
504 for (kind, (i, c)) in &mut iter {
505 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
506 &subslice[..2] == "//" &&
507 [' ', '\t'].contains(&c);
509 if is_comment_connector && first_whitespace.is_none() {
510 first_whitespace = Some(i);
513 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
514 let last_index = match first_whitespace {
518 sub_slice_end = self.last_slice_end + last_index;
522 if !is_comment_connector {
523 first_whitespace = None;
527 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
528 // This was the last subslice.
529 sub_slice_end = match first_whitespace {
530 Some(i) => self.last_slice_end + i,
531 None => self.slice.len(),
535 let kind = match self.last_slice_kind {
536 CodeCharKind::Comment => CodeCharKind::Normal,
537 CodeCharKind::Normal => CodeCharKind::Comment,
539 let res = (kind, self.last_slice_end, &self.slice[self.last_slice_end..sub_slice_end]);
540 self.last_slice_end = sub_slice_end;
541 self.last_slice_kind = kind;
547 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
548 /// (if it fits in the width/offset, else return None), else return `new`
549 pub fn recover_comment_removed(new: String,
551 context: &RewriteContext,
555 let snippet = context.snippet(span);
556 if changed_comment_content(&snippet, &new) {
557 // We missed some comments
558 // Keep previous formatting if it satisfies the constrains
559 wrap_str(snippet, context.config.max_width, width, offset)
565 /// Return true if the two strings of code have the same payload of comments.
566 /// The payload of comments is everything in the string except:
567 /// - actual code (not comments)
568 /// - comment start/end marks
570 /// - '*' at the beginning of lines in block comments
571 fn changed_comment_content(orig: &str, new: &str) -> bool {
572 // Cannot write this as a fn since we cannot return types containing closures
573 let code_comment_content = |code| {
574 let slices = UngroupedCommentCodeSlices::new(code);
575 slices.filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
576 .flat_map(|(_, _, s)| CommentReducer::new(s))
578 let res = code_comment_content(orig).ne(code_comment_content(new));
579 debug!("comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
583 code_comment_content(orig).collect::<String>(),
584 code_comment_content(new).collect::<String>());
589 /// Iterator over the 'payload' characters of a comment.
590 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
591 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
593 struct CommentReducer<'a> {
596 iter: std::str::Chars<'a>,
599 impl<'a> CommentReducer<'a> {
600 fn new(comment: &'a str) -> CommentReducer<'a> {
601 let is_block = comment.starts_with("/*");
602 let comment = remove_comment_header(comment);
605 at_start_line: false, // There are no supplementary '*' on the first line
606 iter: comment.chars(),
611 impl<'a> Iterator for CommentReducer<'a> {
613 fn next(&mut self) -> Option<Self::Item> {
615 let mut c = try_opt!(self.iter.next());
616 if self.is_block && self.at_start_line {
617 while c.is_whitespace() {
618 c = try_opt!(self.iter.next());
620 // Ignore leading '*'
622 c = try_opt!(self.iter.next());
626 self.at_start_line = true;
629 if !c.is_whitespace() {
637 fn remove_comment_header(comment: &str) -> &str {
638 if comment.starts_with("///") || comment.starts_with("//!") {
640 } else if comment.starts_with("//") {
642 } else if (comment.starts_with("/**") && !comment.starts_with("/**/")) ||
643 comment.starts_with("/*!") {
644 &comment[3..comment.len() - 2]
646 assert!(comment.starts_with("/*"),
647 format!("string '{}' is not a comment", comment));
648 &comment[2..comment.len() - 2]
654 use super::{CharClasses, CodeCharKind, FullCodeCharKind, contains_comment, rewrite_comment,
655 FindUncommented, CommentCodeSlices};
660 let mut iter = CharClasses::new("//\n\n".chars());
662 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
663 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
664 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
665 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
666 assert_eq!(None, iter.next());
670 fn comment_code_slices() {
671 let input = "code(); /* test */ 1 + 1";
672 let mut iter = CommentCodeSlices::new(input);
674 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
675 assert_eq!((CodeCharKind::Comment, 8, "/* test */"),
676 iter.next().unwrap());
677 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
678 assert_eq!(None, iter.next());
682 fn comment_code_slices_two() {
683 let input = "// comment\n test();";
684 let mut iter = CommentCodeSlices::new(input);
686 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
687 assert_eq!((CodeCharKind::Comment, 0, "// comment\n"),
688 iter.next().unwrap());
689 assert_eq!((CodeCharKind::Normal, 11, " test();"),
690 iter.next().unwrap());
691 assert_eq!(None, iter.next());
695 fn comment_code_slices_three() {
696 let input = "1 // comment\n // comment2\n\n";
697 let mut iter = CommentCodeSlices::new(input);
699 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
700 assert_eq!((CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
701 iter.next().unwrap());
702 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
703 assert_eq!(None, iter.next());
707 #[cfg_attr(rustfmt, rustfmt_skip)]
708 fn format_comments() {
709 let mut config: ::config::Config = Default::default();
710 config.wrap_comments = true;
712 let comment = rewrite_comment(" //test", true, 100, Indent::new(0, 100), &config).unwrap();
713 assert_eq!("/* test */", comment);
715 let comment = rewrite_comment("// comment on a",
720 assert_eq!("// comment\n// on a", comment);
722 let comment = rewrite_comment("// A multi line comment\n // between args.",
727 assert_eq!("// A multi line comment\n // between args.", comment);
729 let input = "// comment";
732 let comment = rewrite_comment(input, true, 9, Indent::new(0, 69), &config).unwrap();
733 assert_eq!(expected, comment);
735 let comment = rewrite_comment("/* trimmed */",
740 assert_eq!("/* trimmed */", comment);
743 // This is probably intended to be a non-test fn, but it is not used. I'm
744 // keeping it around unless it helps us test stuff.
745 fn uncommented(text: &str) -> String {
746 CharClasses::new(text.chars())
747 .filter_map(|(s, c)| match s {
748 FullCodeCharKind::Normal => Some(c),
755 fn test_uncommented() {
756 assert_eq!(&uncommented("abc/*...*/"), "abc");
757 assert_eq!(&uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
759 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
763 fn test_contains_comment() {
764 assert_eq!(contains_comment("abc"), false);
765 assert_eq!(contains_comment("abc // qsdf"), true);
766 assert_eq!(contains_comment("abc /* kqsdf"), true);
767 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
771 fn test_find_uncommented() {
772 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
773 assert_eq!(expected, haystack.find_uncommented(needle));
776 check("/*/ */test", "test", Some(6));
777 check("//test\ntest", "test", Some(7));
778 check("/* comment only */", "whatever", None);
779 check("/* comment */ some text /* more commentary */ result",
782 check("sup // sup", "p", Some(2));
783 check("sup", "x", None);
784 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
785 check("/*sup yo? \n sup*/ sup", "p", Some(20));
786 check("hel/*lohello*/lo", "hello", None);
787 check("acb", "ab", None);
788 check(",/*A*/ ", ",", Some(0));
789 check("abc", "abc", Some(0));
790 check("/* abc */", "abc", None);
791 check("/**/abc/* */", "abc", Some(4));
792 check("\"/* abc */\"", "abc", Some(4));
793 check("\"/* abc", "abc", Some(4));