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();
76 .map(|(i, mut line)| {
79 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
80 line = &line[..(line.len() - 2)];
85 .map(left_trim_comment_line)
87 if orig.starts_with("/*") && line_breaks == 0 {
94 let mut result = opener.to_owned();
102 result.push_str(&indent_str);
103 result.push_str(line_start);
106 if config.wrap_comments && line.len() > max_chars {
107 let rewrite = rewrite_string(line, &fmt).unwrap_or(line.to_owned());
108 result.push_str(&rewrite);
111 // Remove space if this is an empty comment or a doc comment.
114 result.push_str(line);
118 result.push_str(closer);
119 if result == opener {
127 fn left_trim_comment_line(line: &str) -> &str {
128 if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") ||
129 line.starts_with("/** ") {
131 } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!") ||
132 line.starts_with("///") ||
133 line.starts_with("** ") || line.starts_with("/*!") ||
134 (line.starts_with("/**") && !line.starts_with("/**/")) {
136 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") ||
137 line.starts_with("**") {
139 } else if line.starts_with('*') {
146 pub trait FindUncommented {
147 fn find_uncommented(&self, pat: &str) -> Option<usize>;
150 impl FindUncommented for str {
151 fn find_uncommented(&self, pat: &str) -> Option<usize> {
152 let mut needle_iter = pat.chars();
153 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
154 match needle_iter.next() {
156 return Some(i - pat.len());
160 FullCodeCharKind::Normal if b == c => {}
162 needle_iter = pat.chars();
169 // Handle case where the pattern is a suffix of the search string
170 match needle_iter.next() {
172 None => Some(self.len() - pat.len()),
177 // Returns the first byte position after the first comment. The given string
178 // is expected to be prefixed by a comment, including delimiters.
179 // Good: "/* /* inner */ outer */ code();"
180 // Bad: "code(); // hello\n world!"
181 pub fn find_comment_end(s: &str) -> Option<usize> {
182 let mut iter = CharClasses::new(s.char_indices());
183 for (kind, (i, _c)) in &mut iter {
184 if kind == FullCodeCharKind::Normal {
189 // Handle case where the comment ends at the end of s.
190 if iter.status == CharClassesStatus::Normal {
197 /// Returns true if text contains any comment.
198 pub fn contains_comment(text: &str) -> bool {
199 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
202 struct CharClasses<T>
206 base: iter::Peekable<T>,
207 status: CharClassesStatus,
211 fn get_char(&self) -> char;
214 impl RichChar for char {
215 fn get_char(&self) -> char {
220 impl RichChar for (usize, char) {
221 fn get_char(&self) -> char {
226 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
227 enum CharClassesStatus {
233 // The u32 is the nesting deepness of the comment
235 // Status when the '/' has been consumed, but not yet the '*', deepness is
236 // the new deepness (after the comment opening).
237 BlockCommentOpening(u32),
238 // Status when the '*' has been consumed, but not yet the '/', deepness is
239 // the new deepness (after the comment closing).
240 BlockCommentClosing(u32),
244 /// Distinguish between functionnal part of code and comments
245 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
246 pub enum CodeCharKind {
251 /// Distinguish between functionnal part of code and comments,
252 /// describing opening and closing of comments for ease when chunking
253 /// code from tagged characters
254 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
255 enum FullCodeCharKind {
257 /// The first character of a comment, there is only one for a comment (always '/')
259 /// Any character inside a comment including the second character of comment
260 /// marks ("//", "/*")
262 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
266 impl FullCodeCharKind {
267 fn is_comment(&self) -> bool {
269 FullCodeCharKind::Normal => false,
270 FullCodeCharKind::StartComment |
271 FullCodeCharKind::InComment |
272 FullCodeCharKind::EndComment => true,
276 fn to_codecharkind(&self) -> CodeCharKind {
277 if self.is_comment() {
278 CodeCharKind::Comment
285 impl<T> CharClasses<T>
289 fn new(base: T) -> CharClasses<T> {
291 base: base.peekable(),
292 status: CharClassesStatus::Normal,
297 impl<T> Iterator for CharClasses<T>
301 type Item = (FullCodeCharKind, T::Item);
303 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
304 let item = try_opt!(self.base.next());
305 let chr = item.get_char();
306 self.status = match self.status {
307 CharClassesStatus::LitString => {
309 '"' => CharClassesStatus::Normal,
310 '\\' => CharClassesStatus::LitStringEscape,
311 _ => CharClassesStatus::LitString,
314 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
315 CharClassesStatus::LitChar => {
317 '\\' => CharClassesStatus::LitCharEscape,
318 '\'' => CharClassesStatus::Normal,
319 _ => CharClassesStatus::LitChar,
322 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
323 CharClassesStatus::Normal => {
325 '"' => CharClassesStatus::LitString,
326 '\'' => CharClassesStatus::LitChar,
328 match self.base.peek() {
329 Some(next) if next.get_char() == '*' => {
330 self.status = CharClassesStatus::BlockCommentOpening(1);
331 return Some((FullCodeCharKind::StartComment, item));
333 Some(next) if next.get_char() == '/' => {
334 self.status = CharClassesStatus::LineComment;
335 return Some((FullCodeCharKind::StartComment, item));
337 _ => CharClassesStatus::Normal,
340 _ => CharClassesStatus::Normal,
343 CharClassesStatus::BlockComment(deepness) => {
344 assert!(deepness != 0);
345 self.status = match self.base.peek() {
346 Some(next) if next.get_char() == '/' && chr == '*' => {
347 CharClassesStatus::BlockCommentClosing(deepness - 1)
349 Some(next) if next.get_char() == '*' && chr == '/' => {
350 CharClassesStatus::BlockCommentOpening(deepness + 1)
352 _ => CharClassesStatus::BlockComment(deepness),
354 return Some((FullCodeCharKind::InComment, item));
356 CharClassesStatus::BlockCommentOpening(deepness) => {
357 assert_eq!(chr, '*');
358 self.status = CharClassesStatus::BlockComment(deepness);
359 return Some((FullCodeCharKind::InComment, item));
361 CharClassesStatus::BlockCommentClosing(deepness) => {
362 assert_eq!(chr, '/');
364 self.status = CharClassesStatus::Normal;
365 return Some((FullCodeCharKind::EndComment, item));
367 self.status = CharClassesStatus::BlockComment(deepness);
368 return Some((FullCodeCharKind::InComment, item));
371 CharClassesStatus::LineComment => {
374 self.status = CharClassesStatus::Normal;
375 return Some((FullCodeCharKind::EndComment, item));
378 self.status = CharClassesStatus::LineComment;
379 return Some((FullCodeCharKind::InComment, item));
384 Some((FullCodeCharKind::Normal, item))
388 /// Iterator over functional and commented parts of a string. Any part of a string is either
389 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
390 /// comments is functional code. Line comments contain their ending newlines.
391 struct UngroupedCommentCodeSlices<'a> {
393 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
396 impl<'a> UngroupedCommentCodeSlices<'a> {
397 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
398 UngroupedCommentCodeSlices {
400 iter: CharClasses::new(code.char_indices()).peekable(),
405 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
406 type Item = (CodeCharKind, usize, &'a str);
408 fn next(&mut self) -> Option<Self::Item> {
409 let (kind, (start_idx, _)) = try_opt!(self.iter.next());
411 FullCodeCharKind::Normal => {
412 // Consume all the Normal code
413 while let Some(&(FullCodeCharKind::Normal, (_, _))) = self.iter.peek() {
414 let _ = self.iter.next();
417 FullCodeCharKind::StartComment => {
418 // Consume the whole comment
419 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
423 let slice = match self.iter.peek() {
424 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
425 None => &self.slice[start_idx..],
427 Some((if kind.is_comment() {
428 CodeCharKind::Comment
440 /// Iterator over an alternating sequence of functional and commented parts of
441 /// a string. The first item is always a, possibly zero length, subslice of
442 /// functional text. Line style comments contain their ending newlines.
443 pub struct CommentCodeSlices<'a> {
445 last_slice_kind: CodeCharKind,
446 last_slice_end: usize,
449 impl<'a> CommentCodeSlices<'a> {
450 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
453 last_slice_kind: CodeCharKind::Comment,
459 impl<'a> Iterator for CommentCodeSlices<'a> {
460 type Item = (CodeCharKind, usize, &'a str);
462 fn next(&mut self) -> Option<Self::Item> {
463 if self.last_slice_end == self.slice.len() {
467 let mut sub_slice_end = self.last_slice_end;
468 let mut first_whitespace = None;
469 let subslice = &self.slice[self.last_slice_end..];
470 let mut iter = CharClasses::new(subslice.char_indices());
472 for (kind, (i, c)) in &mut iter {
473 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
474 &subslice[..2] == "//" &&
475 [' ', '\t'].contains(&c);
477 if is_comment_connector && first_whitespace.is_none() {
478 first_whitespace = Some(i);
481 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
482 let last_index = match first_whitespace {
486 sub_slice_end = self.last_slice_end + last_index;
490 if !is_comment_connector {
491 first_whitespace = None;
495 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
496 // This was the last subslice.
497 sub_slice_end = match first_whitespace {
498 Some(i) => self.last_slice_end + i,
499 None => self.slice.len(),
503 let kind = match self.last_slice_kind {
504 CodeCharKind::Comment => CodeCharKind::Normal,
505 CodeCharKind::Normal => CodeCharKind::Comment,
507 let res = (kind, self.last_slice_end, &self.slice[self.last_slice_end..sub_slice_end]);
508 self.last_slice_end = sub_slice_end;
509 self.last_slice_kind = kind;
515 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
516 /// (if it fits in the width/offset, else return None), else return `new`
517 pub fn recover_comment_removed(new: String,
519 context: &RewriteContext,
523 let snippet = context.snippet(span);
524 if changed_comment_content(&snippet, &new) {
525 // We missed some comments
526 // Keep previous formatting if it satisfies the constrains
527 wrap_str(snippet, context.config.max_width, width, offset)
533 /// Return true if the two strings of code have the same payload of comments.
534 /// The payload of comments is everything in the string except:
535 /// - actual code (not comments)
536 /// - comment start/end marks
538 /// - '*' at the beginning of lines in block comments
539 fn changed_comment_content(orig: &str, new: &str) -> bool {
540 // Cannot write this as a fn since we cannot return types containing closures
541 let code_comment_content = |code| {
542 let slices = UngroupedCommentCodeSlices::new(code);
543 slices.filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
544 .flat_map(|(_, _, s)| CommentReducer::new(s))
546 let res = code_comment_content(orig).ne(code_comment_content(new));
547 debug!("comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
551 code_comment_content(orig).collect::<String>(),
552 code_comment_content(new).collect::<String>());
557 /// Iterator over the 'payload' characters of a comment.
558 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
559 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
561 struct CommentReducer<'a> {
564 iter: std::str::Chars<'a>,
567 impl<'a> CommentReducer<'a> {
568 fn new(comment: &'a str) -> CommentReducer<'a> {
569 let is_block = comment.starts_with("/*");
570 let comment = remove_comment_header(comment);
573 at_start_line: false, // There are no supplementary '*' on the first line
574 iter: comment.chars(),
579 impl<'a> Iterator for CommentReducer<'a> {
581 fn next(&mut self) -> Option<Self::Item> {
583 let mut c = try_opt!(self.iter.next());
584 if self.is_block && self.at_start_line {
585 while c.is_whitespace() {
586 c = try_opt!(self.iter.next());
588 // Ignore leading '*'
590 c = try_opt!(self.iter.next());
594 self.at_start_line = true;
597 if !c.is_whitespace() {
605 fn remove_comment_header(comment: &str) -> &str {
606 if comment.starts_with("///") || comment.starts_with("//!") {
608 } else if comment.starts_with("//") {
610 } else if (comment.starts_with("/**") && !comment.starts_with("/**/")) ||
611 comment.starts_with("/*!") {
612 &comment[3..comment.len() - 2]
614 assert!(comment.starts_with("/*"),
615 format!("string '{}' is not a comment", comment));
616 &comment[2..comment.len() - 2]
622 use super::{CharClasses, CodeCharKind, FullCodeCharKind, contains_comment, rewrite_comment,
623 FindUncommented, CommentCodeSlices};
628 let mut iter = CharClasses::new("//\n\n".chars());
630 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
631 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
632 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
633 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
634 assert_eq!(None, iter.next());
638 fn comment_code_slices() {
639 let input = "code(); /* test */ 1 + 1";
640 let mut iter = CommentCodeSlices::new(input);
642 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
643 assert_eq!((CodeCharKind::Comment, 8, "/* test */"),
644 iter.next().unwrap());
645 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
646 assert_eq!(None, iter.next());
650 fn comment_code_slices_two() {
651 let input = "// comment\n test();";
652 let mut iter = CommentCodeSlices::new(input);
654 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
655 assert_eq!((CodeCharKind::Comment, 0, "// comment\n"),
656 iter.next().unwrap());
657 assert_eq!((CodeCharKind::Normal, 11, " test();"),
658 iter.next().unwrap());
659 assert_eq!(None, iter.next());
663 fn comment_code_slices_three() {
664 let input = "1 // comment\n // comment2\n\n";
665 let mut iter = CommentCodeSlices::new(input);
667 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
668 assert_eq!((CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
669 iter.next().unwrap());
670 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
671 assert_eq!(None, iter.next());
675 #[cfg_attr(rustfmt, rustfmt_skip)]
676 fn format_comments() {
677 let mut config: ::config::Config = Default::default();
678 config.wrap_comments = true;
680 let comment = rewrite_comment(" //test", true, 100, Indent::new(0, 100), &config).unwrap();
681 assert_eq!("/* test */", comment);
683 let comment = rewrite_comment("// comment on a",
688 assert_eq!("// comment\n// on a", comment);
690 let comment = rewrite_comment("// A multi line comment\n // between args.",
695 assert_eq!("// A multi line comment\n // between args.", comment);
697 let input = "// comment";
700 let comment = rewrite_comment(input, true, 9, Indent::new(0, 69), &config).unwrap();
701 assert_eq!(expected, comment);
703 let comment = rewrite_comment("/* trimmed */",
708 assert_eq!("/* trimmed */", comment);
711 // This is probably intended to be a non-test fn, but it is not used. I'm
712 // keeping it around unless it helps us test stuff.
713 fn uncommented(text: &str) -> String {
714 CharClasses::new(text.chars())
715 .filter_map(|(s, c)| {
717 FullCodeCharKind::Normal => Some(c),
725 fn test_uncommented() {
726 assert_eq!(&uncommented("abc/*...*/"), "abc");
727 assert_eq!(&uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
729 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
733 fn test_contains_comment() {
734 assert_eq!(contains_comment("abc"), false);
735 assert_eq!(contains_comment("abc // qsdf"), true);
736 assert_eq!(contains_comment("abc /* kqsdf"), true);
737 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
741 fn test_find_uncommented() {
742 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
743 assert_eq!(expected, haystack.find_uncommented(needle));
746 check("/*/ */test", "test", Some(6));
747 check("//test\ntest", "test", Some(7));
748 check("/* comment only */", "whatever", None);
749 check("/* comment */ some text /* more commentary */ result",
752 check("sup // sup", "p", Some(2));
753 check("sup", "x", None);
754 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
755 check("/*sup yo? \n sup*/ sup", "p", Some(20));
756 check("hel/*lohello*/lo", "hello", None);
757 check("acb", "ab", None);
758 check(",/*A*/ ", ",", Some(0));
759 check("abc", "abc", Some(0));
760 check("/* abc */", "abc", None);
761 check("/**/abc/* */", "abc", Some(4));
762 check("\"/* abc */\"", "abc", Some(4));
763 check("\"/* abc", "abc", Some(4));