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) = if block_style {
57 } else if !config.normalize_comments {
58 if orig.starts_with("/**") && !orig.starts_with("/**/") {
59 ("/** ", " **/", " ** ")
60 } else if orig.starts_with("/*!") {
61 ("/*! ", " */", " * ")
62 } else if orig.starts_with("/*") {
64 } else if orig.starts_with("///") {
66 } else if orig.starts_with("//!") {
71 } else if orig.starts_with("///") || (orig.starts_with("/**") && !orig.starts_with("/**/")) {
73 } else if orig.starts_with("//!") || orig.starts_with("/*!") {
75 } else if is_custom_comment(orig) {
76 if orig.chars().nth(3) == Some(' ') {
77 (&orig[0..4], "", &orig[0..4])
79 (&orig[0..3], "", &orig[0..3])
87 .checked_sub(closer.len() + opener.len())
89 let indent_str = shape.indent.to_string(config);
90 let fmt = StringFormat {
93 line_start: line_start,
95 shape: Shape::legacy(max_chars, shape.indent + (opener.len() - line_start.len())),
100 let line_breaks = orig.trim_right().chars().filter(|&c| c == '\n').count();
101 let lines = orig.lines()
103 .map(|(i, mut line)| {
106 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
107 line = &line[..(line.len() - 2)].trim_right();
112 .map(left_trim_comment_line)
113 .map(|line| if orig.starts_with("/*") && line_breaks == 0 {
119 let mut result = opener.to_owned();
121 if result == opener {
127 result.push_str(&indent_str);
128 result.push_str(line_start);
131 if config.wrap_comments && line.len() > max_chars {
132 let rewrite = rewrite_string(line, &fmt).unwrap_or(line.to_owned());
133 result.push_str(&rewrite);
136 // Remove space if this is an empty comment or a doc comment.
139 result.push_str(line);
143 result.push_str(closer);
144 if result == opener {
152 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
153 fn light_rewrite_comment(orig: &str, offset: Indent, config: &Config) -> Option<String> {
154 let lines: Vec<&str> = orig.lines()
156 // This is basically just l.trim(), but in the case that a line starts
157 // with `*` we want to leave one space before it, so it aligns with the
159 let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
160 if let Some(fnw) = first_non_whitespace {
161 if l.as_bytes()[fnw] == '*' as u8 && fnw > 0 {
172 Some(lines.join(&format!("\n{}", offset.to_string(config))))
175 /// Trims comment characters and possibly a single space from the left of a string.
176 /// Does not trim all whitespace.
177 fn left_trim_comment_line(line: &str) -> &str {
178 if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") ||
179 line.starts_with("/** ") {
181 } else if is_custom_comment(line) {
182 if line.len() > 3 && line.chars().nth(3) == Some(' ') {
187 } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!") ||
188 line.starts_with("///") ||
189 line.starts_with("** ") || line.starts_with("/*!") ||
190 (line.starts_with("/**") && !line.starts_with("/**/")) {
192 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") ||
193 line.starts_with("**") {
195 } else if line.starts_with('*') {
202 pub trait FindUncommented {
203 fn find_uncommented(&self, pat: &str) -> Option<usize>;
206 impl FindUncommented for str {
207 fn find_uncommented(&self, pat: &str) -> Option<usize> {
208 let mut needle_iter = pat.chars();
209 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
210 match needle_iter.next() {
212 return Some(i - pat.len());
216 FullCodeCharKind::Normal if b == c => {}
218 needle_iter = pat.chars();
225 // Handle case where the pattern is a suffix of the search string
226 match needle_iter.next() {
228 None => Some(self.len() - pat.len()),
233 // Returns the first byte position after the first comment. The given string
234 // is expected to be prefixed by a comment, including delimiters.
235 // Good: "/* /* inner */ outer */ code();"
236 // Bad: "code(); // hello\n world!"
237 pub fn find_comment_end(s: &str) -> Option<usize> {
238 let mut iter = CharClasses::new(s.char_indices());
239 for (kind, (i, _c)) in &mut iter {
240 if kind == FullCodeCharKind::Normal {
245 // Handle case where the comment ends at the end of s.
246 if iter.status == CharClassesStatus::Normal {
253 /// Returns true if text contains any comment.
254 pub fn contains_comment(text: &str) -> bool {
255 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
258 struct CharClasses<T>
262 base: iter::Peekable<T>,
263 status: CharClassesStatus,
267 fn get_char(&self) -> char;
270 impl RichChar for char {
271 fn get_char(&self) -> char {
276 impl RichChar for (usize, char) {
277 fn get_char(&self) -> char {
282 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
283 enum CharClassesStatus {
289 // The u32 is the nesting deepness of the comment
291 // Status when the '/' has been consumed, but not yet the '*', deepness is
292 // the new deepness (after the comment opening).
293 BlockCommentOpening(u32),
294 // Status when the '*' has been consumed, but not yet the '/', deepness is
295 // the new deepness (after the comment closing).
296 BlockCommentClosing(u32),
300 /// Distinguish between functional part of code and comments
301 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
302 pub enum CodeCharKind {
307 /// Distinguish between functional part of code and comments,
308 /// describing opening and closing of comments for ease when chunking
309 /// code from tagged characters
310 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
311 enum FullCodeCharKind {
313 /// The first character of a comment, there is only one for a comment (always '/')
315 /// Any character inside a comment including the second character of comment
316 /// marks ("//", "/*")
318 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
322 impl FullCodeCharKind {
323 fn is_comment(&self) -> bool {
325 FullCodeCharKind::Normal => false,
326 FullCodeCharKind::StartComment |
327 FullCodeCharKind::InComment |
328 FullCodeCharKind::EndComment => true,
332 fn to_codecharkind(&self) -> CodeCharKind {
333 if self.is_comment() {
334 CodeCharKind::Comment
341 impl<T> CharClasses<T>
345 fn new(base: T) -> CharClasses<T> {
347 base: base.peekable(),
348 status: CharClassesStatus::Normal,
353 impl<T> Iterator for CharClasses<T>
357 type Item = (FullCodeCharKind, T::Item);
359 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
360 let item = try_opt!(self.base.next());
361 let chr = item.get_char();
362 self.status = match self.status {
363 CharClassesStatus::LitString => {
365 '"' => CharClassesStatus::Normal,
366 '\\' => CharClassesStatus::LitStringEscape,
367 _ => CharClassesStatus::LitString,
370 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
371 CharClassesStatus::LitChar => {
373 '\\' => CharClassesStatus::LitCharEscape,
374 '\'' => CharClassesStatus::Normal,
375 _ => CharClassesStatus::LitChar,
378 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
379 CharClassesStatus::Normal => {
381 '"' => CharClassesStatus::LitString,
382 '\'' => CharClassesStatus::LitChar,
384 match self.base.peek() {
385 Some(next) if next.get_char() == '*' => {
386 self.status = CharClassesStatus::BlockCommentOpening(1);
387 return Some((FullCodeCharKind::StartComment, item));
389 Some(next) if next.get_char() == '/' => {
390 self.status = CharClassesStatus::LineComment;
391 return Some((FullCodeCharKind::StartComment, item));
393 _ => CharClassesStatus::Normal,
396 _ => CharClassesStatus::Normal,
399 CharClassesStatus::BlockComment(deepness) => {
400 assert!(deepness != 0);
401 self.status = match self.base.peek() {
402 Some(next) if next.get_char() == '/' && chr == '*' => {
403 CharClassesStatus::BlockCommentClosing(deepness - 1)
405 Some(next) if next.get_char() == '*' && chr == '/' => {
406 CharClassesStatus::BlockCommentOpening(deepness + 1)
408 _ => CharClassesStatus::BlockComment(deepness),
410 return Some((FullCodeCharKind::InComment, item));
412 CharClassesStatus::BlockCommentOpening(deepness) => {
413 assert_eq!(chr, '*');
414 self.status = CharClassesStatus::BlockComment(deepness);
415 return Some((FullCodeCharKind::InComment, item));
417 CharClassesStatus::BlockCommentClosing(deepness) => {
418 assert_eq!(chr, '/');
420 self.status = CharClassesStatus::Normal;
421 return Some((FullCodeCharKind::EndComment, item));
423 self.status = CharClassesStatus::BlockComment(deepness);
424 return Some((FullCodeCharKind::InComment, item));
427 CharClassesStatus::LineComment => {
430 self.status = CharClassesStatus::Normal;
431 return Some((FullCodeCharKind::EndComment, item));
434 self.status = CharClassesStatus::LineComment;
435 return Some((FullCodeCharKind::InComment, item));
440 Some((FullCodeCharKind::Normal, item))
444 /// Iterator over functional and commented parts of a string. Any part of a string is either
445 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
446 /// comments is functional code. Line comments contain their ending newlines.
447 struct UngroupedCommentCodeSlices<'a> {
449 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
452 impl<'a> UngroupedCommentCodeSlices<'a> {
453 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
454 UngroupedCommentCodeSlices {
456 iter: CharClasses::new(code.char_indices()).peekable(),
461 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
462 type Item = (CodeCharKind, usize, &'a str);
464 fn next(&mut self) -> Option<Self::Item> {
465 let (kind, (start_idx, _)) = try_opt!(self.iter.next());
467 FullCodeCharKind::Normal => {
468 // Consume all the Normal code
469 while let Some(&(FullCodeCharKind::Normal, (_, _))) = self.iter.peek() {
470 let _ = self.iter.next();
473 FullCodeCharKind::StartComment => {
474 // Consume the whole comment
475 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
479 let slice = match self.iter.peek() {
480 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
481 None => &self.slice[start_idx..],
483 Some((if kind.is_comment() {
484 CodeCharKind::Comment
496 /// Iterator over an alternating sequence of functional and commented parts of
497 /// a string. The first item is always a, possibly zero length, subslice of
498 /// functional text. Line style comments contain their ending newlines.
499 pub struct CommentCodeSlices<'a> {
501 last_slice_kind: CodeCharKind,
502 last_slice_end: usize,
505 impl<'a> CommentCodeSlices<'a> {
506 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
509 last_slice_kind: CodeCharKind::Comment,
515 impl<'a> Iterator for CommentCodeSlices<'a> {
516 type Item = (CodeCharKind, usize, &'a str);
518 fn next(&mut self) -> Option<Self::Item> {
519 if self.last_slice_end == self.slice.len() {
523 let mut sub_slice_end = self.last_slice_end;
524 let mut first_whitespace = None;
525 let subslice = &self.slice[self.last_slice_end..];
526 let mut iter = CharClasses::new(subslice.char_indices());
528 for (kind, (i, c)) in &mut iter {
529 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
530 &subslice[..2] == "//" &&
531 [' ', '\t'].contains(&c);
533 if is_comment_connector && first_whitespace.is_none() {
534 first_whitespace = Some(i);
537 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
538 let last_index = match first_whitespace {
542 sub_slice_end = self.last_slice_end + last_index;
546 if !is_comment_connector {
547 first_whitespace = None;
551 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
552 // This was the last subslice.
553 sub_slice_end = match first_whitespace {
554 Some(i) => self.last_slice_end + i,
555 None => self.slice.len(),
559 let kind = match self.last_slice_kind {
560 CodeCharKind::Comment => CodeCharKind::Normal,
561 CodeCharKind::Normal => CodeCharKind::Comment,
563 let res = (kind, self.last_slice_end, &self.slice[self.last_slice_end..sub_slice_end]);
564 self.last_slice_end = sub_slice_end;
565 self.last_slice_kind = kind;
571 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
572 /// (if it fits in the width/offset, else return None), else return `new`
573 pub fn recover_comment_removed(new: String,
575 context: &RewriteContext,
578 let snippet = context.snippet(span);
579 if changed_comment_content(&snippet, &new) {
580 // We missed some comments
581 // Keep previous formatting if it satisfies the constrains
582 wrap_str(snippet, context.config.max_width, shape)
588 /// Return true if the two strings of code have the same payload of comments.
589 /// The payload of comments is everything in the string except:
590 /// - actual code (not comments)
591 /// - comment start/end marks
593 /// - '*' at the beginning of lines in block comments
594 fn changed_comment_content(orig: &str, new: &str) -> bool {
595 // Cannot write this as a fn since we cannot return types containing closures
596 let code_comment_content = |code| {
597 let slices = UngroupedCommentCodeSlices::new(code);
599 .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
600 .flat_map(|(_, _, s)| CommentReducer::new(s))
602 let res = code_comment_content(orig).ne(code_comment_content(new));
603 debug!("comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
607 code_comment_content(orig).collect::<String>(),
608 code_comment_content(new).collect::<String>());
613 /// Iterator over the 'payload' characters of a comment.
614 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
615 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
617 struct CommentReducer<'a> {
620 iter: std::str::Chars<'a>,
623 impl<'a> CommentReducer<'a> {
624 fn new(comment: &'a str) -> CommentReducer<'a> {
625 let is_block = comment.starts_with("/*");
626 let comment = remove_comment_header(comment);
629 at_start_line: false, // There are no supplementary '*' on the first line
630 iter: comment.chars(),
635 impl<'a> Iterator for CommentReducer<'a> {
637 fn next(&mut self) -> Option<Self::Item> {
639 let mut c = try_opt!(self.iter.next());
640 if self.is_block && self.at_start_line {
641 while c.is_whitespace() {
642 c = try_opt!(self.iter.next());
644 // Ignore leading '*'
646 c = try_opt!(self.iter.next());
650 self.at_start_line = true;
653 if !c.is_whitespace() {
661 fn remove_comment_header(comment: &str) -> &str {
662 if comment.starts_with("///") || comment.starts_with("//!") {
664 } else if comment.starts_with("//") {
666 } else if (comment.starts_with("/**") && !comment.starts_with("/**/")) ||
667 comment.starts_with("/*!") {
668 &comment[3..comment.len() - 2]
670 assert!(comment.starts_with("/*"),
671 format!("string '{}' is not a comment", comment));
672 &comment[2..comment.len() - 2]
678 use super::{CharClasses, CodeCharKind, FullCodeCharKind, contains_comment, rewrite_comment,
679 FindUncommented, CommentCodeSlices};
684 let mut iter = CharClasses::new("//\n\n".chars());
686 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
687 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
688 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
689 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
690 assert_eq!(None, iter.next());
694 fn comment_code_slices() {
695 let input = "code(); /* test */ 1 + 1";
696 let mut iter = CommentCodeSlices::new(input);
698 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
699 assert_eq!((CodeCharKind::Comment, 8, "/* test */"),
700 iter.next().unwrap());
701 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
702 assert_eq!(None, iter.next());
706 fn comment_code_slices_two() {
707 let input = "// comment\n test();";
708 let mut iter = CommentCodeSlices::new(input);
710 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
711 assert_eq!((CodeCharKind::Comment, 0, "// comment\n"),
712 iter.next().unwrap());
713 assert_eq!((CodeCharKind::Normal, 11, " test();"),
714 iter.next().unwrap());
715 assert_eq!(None, iter.next());
719 fn comment_code_slices_three() {
720 let input = "1 // comment\n // comment2\n\n";
721 let mut iter = CommentCodeSlices::new(input);
723 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
724 assert_eq!((CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
725 iter.next().unwrap());
726 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
727 assert_eq!(None, iter.next());
731 #[cfg_attr(rustfmt, rustfmt_skip)]
732 fn format_comments() {
733 let mut config: ::config::Config = Default::default();
734 config.wrap_comments = true;
735 config.normalize_comments = true;
737 let comment = rewrite_comment(" //test",
739 Shape::legacy(100, Indent::new(0, 100)),
741 assert_eq!("/* test */", comment);
743 let comment = rewrite_comment("// comment on a",
745 Shape::legacy(10, Indent::empty()),
747 assert_eq!("// comment\n// on a", comment);
749 let comment = rewrite_comment("// A multi line comment\n // between args.",
751 Shape::legacy(60, Indent::new(0, 12)),
753 assert_eq!("// A multi line comment\n // between args.", comment);
755 let input = "// comment";
758 let comment = rewrite_comment(input,
760 Shape::legacy(9, Indent::new(0, 69)),
762 assert_eq!(expected, comment);
764 let comment = rewrite_comment("/* trimmed */",
766 Shape::legacy(100, Indent::new(0, 100)),
768 assert_eq!("/* trimmed */", comment);
771 // This is probably intended to be a non-test fn, but it is not used. I'm
772 // keeping it around unless it helps us test stuff.
773 fn uncommented(text: &str) -> String {
774 CharClasses::new(text.chars())
775 .filter_map(|(s, c)| match s {
776 FullCodeCharKind::Normal => Some(c),
783 fn test_uncommented() {
784 assert_eq!(&uncommented("abc/*...*/"), "abc");
785 assert_eq!(&uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
787 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
791 fn test_contains_comment() {
792 assert_eq!(contains_comment("abc"), false);
793 assert_eq!(contains_comment("abc // qsdf"), true);
794 assert_eq!(contains_comment("abc /* kqsdf"), true);
795 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
799 fn test_find_uncommented() {
800 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
801 assert_eq!(expected, haystack.find_uncommented(needle));
804 check("/*/ */test", "test", Some(6));
805 check("//test\ntest", "test", Some(7));
806 check("/* comment only */", "whatever", None);
807 check("/* comment */ some text /* more commentary */ result",
810 check("sup // sup", "p", Some(2));
811 check("sup", "x", None);
812 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
813 check("/*sup yo? \n sup*/ sup", "p", Some(20));
814 check("hel/*lohello*/lo", "hello", None);
815 check("acb", "ab", None);
816 check(",/*A*/ ", ",", Some(0));
817 check("abc", "abc", Some(0));
818 check("/* abc */", "abc", None);
819 check("/**/abc/* */", "abc", Some(4));
820 check("\"/* abc */\"", "abc", Some(4));
821 check("\"/* abc", "abc", Some(4));