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, borrow::Cow, iter};
15 use itertools::{multipeek, MultiPeek};
16 use syntax::codemap::Span;
19 use rewrite::RewriteContext;
20 use shape::{Indent, Shape};
21 use string::{rewrite_string, StringFormat};
22 use utils::{count_newlines, first_line_width, last_line_width};
24 fn is_custom_comment(comment: &str) -> bool {
25 if !comment.starts_with("//") {
27 } else if let Some(c) = comment.chars().nth(2) {
28 !c.is_alphanumeric() && !c.is_whitespace()
34 #[derive(Copy, Clone, PartialEq, Eq)]
35 pub enum CommentStyle<'a> {
45 fn custom_opener(s: &str) -> &str {
46 s.lines().next().map_or("", |first_line| {
49 .map_or(first_line, |space_index| &first_line[0..space_index + 1])
53 impl<'a> CommentStyle<'a> {
54 pub fn is_doc_comment(&self) -> bool {
56 CommentStyle::TripleSlash | CommentStyle::Doc => true,
61 pub fn opener(&self) -> &'a str {
63 CommentStyle::DoubleSlash => "// ",
64 CommentStyle::TripleSlash => "/// ",
65 CommentStyle::Doc => "//! ",
66 CommentStyle::SingleBullet => "/* ",
67 CommentStyle::DoubleBullet => "/** ",
68 CommentStyle::Exclamation => "/*! ",
69 CommentStyle::Custom(opener) => opener,
73 pub fn closer(&self) -> &'a str {
75 CommentStyle::DoubleSlash
76 | CommentStyle::TripleSlash
77 | CommentStyle::Custom(..)
78 | CommentStyle::Doc => "",
79 CommentStyle::DoubleBullet => " **/",
80 CommentStyle::SingleBullet | CommentStyle::Exclamation => " */",
84 pub fn line_start(&self) -> &'a str {
86 CommentStyle::DoubleSlash => "// ",
87 CommentStyle::TripleSlash => "/// ",
88 CommentStyle::Doc => "//! ",
89 CommentStyle::SingleBullet | CommentStyle::Exclamation => " * ",
90 CommentStyle::DoubleBullet => " ** ",
91 CommentStyle::Custom(opener) => opener,
95 pub fn to_str_tuplet(&self) -> (&'a str, &'a str, &'a str) {
96 (self.opener(), self.closer(), self.line_start())
99 pub fn line_with_same_comment_style(&self, line: &str, normalize_comments: bool) -> bool {
101 CommentStyle::DoubleSlash | CommentStyle::TripleSlash | CommentStyle::Doc => {
102 line.trim_left().starts_with(self.line_start().trim_left())
103 || comment_style(line, normalize_comments) == *self
105 CommentStyle::DoubleBullet | CommentStyle::SingleBullet | CommentStyle::Exclamation => {
106 line.trim_left().starts_with(self.closer().trim_left())
107 || line.trim_left().starts_with(self.line_start().trim_left())
108 || comment_style(line, normalize_comments) == *self
110 CommentStyle::Custom(opener) => line.trim_left().starts_with(opener.trim_right()),
115 fn comment_style(orig: &str, normalize_comments: bool) -> CommentStyle {
116 if !normalize_comments {
117 if orig.starts_with("/**") && !orig.starts_with("/**/") {
118 CommentStyle::DoubleBullet
119 } else if orig.starts_with("/*!") {
120 CommentStyle::Exclamation
121 } else if orig.starts_with("/*") {
122 CommentStyle::SingleBullet
123 } else if orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/') {
124 CommentStyle::TripleSlash
125 } else if orig.starts_with("//!") {
127 } else if is_custom_comment(orig) {
128 CommentStyle::Custom(custom_opener(orig))
130 CommentStyle::DoubleSlash
132 } else if (orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/'))
133 || (orig.starts_with("/**") && !orig.starts_with("/**/"))
135 CommentStyle::TripleSlash
136 } else if orig.starts_with("//!") || orig.starts_with("/*!") {
138 } else if is_custom_comment(orig) {
139 CommentStyle::Custom(custom_opener(orig))
141 CommentStyle::DoubleSlash
145 /// Combine `prev_str` and `next_str` into a single `String`. `span` may contain
146 /// comments between two strings. If there are such comments, then that will be
147 /// recovered. If `allow_extend` is true and there is no comment between the two
148 /// strings, then they will be put on a single line as long as doing so does not
149 /// exceed max width.
150 pub fn combine_strs_with_missing_comments(
151 context: &RewriteContext,
157 ) -> Option<String> {
159 String::with_capacity(prev_str.len() + next_str.len() + shape.indent.width() + 128);
160 result.push_str(prev_str);
161 let mut allow_one_line = !prev_str.contains('\n') && !next_str.contains('\n');
162 let first_sep = if prev_str.is_empty() || next_str.is_empty() {
167 let mut one_line_width =
168 last_line_width(prev_str) + first_line_width(next_str) + first_sep.len();
170 let config = context.config;
171 let indent = shape.indent;
172 let missing_comment = rewrite_missing_comment(span, shape, context)?;
174 if missing_comment.is_empty() {
175 if allow_extend && prev_str.len() + first_sep.len() + next_str.len() <= shape.width {
176 result.push_str(first_sep);
177 } else if !prev_str.is_empty() {
178 result.push_str(&indent.to_string_with_newline(config))
180 result.push_str(next_str);
184 // We have a missing comment between the first expression and the second expression.
186 // Peek the the original source code and find out whether there is a newline between the first
187 // expression and the second expression or the missing comment. We will preserve the original
188 // layout whenever possible.
189 let original_snippet = context.snippet(span);
190 let prefer_same_line = if let Some(pos) = original_snippet.find('/') {
191 !original_snippet[..pos].contains('\n')
193 !original_snippet.contains('\n')
196 one_line_width -= first_sep.len();
197 let first_sep = if prev_str.is_empty() || missing_comment.is_empty() {
200 let one_line_width = last_line_width(prev_str) + first_line_width(&missing_comment) + 1;
201 if prefer_same_line && one_line_width <= shape.width {
204 indent.to_string_with_newline(config)
207 result.push_str(&first_sep);
208 result.push_str(&missing_comment);
210 let second_sep = if missing_comment.is_empty() || next_str.is_empty() {
212 } else if missing_comment.starts_with("//") {
213 indent.to_string_with_newline(config)
215 one_line_width += missing_comment.len() + first_sep.len() + 1;
216 allow_one_line &= !missing_comment.starts_with("//") && !missing_comment.contains('\n');
217 if prefer_same_line && allow_one_line && one_line_width <= shape.width {
220 indent.to_string_with_newline(config)
223 result.push_str(&second_sep);
224 result.push_str(next_str);
229 pub fn rewrite_doc_comment(orig: &str, shape: Shape, config: &Config) -> Option<String> {
230 _rewrite_comment(orig, false, shape, config, true)
233 pub fn rewrite_comment(
238 ) -> Option<String> {
239 _rewrite_comment(orig, block_style, shape, config, false)
247 is_doc_comment: bool,
248 ) -> Option<String> {
249 // If there are lines without a starting sigil, we won't format them correctly
250 // so in that case we won't even re-align (if !config.normalize_comments()) and
251 // we should stop now.
252 let num_bare_lines = orig
254 .map(|line| line.trim())
255 .filter(|l| !(l.starts_with('*') || l.starts_with("//") || l.starts_with("/*")))
257 if num_bare_lines > 0 && !config.normalize_comments() {
258 return Some(orig.to_owned());
260 if !config.normalize_comments() && !config.wrap_comments() {
261 return light_rewrite_comment(orig, shape.indent, config, is_doc_comment);
264 identify_comment(orig, block_style, shape, config, is_doc_comment)
272 is_doc_comment: bool,
273 ) -> Option<String> {
274 let style = comment_style(orig, false);
275 let first_group = orig
277 .take_while(|l| style.line_with_same_comment_style(l, false))
282 .skip(first_group.lines().count())
286 let first_group_str = rewrite_comment_inner(
292 is_doc_comment || style.is_doc_comment(),
295 Some(first_group_str)
297 identify_comment(&rest, block_style, shape, config, is_doc_comment).map(|rest_str| {
301 shape.indent.to_string(config),
308 fn rewrite_comment_inner(
314 is_doc_comment: bool,
315 ) -> Option<String> {
316 let (opener, closer, line_start) = if block_style {
317 CommentStyle::SingleBullet.to_str_tuplet()
319 comment_style(orig, config.normalize_comments()).to_str_tuplet()
322 let max_chars = shape
324 .checked_sub(closer.len() + opener.len())
326 let indent_str = shape.indent.to_string_with_newline(config);
327 let fmt_indent = shape.indent + (opener.len() - line_start.len());
328 let mut fmt = StringFormat {
333 shape: Shape::legacy(max_chars, fmt_indent),
338 let line_breaks = count_newlines(orig.trim_right());
342 .map(|(i, mut line)| {
343 line = trim_right_unless_two_whitespaces(line.trim_left(), is_doc_comment);
345 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
346 line = line[..(line.len() - 2)].trim_right();
351 .map(|s| left_trim_comment_line(s, &style))
352 .map(|(line, has_leading_whitespace)| {
353 if orig.starts_with("/*") && line_breaks == 0 {
356 has_leading_whitespace || config.normalize_comments(),
359 (line, has_leading_whitespace || config.normalize_comments())
363 let mut result = String::with_capacity(orig.len() * 2);
364 result.push_str(opener);
365 let mut code_block_buffer = String::with_capacity(128);
366 let mut is_prev_line_multi_line = false;
367 let mut inside_code_block = false;
368 let comment_line_separator = format!("{}{}", indent_str, line_start);
369 let join_code_block_with_comment_line_separator = |s: &str| {
370 let mut result = String::with_capacity(s.len() + 128);
371 let mut iter = s.lines().peekable();
372 while let Some(line) = iter.next() {
373 result.push_str(line);
374 result.push_str(match iter.peek() {
375 Some(next_line) if next_line.is_empty() => comment_line_separator.trim_right(),
376 Some(..) => &comment_line_separator,
383 for (i, (line, has_leading_whitespace)) in lines.enumerate() {
384 let is_last = i == count_newlines(orig);
386 if inside_code_block {
387 if line.starts_with("```") {
388 inside_code_block = false;
389 result.push_str(&comment_line_separator);
391 let mut config = config.clone();
392 config.set().wrap_comments(false);
393 ::format_code_block(&code_block_buffer, &config)
394 .map_or_else(|| code_block_buffer.to_owned(), trim_custom_comment_prefix)
396 result.push_str(&join_code_block_with_comment_line_separator(&code_block));
397 code_block_buffer.clear();
398 result.push_str(&comment_line_separator);
399 result.push_str(line);
401 code_block_buffer.push_str(&hide_sharp_behind_comment(line));
402 code_block_buffer.push('\n');
405 // There is an code block that is not properly enclosed by backticks.
406 // We will leave them untouched.
407 result.push_str(&comment_line_separator);
408 result.push_str(&join_code_block_with_comment_line_separator(
409 &trim_custom_comment_prefix(&code_block_buffer),
416 inside_code_block = line.starts_with("```");
418 if result == opener {
419 let force_leading_whitespace = opener == "/* " && count_newlines(orig) == 0;
420 if !has_leading_whitespace && !force_leading_whitespace && result.ends_with(' ') {
426 } else if is_prev_line_multi_line && !line.is_empty() {
428 } else if is_last && !closer.is_empty() && line.is_empty() {
429 result.push_str(&indent_str);
431 result.push_str(&comment_line_separator);
432 if !has_leading_whitespace && result.ends_with(' ') {
438 if config.wrap_comments() && line.len() > fmt.shape.width && !has_url(line) {
439 match rewrite_string(line, &fmt, Some(max_chars)) {
441 is_prev_line_multi_line = s.contains('\n');
444 None if is_prev_line_multi_line => {
445 // We failed to put the current `line` next to the previous `line`.
446 // Remove the trailing space, then start rewrite on the next line.
448 result.push_str(&comment_line_separator);
449 fmt.shape = Shape::legacy(max_chars, fmt_indent);
450 match rewrite_string(line, &fmt, Some(max_chars)) {
452 is_prev_line_multi_line = s.contains('\n');
456 is_prev_line_multi_line = false;
457 result.push_str(line);
462 is_prev_line_multi_line = false;
463 result.push_str(line);
467 fmt.shape = if is_prev_line_multi_line {
469 let offset = 1 + last_line_width(&result) - line_start.len();
471 width: max_chars.saturating_sub(offset),
473 offset: fmt.shape.offset + offset,
476 Shape::legacy(max_chars, fmt_indent)
479 if line.is_empty() && result.ends_with(' ') && !is_last {
480 // Remove space if this is an empty comment or a doc comment.
483 result.push_str(line);
484 fmt.shape = Shape::legacy(max_chars, fmt_indent);
485 is_prev_line_multi_line = false;
489 result.push_str(closer);
490 if result.ends_with(opener) && opener.ends_with(' ') {
498 const RUSTFMT_CUSTOM_COMMENT_PREFIX: &str = "//#### ";
500 fn hide_sharp_behind_comment<'a>(s: &'a str) -> Cow<'a, str> {
501 if s.trim_left().starts_with('#') {
502 Cow::from(format!("{}{}", RUSTFMT_CUSTOM_COMMENT_PREFIX, s))
508 fn trim_custom_comment_prefix(s: String) -> String {
510 .map(|line| line.trim_left_matches(RUSTFMT_CUSTOM_COMMENT_PREFIX))
515 /// Returns true if the given string MAY include URLs or alike.
516 fn has_url(s: &str) -> bool {
517 // This function may return false positive, but should get its job done in most cases.
518 s.contains("https://") || s.contains("http://") || s.contains("ftp://") || s.contains("file://")
521 /// Given the span, rewrite the missing comment inside it if available.
522 /// Note that the given span must only include comments (or leading/trailing whitespaces).
523 pub fn rewrite_missing_comment(
526 context: &RewriteContext,
527 ) -> Option<String> {
528 let missing_snippet = context.snippet(span);
529 let trimmed_snippet = missing_snippet.trim();
530 if !trimmed_snippet.is_empty() {
531 rewrite_comment(trimmed_snippet, false, shape, context.config)
537 /// Recover the missing comments in the specified span, if available.
538 /// The layout of the comments will be preserved as long as it does not break the code
539 /// and its total width does not exceed the max width.
540 pub fn recover_missing_comment_in_span(
543 context: &RewriteContext,
545 ) -> Option<String> {
546 let missing_comment = rewrite_missing_comment(span, shape, context)?;
547 if missing_comment.is_empty() {
550 let missing_snippet = context.snippet(span);
551 let pos = missing_snippet.find('/').unwrap_or(0);
553 let total_width = missing_comment.len() + used_width + 1;
554 let force_new_line_before_comment =
555 missing_snippet[..pos].contains('\n') || total_width > context.config.max_width();
556 let sep = if force_new_line_before_comment {
557 shape.indent.to_string_with_newline(context.config)
561 Some(format!("{}{}", sep, missing_comment))
565 /// Trim trailing whitespaces unless they consist of two or more whitespaces.
566 fn trim_right_unless_two_whitespaces(s: &str, is_doc_comment: bool) -> &str {
567 if is_doc_comment && s.ends_with(" ") {
574 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
575 fn light_rewrite_comment(
579 is_doc_comment: bool,
580 ) -> Option<String> {
581 let lines: Vec<&str> = orig
584 // This is basically just l.trim(), but in the case that a line starts
585 // with `*` we want to leave one space before it, so it aligns with the
587 let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
588 let left_trimmed = if let Some(fnw) = first_non_whitespace {
589 if l.as_bytes()[fnw] == b'*' && fnw > 0 {
597 // Preserve markdown's double-space line break syntax in doc comment.
598 trim_right_unless_two_whitespaces(left_trimmed, is_doc_comment)
601 Some(lines.join(&format!("\n{}", offset.to_string(config))))
604 /// Trims comment characters and possibly a single space from the left of a string.
605 /// Does not trim all whitespace. If a single space is trimmed from the left of the string,
606 /// this function returns true.
607 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle) -> (&'a str, bool) {
608 if line.starts_with("//! ")
609 || line.starts_with("/// ")
610 || line.starts_with("/*! ")
611 || line.starts_with("/** ")
614 } else if let CommentStyle::Custom(opener) = *style {
615 if line.starts_with(opener) {
616 (&line[opener.len()..], true)
618 (&line[opener.trim_right().len()..], false)
620 } else if line.starts_with("/* ")
621 || line.starts_with("// ")
622 || line.starts_with("//!")
623 || line.starts_with("///")
624 || line.starts_with("** ")
625 || line.starts_with("/*!")
626 || (line.starts_with("/**") && !line.starts_with("/**/"))
628 (&line[3..], line.chars().nth(2).unwrap() == ' ')
629 } else if line.starts_with("/*")
630 || line.starts_with("* ")
631 || line.starts_with("//")
632 || line.starts_with("**")
634 (&line[2..], line.chars().nth(1).unwrap() == ' ')
635 } else if line.starts_with('*') {
638 (line, line.starts_with(' '))
642 pub trait FindUncommented {
643 fn find_uncommented(&self, pat: &str) -> Option<usize>;
646 impl FindUncommented for str {
647 fn find_uncommented(&self, pat: &str) -> Option<usize> {
648 let mut needle_iter = pat.chars();
649 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
650 match needle_iter.next() {
652 return Some(i - pat.len());
654 Some(c) => match kind {
655 FullCodeCharKind::Normal | FullCodeCharKind::InString if b == c => {}
657 needle_iter = pat.chars();
663 // Handle case where the pattern is a suffix of the search string
664 match needle_iter.next() {
666 None => Some(self.len() - pat.len()),
671 // Returns the first byte position after the first comment. The given string
672 // is expected to be prefixed by a comment, including delimiters.
673 // Good: "/* /* inner */ outer */ code();"
674 // Bad: "code(); // hello\n world!"
675 pub fn find_comment_end(s: &str) -> Option<usize> {
676 let mut iter = CharClasses::new(s.char_indices());
677 for (kind, (i, _c)) in &mut iter {
678 if kind == FullCodeCharKind::Normal || kind == FullCodeCharKind::InString {
683 // Handle case where the comment ends at the end of s.
684 if iter.status == CharClassesStatus::Normal {
691 /// Returns true if text contains any comment.
692 pub fn contains_comment(text: &str) -> bool {
693 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
696 /// Remove trailing spaces from the specified snippet. We do not remove spaces
697 /// inside strings or comments.
698 pub fn remove_trailing_white_spaces(text: &str) -> String {
699 let mut buffer = String::with_capacity(text.len());
700 let mut space_buffer = String::with_capacity(128);
701 for (char_kind, c) in CharClasses::new(text.chars()) {
704 if char_kind == FullCodeCharKind::InString {
705 buffer.push_str(&space_buffer);
707 space_buffer.clear();
710 _ if c.is_whitespace() => {
711 space_buffer.push(c);
714 if !space_buffer.is_empty() {
715 buffer.push_str(&space_buffer);
716 space_buffer.clear();
725 pub struct CharClasses<T>
731 status: CharClassesStatus,
735 fn get_char(&self) -> char;
738 impl RichChar for char {
739 fn get_char(&self) -> char {
744 impl RichChar for (usize, char) {
745 fn get_char(&self) -> char {
750 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
751 enum CharClassesStatus {
757 // The u32 is the nesting deepness of the comment
759 // Status when the '/' has been consumed, but not yet the '*', deepness is
760 // the new deepness (after the comment opening).
761 BlockCommentOpening(u32),
762 // Status when the '*' has been consumed, but not yet the '/', deepness is
763 // the new deepness (after the comment closing).
764 BlockCommentClosing(u32),
768 /// Distinguish between functional part of code and comments
769 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
770 pub enum CodeCharKind {
775 /// Distinguish between functional part of code and comments,
776 /// describing opening and closing of comments for ease when chunking
777 /// code from tagged characters
778 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
779 pub enum FullCodeCharKind {
781 /// The first character of a comment, there is only one for a comment (always '/')
783 /// Any character inside a comment including the second character of comment
784 /// marks ("//", "/*")
786 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
792 impl FullCodeCharKind {
793 pub fn is_comment(&self) -> bool {
795 FullCodeCharKind::StartComment
796 | FullCodeCharKind::InComment
797 | FullCodeCharKind::EndComment => true,
802 pub fn is_string(&self) -> bool {
803 *self == FullCodeCharKind::InString
806 fn to_codecharkind(&self) -> CodeCharKind {
807 if self.is_comment() {
808 CodeCharKind::Comment
815 impl<T> CharClasses<T>
820 pub fn new(base: T) -> CharClasses<T> {
822 base: multipeek(base),
823 status: CharClassesStatus::Normal,
828 impl<T> Iterator for CharClasses<T>
833 type Item = (FullCodeCharKind, T::Item);
835 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
836 let item = self.base.next()?;
837 let chr = item.get_char();
838 let mut char_kind = FullCodeCharKind::Normal;
839 self.status = match self.status {
840 CharClassesStatus::LitString => match chr {
841 '"' => CharClassesStatus::Normal,
843 char_kind = FullCodeCharKind::InString;
844 CharClassesStatus::LitStringEscape
847 char_kind = FullCodeCharKind::InString;
848 CharClassesStatus::LitString
851 CharClassesStatus::LitStringEscape => {
852 char_kind = FullCodeCharKind::InString;
853 CharClassesStatus::LitString
855 CharClassesStatus::LitChar => match chr {
856 '\\' => CharClassesStatus::LitCharEscape,
857 '\'' => CharClassesStatus::Normal,
858 _ => CharClassesStatus::LitChar,
860 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
861 CharClassesStatus::Normal => match chr {
863 char_kind = FullCodeCharKind::InString;
864 CharClassesStatus::LitString
867 // HACK: Work around mut borrow.
868 match self.base.peek() {
869 Some(next) if next.get_char() == '\\' => {
870 self.status = CharClassesStatus::LitChar;
871 return Some((char_kind, item));
876 match self.base.peek() {
877 Some(next) if next.get_char() == '\'' => CharClassesStatus::LitChar,
878 _ => CharClassesStatus::Normal,
881 '/' => match self.base.peek() {
882 Some(next) if next.get_char() == '*' => {
883 self.status = CharClassesStatus::BlockCommentOpening(1);
884 return Some((FullCodeCharKind::StartComment, item));
886 Some(next) if next.get_char() == '/' => {
887 self.status = CharClassesStatus::LineComment;
888 return Some((FullCodeCharKind::StartComment, item));
890 _ => CharClassesStatus::Normal,
892 _ => CharClassesStatus::Normal,
894 CharClassesStatus::BlockComment(deepness) => {
895 assert_ne!(deepness, 0);
896 self.status = match self.base.peek() {
897 Some(next) if next.get_char() == '/' && chr == '*' => {
898 CharClassesStatus::BlockCommentClosing(deepness - 1)
900 Some(next) if next.get_char() == '*' && chr == '/' => {
901 CharClassesStatus::BlockCommentOpening(deepness + 1)
903 _ => CharClassesStatus::BlockComment(deepness),
905 return Some((FullCodeCharKind::InComment, item));
907 CharClassesStatus::BlockCommentOpening(deepness) => {
908 assert_eq!(chr, '*');
909 self.status = CharClassesStatus::BlockComment(deepness);
910 return Some((FullCodeCharKind::InComment, item));
912 CharClassesStatus::BlockCommentClosing(deepness) => {
913 assert_eq!(chr, '/');
915 self.status = CharClassesStatus::Normal;
916 return Some((FullCodeCharKind::EndComment, item));
918 self.status = CharClassesStatus::BlockComment(deepness);
919 return Some((FullCodeCharKind::InComment, item));
922 CharClassesStatus::LineComment => match chr {
924 self.status = CharClassesStatus::Normal;
925 return Some((FullCodeCharKind::EndComment, item));
928 self.status = CharClassesStatus::LineComment;
929 return Some((FullCodeCharKind::InComment, item));
933 Some((char_kind, item))
937 /// An iterator over the lines of a string, paired with the char kind at the
939 pub struct LineClasses<'a> {
940 base: iter::Peekable<CharClasses<std::str::Chars<'a>>>,
941 kind: FullCodeCharKind,
944 impl<'a> LineClasses<'a> {
945 pub fn new(s: &'a str) -> Self {
947 base: CharClasses::new(s.chars()).peekable(),
948 kind: FullCodeCharKind::Normal,
953 impl<'a> Iterator for LineClasses<'a> {
954 type Item = (FullCodeCharKind, String);
956 fn next(&mut self) -> Option<Self::Item> {
957 if self.base.peek().is_none() {
961 let mut line = String::new();
963 while let Some((kind, c)) = self.base.next() {
972 Some((self.kind, line))
976 /// Iterator over functional and commented parts of a string. Any part of a string is either
977 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
978 /// comments is functional code. Line comments contain their ending newlines.
979 struct UngroupedCommentCodeSlices<'a> {
981 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
984 impl<'a> UngroupedCommentCodeSlices<'a> {
985 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
986 UngroupedCommentCodeSlices {
988 iter: CharClasses::new(code.char_indices()).peekable(),
993 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
994 type Item = (CodeCharKind, usize, &'a str);
996 fn next(&mut self) -> Option<Self::Item> {
997 let (kind, (start_idx, _)) = self.iter.next()?;
999 FullCodeCharKind::Normal | FullCodeCharKind::InString => {
1000 // Consume all the Normal code
1001 while let Some(&(char_kind, _)) = self.iter.peek() {
1002 if char_kind.is_comment() {
1005 let _ = self.iter.next();
1008 FullCodeCharKind::StartComment => {
1009 // Consume the whole comment
1010 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
1014 let slice = match self.iter.peek() {
1015 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
1016 None => &self.slice[start_idx..],
1019 if kind.is_comment() {
1020 CodeCharKind::Comment
1022 CodeCharKind::Normal
1030 /// Iterator over an alternating sequence of functional and commented parts of
1031 /// a string. The first item is always a, possibly zero length, subslice of
1032 /// functional text. Line style comments contain their ending newlines.
1033 pub struct CommentCodeSlices<'a> {
1035 last_slice_kind: CodeCharKind,
1036 last_slice_end: usize,
1039 impl<'a> CommentCodeSlices<'a> {
1040 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
1043 last_slice_kind: CodeCharKind::Comment,
1049 impl<'a> Iterator for CommentCodeSlices<'a> {
1050 type Item = (CodeCharKind, usize, &'a str);
1052 fn next(&mut self) -> Option<Self::Item> {
1053 if self.last_slice_end == self.slice.len() {
1057 let mut sub_slice_end = self.last_slice_end;
1058 let mut first_whitespace = None;
1059 let subslice = &self.slice[self.last_slice_end..];
1060 let mut iter = CharClasses::new(subslice.char_indices());
1062 for (kind, (i, c)) in &mut iter {
1063 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal
1064 && &subslice[..2] == "//"
1065 && [' ', '\t'].contains(&c);
1067 if is_comment_connector && first_whitespace.is_none() {
1068 first_whitespace = Some(i);
1071 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
1072 let last_index = match first_whitespace {
1076 sub_slice_end = self.last_slice_end + last_index;
1080 if !is_comment_connector {
1081 first_whitespace = None;
1085 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
1086 // This was the last subslice.
1087 sub_slice_end = match first_whitespace {
1088 Some(i) => self.last_slice_end + i,
1089 None => self.slice.len(),
1093 let kind = match self.last_slice_kind {
1094 CodeCharKind::Comment => CodeCharKind::Normal,
1095 CodeCharKind::Normal => CodeCharKind::Comment,
1099 self.last_slice_end,
1100 &self.slice[self.last_slice_end..sub_slice_end],
1102 self.last_slice_end = sub_slice_end;
1103 self.last_slice_kind = kind;
1109 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
1110 /// (if it fits in the width/offset, else return None), else return `new`
1111 pub fn recover_comment_removed(
1114 context: &RewriteContext,
1115 ) -> Option<String> {
1116 let snippet = context.snippet(span);
1117 if snippet != new && changed_comment_content(snippet, &new) {
1118 // We missed some comments. Keep the original text.
1119 Some(snippet.to_owned())
1125 /// Return true if the two strings of code have the same payload of comments.
1126 /// The payload of comments is everything in the string except:
1127 /// - actual code (not comments)
1128 /// - comment start/end marks
1130 /// - '*' at the beginning of lines in block comments
1131 fn changed_comment_content(orig: &str, new: &str) -> bool {
1132 // Cannot write this as a fn since we cannot return types containing closures
1133 let code_comment_content = |code| {
1134 let slices = UngroupedCommentCodeSlices::new(code);
1136 .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
1137 .flat_map(|(_, _, s)| CommentReducer::new(s))
1139 let res = code_comment_content(orig).ne(code_comment_content(new));
1141 "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
1145 code_comment_content(orig).collect::<String>(),
1146 code_comment_content(new).collect::<String>()
1151 /// Iterator over the 'payload' characters of a comment.
1152 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
1153 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
1155 struct CommentReducer<'a> {
1157 at_start_line: bool,
1158 iter: std::str::Chars<'a>,
1161 impl<'a> CommentReducer<'a> {
1162 fn new(comment: &'a str) -> CommentReducer<'a> {
1163 let is_block = comment.starts_with("/*");
1164 let comment = remove_comment_header(comment);
1167 at_start_line: false, // There are no supplementary '*' on the first line
1168 iter: comment.chars(),
1173 impl<'a> Iterator for CommentReducer<'a> {
1176 fn next(&mut self) -> Option<Self::Item> {
1178 let mut c = self.iter.next()?;
1179 if self.is_block && self.at_start_line {
1180 while c.is_whitespace() {
1181 c = self.iter.next()?;
1183 // Ignore leading '*'
1185 c = self.iter.next()?;
1187 } else if c == '\n' {
1188 self.at_start_line = true;
1190 if !c.is_whitespace() {
1197 fn remove_comment_header(comment: &str) -> &str {
1198 if comment.starts_with("///") || comment.starts_with("//!") {
1200 } else if comment.starts_with("//") {
1202 } else if (comment.starts_with("/**") && !comment.starts_with("/**/"))
1203 || comment.starts_with("/*!")
1205 &comment[3..comment.len() - 2]
1208 comment.starts_with("/*"),
1209 format!("string '{}' is not a comment", comment)
1211 &comment[2..comment.len() - 2]
1218 use shape::{Indent, Shape};
1222 let mut iter = CharClasses::new("//\n\n".chars());
1224 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
1225 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
1226 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
1227 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
1228 assert_eq!(None, iter.next());
1232 fn comment_code_slices() {
1233 let input = "code(); /* test */ 1 + 1";
1234 let mut iter = CommentCodeSlices::new(input);
1236 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
1238 (CodeCharKind::Comment, 8, "/* test */"),
1239 iter.next().unwrap()
1241 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
1242 assert_eq!(None, iter.next());
1246 fn comment_code_slices_two() {
1247 let input = "// comment\n test();";
1248 let mut iter = CommentCodeSlices::new(input);
1250 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
1252 (CodeCharKind::Comment, 0, "// comment\n"),
1253 iter.next().unwrap()
1256 (CodeCharKind::Normal, 11, " test();"),
1257 iter.next().unwrap()
1259 assert_eq!(None, iter.next());
1263 fn comment_code_slices_three() {
1264 let input = "1 // comment\n // comment2\n\n";
1265 let mut iter = CommentCodeSlices::new(input);
1267 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
1269 (CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
1270 iter.next().unwrap()
1272 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
1273 assert_eq!(None, iter.next());
1278 fn format_comments() {
1279 let mut config: ::config::Config = Default::default();
1280 config.set().wrap_comments(true);
1281 config.set().normalize_comments(true);
1283 let comment = rewrite_comment(" //test",
1285 Shape::legacy(100, Indent::new(0, 100)),
1287 assert_eq!("/* test */", comment);
1289 let comment = rewrite_comment("// comment on a",
1291 Shape::legacy(10, Indent::empty()),
1293 assert_eq!("// comment\n// on a", comment);
1295 let comment = rewrite_comment("// A multi line comment\n // between args.",
1297 Shape::legacy(60, Indent::new(0, 12)),
1299 assert_eq!("// A multi line comment\n // between args.", comment);
1301 let input = "// comment";
1304 let comment = rewrite_comment(input,
1306 Shape::legacy(9, Indent::new(0, 69)),
1308 assert_eq!(expected, comment);
1310 let comment = rewrite_comment("/* trimmed */",
1312 Shape::legacy(100, Indent::new(0, 100)),
1314 assert_eq!("/* trimmed */", comment);
1317 // This is probably intended to be a non-test fn, but it is not used. I'm
1318 // keeping it around unless it helps us test stuff.
1319 fn uncommented(text: &str) -> String {
1320 CharClasses::new(text.chars())
1321 .filter_map(|(s, c)| match s {
1322 FullCodeCharKind::Normal | FullCodeCharKind::InString => Some(c),
1329 fn test_uncommented() {
1330 assert_eq!(&uncommented("abc/*...*/"), "abc");
1332 &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
1335 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
1339 fn test_contains_comment() {
1340 assert_eq!(contains_comment("abc"), false);
1341 assert_eq!(contains_comment("abc // qsdf"), true);
1342 assert_eq!(contains_comment("abc /* kqsdf"), true);
1343 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
1347 fn test_find_uncommented() {
1348 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
1349 assert_eq!(expected, haystack.find_uncommented(needle));
1352 check("/*/ */test", "test", Some(6));
1353 check("//test\ntest", "test", Some(7));
1354 check("/* comment only */", "whatever", None);
1356 "/* comment */ some text /* more commentary */ result",
1360 check("sup // sup", "p", Some(2));
1361 check("sup", "x", None);
1362 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
1363 check("/*sup yo? \n sup*/ sup", "p", Some(20));
1364 check("hel/*lohello*/lo", "hello", None);
1365 check("acb", "ab", None);
1366 check(",/*A*/ ", ",", Some(0));
1367 check("abc", "abc", Some(0));
1368 check("/* abc */", "abc", None);
1369 check("/**/abc/* */", "abc", Some(4));
1370 check("\"/* abc */\"", "abc", Some(4));
1371 check("\"/* abc", "abc", Some(4));
1375 fn test_remove_trailing_white_spaces() {
1376 let s = format!(" r#\"\n test\n \"#");
1377 assert_eq!(remove_trailing_white_spaces(&s), s);