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::source_map::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};
23 use {ErrorKind, FormattingError};
25 fn is_custom_comment(comment: &str) -> bool {
26 if !comment.starts_with("//") {
28 } else if let Some(c) = comment.chars().nth(2) {
29 !c.is_alphanumeric() && !c.is_whitespace()
35 #[derive(Copy, Clone, PartialEq, Eq)]
36 pub enum CommentStyle<'a> {
46 fn custom_opener(s: &str) -> &str {
47 s.lines().next().map_or("", |first_line| {
50 .map_or(first_line, |space_index| &first_line[0..space_index + 1])
54 impl<'a> CommentStyle<'a> {
55 pub fn is_doc_comment(&self) -> bool {
57 CommentStyle::TripleSlash | CommentStyle::Doc => true,
62 pub fn opener(&self) -> &'a str {
64 CommentStyle::DoubleSlash => "// ",
65 CommentStyle::TripleSlash => "/// ",
66 CommentStyle::Doc => "//! ",
67 CommentStyle::SingleBullet => "/* ",
68 CommentStyle::DoubleBullet => "/** ",
69 CommentStyle::Exclamation => "/*! ",
70 CommentStyle::Custom(opener) => opener,
74 pub fn closer(&self) -> &'a str {
76 CommentStyle::DoubleSlash
77 | CommentStyle::TripleSlash
78 | CommentStyle::Custom(..)
79 | CommentStyle::Doc => "",
80 CommentStyle::DoubleBullet => " **/",
81 CommentStyle::SingleBullet | CommentStyle::Exclamation => " */",
85 pub fn line_start(&self) -> &'a str {
87 CommentStyle::DoubleSlash => "// ",
88 CommentStyle::TripleSlash => "/// ",
89 CommentStyle::Doc => "//! ",
90 CommentStyle::SingleBullet | CommentStyle::Exclamation => " * ",
91 CommentStyle::DoubleBullet => " ** ",
92 CommentStyle::Custom(opener) => opener,
96 pub fn to_str_tuplet(&self) -> (&'a str, &'a str, &'a str) {
97 (self.opener(), self.closer(), self.line_start())
101 fn comment_style(orig: &str, normalize_comments: bool) -> CommentStyle {
102 if !normalize_comments {
103 if orig.starts_with("/**") && !orig.starts_with("/**/") {
104 CommentStyle::DoubleBullet
105 } else if orig.starts_with("/*!") {
106 CommentStyle::Exclamation
107 } else if orig.starts_with("/*") {
108 CommentStyle::SingleBullet
109 } else if orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/') {
110 CommentStyle::TripleSlash
111 } else if orig.starts_with("//!") {
113 } else if is_custom_comment(orig) {
114 CommentStyle::Custom(custom_opener(orig))
116 CommentStyle::DoubleSlash
118 } else if (orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/'))
119 || (orig.starts_with("/**") && !orig.starts_with("/**/"))
121 CommentStyle::TripleSlash
122 } else if orig.starts_with("//!") || orig.starts_with("/*!") {
124 } else if is_custom_comment(orig) {
125 CommentStyle::Custom(custom_opener(orig))
127 CommentStyle::DoubleSlash
131 /// Combine `prev_str` and `next_str` into a single `String`. `span` may contain
132 /// comments between two strings. If there are such comments, then that will be
133 /// recovered. If `allow_extend` is true and there is no comment between the two
134 /// strings, then they will be put on a single line as long as doing so does not
135 /// exceed max width.
136 pub fn combine_strs_with_missing_comments(
137 context: &RewriteContext,
143 ) -> Option<String> {
145 String::with_capacity(prev_str.len() + next_str.len() + shape.indent.width() + 128);
146 result.push_str(prev_str);
147 let mut allow_one_line = !prev_str.contains('\n') && !next_str.contains('\n');
148 let first_sep = if prev_str.is_empty() || next_str.is_empty() {
153 let mut one_line_width =
154 last_line_width(prev_str) + first_line_width(next_str) + first_sep.len();
156 let config = context.config;
157 let indent = shape.indent;
158 let missing_comment = rewrite_missing_comment(span, shape, context)?;
160 if missing_comment.is_empty() {
161 if allow_extend && prev_str.len() + first_sep.len() + next_str.len() <= shape.width {
162 result.push_str(first_sep);
163 } else if !prev_str.is_empty() {
164 result.push_str(&indent.to_string_with_newline(config))
166 result.push_str(next_str);
170 // We have a missing comment between the first expression and the second expression.
172 // Peek the the original source code and find out whether there is a newline between the first
173 // expression and the second expression or the missing comment. We will preserve the original
174 // layout whenever possible.
175 let original_snippet = context.snippet(span);
176 let prefer_same_line = if let Some(pos) = original_snippet.find('/') {
177 !original_snippet[..pos].contains('\n')
179 !original_snippet.contains('\n')
182 one_line_width -= first_sep.len();
183 let first_sep = if prev_str.is_empty() || missing_comment.is_empty() {
186 let one_line_width = last_line_width(prev_str) + first_line_width(&missing_comment) + 1;
187 if prefer_same_line && one_line_width <= shape.width {
190 indent.to_string_with_newline(config)
193 result.push_str(&first_sep);
194 result.push_str(&missing_comment);
196 let second_sep = if missing_comment.is_empty() || next_str.is_empty() {
198 } else if missing_comment.starts_with("//") {
199 indent.to_string_with_newline(config)
201 one_line_width += missing_comment.len() + first_sep.len() + 1;
202 allow_one_line &= !missing_comment.starts_with("//") && !missing_comment.contains('\n');
203 if prefer_same_line && allow_one_line && one_line_width <= shape.width {
206 indent.to_string_with_newline(config)
209 result.push_str(&second_sep);
210 result.push_str(next_str);
215 pub fn rewrite_doc_comment(orig: &str, shape: Shape, config: &Config) -> Option<String> {
216 _rewrite_comment(orig, false, shape, config, true)
219 pub fn rewrite_comment(
224 ) -> Option<String> {
225 _rewrite_comment(orig, block_style, shape, config, false)
233 is_doc_comment: bool,
234 ) -> Option<String> {
235 // If there are lines without a starting sigil, we won't format them correctly
236 // so in that case we won't even re-align (if !config.normalize_comments()) and
237 // we should stop now.
238 let num_bare_lines = orig
240 .map(|line| line.trim())
241 .filter(|l| !(l.starts_with('*') || l.starts_with("//") || l.starts_with("/*")))
243 if num_bare_lines > 0 && !config.normalize_comments() {
244 return Some(orig.to_owned());
246 if !config.normalize_comments() && !config.wrap_comments() {
247 return light_rewrite_comment(orig, shape.indent, config, is_doc_comment);
250 identify_comment(orig, block_style, shape, config, is_doc_comment)
258 is_doc_comment: bool,
259 ) -> Option<String> {
260 let style = comment_style(orig, false);
261 let mut first_group_ending = 0;
263 fn compute_len(orig: &str, line: &str) -> usize {
264 if orig.len() > line.len() {
265 if orig.as_bytes()[line.len()] == b'\r' {
276 CommentStyle::DoubleSlash | CommentStyle::TripleSlash | CommentStyle::Doc => {
277 let line_start = style.line_start().trim_left();
278 for line in orig.lines() {
279 if line.trim_left().starts_with(line_start) || comment_style(line, false) == style {
280 first_group_ending += compute_len(&orig[first_group_ending..], line);
286 CommentStyle::Custom(opener) => {
287 let trimmed_opener = opener.trim_right();
288 for line in orig.lines() {
289 if line.trim_left().starts_with(trimmed_opener) {
290 first_group_ending += compute_len(&orig[first_group_ending..], line);
296 // for a block comment, search for the closing symbol
297 CommentStyle::DoubleBullet | CommentStyle::SingleBullet | CommentStyle::Exclamation => {
298 let closer = style.closer().trim_left();
299 for line in orig.lines() {
300 first_group_ending += compute_len(&orig[first_group_ending..], line);
301 if line.trim_left().ends_with(closer) {
308 let (first_group, rest) = orig.split_at(first_group_ending);
309 let first_group_str = rewrite_comment_inner(
315 is_doc_comment || style.is_doc_comment(),
318 Some(first_group_str)
320 identify_comment(rest, block_style, shape, config, is_doc_comment).map(|rest_str| {
324 shape.indent.to_string(config),
331 fn rewrite_comment_inner(
337 is_doc_comment: bool,
338 ) -> Option<String> {
339 let (opener, closer, line_start) = if block_style {
340 CommentStyle::SingleBullet.to_str_tuplet()
342 comment_style(orig, config.normalize_comments()).to_str_tuplet()
345 let max_chars = shape
347 .checked_sub(closer.len() + opener.len())
349 let indent_str = shape.indent.to_string_with_newline(config);
350 let fmt_indent = shape.indent + (opener.len() - line_start.len());
351 let mut fmt = StringFormat {
356 shape: Shape::legacy(max_chars, fmt_indent),
361 let line_breaks = count_newlines(orig.trim_right());
365 .map(|(i, mut line)| {
366 line = trim_right_unless_two_whitespaces(line.trim_left(), is_doc_comment);
368 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
369 line = line[..(line.len() - 2)].trim_right();
373 }).map(|s| left_trim_comment_line(s, &style))
374 .map(|(line, has_leading_whitespace)| {
375 if orig.starts_with("/*") && line_breaks == 0 {
378 has_leading_whitespace || config.normalize_comments(),
381 (line, has_leading_whitespace || config.normalize_comments())
385 let mut result = String::with_capacity(orig.len() * 2);
386 result.push_str(opener);
387 let mut code_block_buffer = String::with_capacity(128);
388 let mut is_prev_line_multi_line = false;
389 let mut inside_code_block = false;
390 let comment_line_separator = format!("{}{}", indent_str, line_start);
391 let join_code_block_with_comment_line_separator = |s: &str| {
392 let mut result = String::with_capacity(s.len() + 128);
393 let mut iter = s.lines().peekable();
394 while let Some(line) = iter.next() {
395 result.push_str(line);
396 result.push_str(match iter.peek() {
397 Some(next_line) if next_line.is_empty() => comment_line_separator.trim_right(),
398 Some(..) => &comment_line_separator,
405 for (i, (line, has_leading_whitespace)) in lines.enumerate() {
406 let is_last = i == count_newlines(orig);
408 if inside_code_block {
409 if line.starts_with("```") {
410 inside_code_block = false;
411 result.push_str(&comment_line_separator);
413 let mut config = config.clone();
414 config.set().wrap_comments(false);
415 match ::format_code_block(&code_block_buffer, &config) {
416 Some(ref s) => trim_custom_comment_prefix(s),
417 None => trim_custom_comment_prefix(&code_block_buffer),
420 result.push_str(&join_code_block_with_comment_line_separator(&code_block));
421 code_block_buffer.clear();
422 result.push_str(&comment_line_separator);
423 result.push_str(line);
425 code_block_buffer.push_str(&hide_sharp_behind_comment(line));
426 code_block_buffer.push('\n');
429 // There is an code block that is not properly enclosed by backticks.
430 // We will leave them untouched.
431 result.push_str(&comment_line_separator);
432 result.push_str(&join_code_block_with_comment_line_separator(
433 &trim_custom_comment_prefix(&code_block_buffer),
440 inside_code_block = line.starts_with("```");
442 if result == opener {
443 let force_leading_whitespace = opener == "/* " && count_newlines(orig) == 0;
444 if !has_leading_whitespace && !force_leading_whitespace && result.ends_with(' ') {
450 } else if is_prev_line_multi_line && !line.is_empty() {
452 } else if is_last && line.is_empty() {
453 // trailing blank lines are unwanted
454 if !closer.is_empty() {
455 result.push_str(&indent_str);
459 result.push_str(&comment_line_separator);
460 if !has_leading_whitespace && result.ends_with(' ') {
466 if config.wrap_comments() && line.len() > fmt.shape.width && !has_url(line) {
467 match rewrite_string(line, &fmt) {
469 is_prev_line_multi_line = s.contains('\n');
472 None if is_prev_line_multi_line => {
473 // We failed to put the current `line` next to the previous `line`.
474 // Remove the trailing space, then start rewrite on the next line.
476 result.push_str(&comment_line_separator);
477 fmt.shape = Shape::legacy(max_chars, fmt_indent);
478 match rewrite_string(line, &fmt) {
480 is_prev_line_multi_line = s.contains('\n');
484 is_prev_line_multi_line = false;
485 result.push_str(line);
490 is_prev_line_multi_line = false;
491 result.push_str(line);
495 fmt.shape = if is_prev_line_multi_line {
497 let offset = 1 + last_line_width(&result) - line_start.len();
499 width: max_chars.saturating_sub(offset),
501 offset: fmt.shape.offset + offset,
504 Shape::legacy(max_chars, fmt_indent)
507 if line.is_empty() && result.ends_with(' ') && !is_last {
508 // Remove space if this is an empty comment or a doc comment.
511 result.push_str(line);
512 fmt.shape = Shape::legacy(max_chars, fmt_indent);
513 is_prev_line_multi_line = false;
517 result.push_str(closer);
518 if result.ends_with(opener) && opener.ends_with(' ') {
526 const RUSTFMT_CUSTOM_COMMENT_PREFIX: &str = "//#### ";
528 fn hide_sharp_behind_comment(s: &str) -> Cow<str> {
529 if s.trim_left().starts_with("# ") {
530 Cow::from(format!("{}{}", RUSTFMT_CUSTOM_COMMENT_PREFIX, s))
536 fn trim_custom_comment_prefix(s: &str) -> String {
539 let left_trimmed = line.trim_left();
540 if left_trimmed.starts_with(RUSTFMT_CUSTOM_COMMENT_PREFIX) {
541 left_trimmed.trim_left_matches(RUSTFMT_CUSTOM_COMMENT_PREFIX)
545 }).collect::<Vec<_>>()
549 /// Returns true if the given string MAY include URLs or alike.
550 fn has_url(s: &str) -> bool {
551 // This function may return false positive, but should get its job done in most cases.
552 s.contains("https://") || s.contains("http://") || s.contains("ftp://") || s.contains("file://")
555 /// Given the span, rewrite the missing comment inside it if available.
556 /// Note that the given span must only include comments (or leading/trailing whitespaces).
557 pub fn rewrite_missing_comment(
560 context: &RewriteContext,
561 ) -> Option<String> {
562 let missing_snippet = context.snippet(span);
563 let trimmed_snippet = missing_snippet.trim();
564 if !trimmed_snippet.is_empty() {
565 rewrite_comment(trimmed_snippet, false, shape, context.config)
571 /// Recover the missing comments in the specified span, if available.
572 /// The layout of the comments will be preserved as long as it does not break the code
573 /// and its total width does not exceed the max width.
574 pub fn recover_missing_comment_in_span(
577 context: &RewriteContext,
579 ) -> Option<String> {
580 let missing_comment = rewrite_missing_comment(span, shape, context)?;
581 if missing_comment.is_empty() {
584 let missing_snippet = context.snippet(span);
585 let pos = missing_snippet.find('/').unwrap_or(0);
587 let total_width = missing_comment.len() + used_width + 1;
588 let force_new_line_before_comment =
589 missing_snippet[..pos].contains('\n') || total_width > context.config.max_width();
590 let sep = if force_new_line_before_comment {
591 shape.indent.to_string_with_newline(context.config)
595 Some(format!("{}{}", sep, missing_comment))
599 /// Trim trailing whitespaces unless they consist of two or more whitespaces.
600 fn trim_right_unless_two_whitespaces(s: &str, is_doc_comment: bool) -> &str {
601 if is_doc_comment && s.ends_with(" ") {
608 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
609 fn light_rewrite_comment(
613 is_doc_comment: bool,
614 ) -> Option<String> {
615 let lines: Vec<&str> = orig
618 // This is basically just l.trim(), but in the case that a line starts
619 // with `*` we want to leave one space before it, so it aligns with the
621 let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
622 let left_trimmed = if let Some(fnw) = first_non_whitespace {
623 if l.as_bytes()[fnw] == b'*' && fnw > 0 {
631 // Preserve markdown's double-space line break syntax in doc comment.
632 trim_right_unless_two_whitespaces(left_trimmed, is_doc_comment)
634 Some(lines.join(&format!("\n{}", offset.to_string(config))))
637 /// Trims comment characters and possibly a single space from the left of a string.
638 /// Does not trim all whitespace. If a single space is trimmed from the left of the string,
639 /// this function returns true.
640 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle) -> (&'a str, bool) {
641 if line.starts_with("//! ")
642 || line.starts_with("/// ")
643 || line.starts_with("/*! ")
644 || line.starts_with("/** ")
647 } else if let CommentStyle::Custom(opener) = *style {
648 if line.starts_with(opener) {
649 (&line[opener.len()..], true)
651 (&line[opener.trim_right().len()..], false)
653 } else if line.starts_with("/* ")
654 || line.starts_with("// ")
655 || line.starts_with("//!")
656 || line.starts_with("///")
657 || line.starts_with("** ")
658 || line.starts_with("/*!")
659 || (line.starts_with("/**") && !line.starts_with("/**/"))
661 (&line[3..], line.chars().nth(2).unwrap() == ' ')
662 } else if line.starts_with("/*")
663 || line.starts_with("* ")
664 || line.starts_with("//")
665 || line.starts_with("**")
667 (&line[2..], line.chars().nth(1).unwrap() == ' ')
668 } else if line.starts_with('*') {
671 (line, line.starts_with(' '))
675 pub trait FindUncommented {
676 fn find_uncommented(&self, pat: &str) -> Option<usize>;
679 impl FindUncommented for str {
680 fn find_uncommented(&self, pat: &str) -> Option<usize> {
681 let mut needle_iter = pat.chars();
682 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
683 match needle_iter.next() {
685 return Some(i - pat.len());
687 Some(c) => match kind {
688 FullCodeCharKind::Normal | FullCodeCharKind::InString if b == c => {}
690 needle_iter = pat.chars();
696 // Handle case where the pattern is a suffix of the search string
697 match needle_iter.next() {
699 None => Some(self.len() - pat.len()),
704 // Returns the first byte position after the first comment. The given string
705 // is expected to be prefixed by a comment, including delimiters.
706 // Good: "/* /* inner */ outer */ code();"
707 // Bad: "code(); // hello\n world!"
708 pub fn find_comment_end(s: &str) -> Option<usize> {
709 let mut iter = CharClasses::new(s.char_indices());
710 for (kind, (i, _c)) in &mut iter {
711 if kind == FullCodeCharKind::Normal || kind == FullCodeCharKind::InString {
716 // Handle case where the comment ends at the end of s.
717 if iter.status == CharClassesStatus::Normal {
724 /// Returns true if text contains any comment.
725 pub fn contains_comment(text: &str) -> bool {
726 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
729 /// Remove trailing spaces from the specified snippet. We do not remove spaces
730 /// inside strings or comments.
731 pub fn remove_trailing_white_spaces(text: &str) -> String {
732 let mut buffer = String::with_capacity(text.len());
733 let mut space_buffer = String::with_capacity(128);
734 for (char_kind, c) in CharClasses::new(text.chars()) {
737 if char_kind == FullCodeCharKind::InString {
738 buffer.push_str(&space_buffer);
740 space_buffer.clear();
743 _ if c.is_whitespace() => {
744 space_buffer.push(c);
747 if !space_buffer.is_empty() {
748 buffer.push_str(&space_buffer);
749 space_buffer.clear();
758 pub struct CharClasses<T>
764 status: CharClassesStatus,
768 fn get_char(&self) -> char;
771 impl RichChar for char {
772 fn get_char(&self) -> char {
777 impl RichChar for (usize, char) {
778 fn get_char(&self) -> char {
783 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
784 enum CharClassesStatus {
790 // The u32 is the nesting deepness of the comment
792 // Status when the '/' has been consumed, but not yet the '*', deepness is
793 // the new deepness (after the comment opening).
794 BlockCommentOpening(u32),
795 // Status when the '*' has been consumed, but not yet the '/', deepness is
796 // the new deepness (after the comment closing).
797 BlockCommentClosing(u32),
801 /// Distinguish between functional part of code and comments
802 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
803 pub enum CodeCharKind {
808 /// Distinguish between functional part of code and comments,
809 /// describing opening and closing of comments for ease when chunking
810 /// code from tagged characters
811 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
812 pub enum FullCodeCharKind {
814 /// The first character of a comment, there is only one for a comment (always '/')
816 /// Any character inside a comment including the second character of comment
817 /// marks ("//", "/*")
819 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
825 impl FullCodeCharKind {
826 pub fn is_comment(self) -> bool {
828 FullCodeCharKind::StartComment
829 | FullCodeCharKind::InComment
830 | FullCodeCharKind::EndComment => true,
835 pub fn is_string(self) -> bool {
836 self == FullCodeCharKind::InString
839 fn to_codecharkind(self) -> CodeCharKind {
840 if self.is_comment() {
841 CodeCharKind::Comment
848 impl<T> CharClasses<T>
853 pub fn new(base: T) -> CharClasses<T> {
855 base: multipeek(base),
856 status: CharClassesStatus::Normal,
861 impl<T> Iterator for CharClasses<T>
866 type Item = (FullCodeCharKind, T::Item);
868 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
869 let item = self.base.next()?;
870 let chr = item.get_char();
871 let mut char_kind = FullCodeCharKind::Normal;
872 self.status = match self.status {
873 CharClassesStatus::LitString => match chr {
874 '"' => CharClassesStatus::Normal,
876 char_kind = FullCodeCharKind::InString;
877 CharClassesStatus::LitStringEscape
880 char_kind = FullCodeCharKind::InString;
881 CharClassesStatus::LitString
884 CharClassesStatus::LitStringEscape => {
885 char_kind = FullCodeCharKind::InString;
886 CharClassesStatus::LitString
888 CharClassesStatus::LitChar => match chr {
889 '\\' => CharClassesStatus::LitCharEscape,
890 '\'' => CharClassesStatus::Normal,
891 _ => CharClassesStatus::LitChar,
893 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
894 CharClassesStatus::Normal => match chr {
896 char_kind = FullCodeCharKind::InString;
897 CharClassesStatus::LitString
900 // HACK: Work around mut borrow.
901 match self.base.peek() {
902 Some(next) if next.get_char() == '\\' => {
903 self.status = CharClassesStatus::LitChar;
904 return Some((char_kind, item));
909 match self.base.peek() {
910 Some(next) if next.get_char() == '\'' => CharClassesStatus::LitChar,
911 _ => CharClassesStatus::Normal,
914 '/' => match self.base.peek() {
915 Some(next) if next.get_char() == '*' => {
916 self.status = CharClassesStatus::BlockCommentOpening(1);
917 return Some((FullCodeCharKind::StartComment, item));
919 Some(next) if next.get_char() == '/' => {
920 self.status = CharClassesStatus::LineComment;
921 return Some((FullCodeCharKind::StartComment, item));
923 _ => CharClassesStatus::Normal,
925 _ => CharClassesStatus::Normal,
927 CharClassesStatus::BlockComment(deepness) => {
928 assert_ne!(deepness, 0);
929 self.status = match self.base.peek() {
930 Some(next) if next.get_char() == '/' && chr == '*' => {
931 CharClassesStatus::BlockCommentClosing(deepness - 1)
933 Some(next) if next.get_char() == '*' && chr == '/' => {
934 CharClassesStatus::BlockCommentOpening(deepness + 1)
936 _ => CharClassesStatus::BlockComment(deepness),
938 return Some((FullCodeCharKind::InComment, item));
940 CharClassesStatus::BlockCommentOpening(deepness) => {
941 assert_eq!(chr, '*');
942 self.status = CharClassesStatus::BlockComment(deepness);
943 return Some((FullCodeCharKind::InComment, item));
945 CharClassesStatus::BlockCommentClosing(deepness) => {
946 assert_eq!(chr, '/');
948 self.status = CharClassesStatus::Normal;
949 return Some((FullCodeCharKind::EndComment, item));
951 self.status = CharClassesStatus::BlockComment(deepness);
952 return Some((FullCodeCharKind::InComment, item));
955 CharClassesStatus::LineComment => match chr {
957 self.status = CharClassesStatus::Normal;
958 return Some((FullCodeCharKind::EndComment, item));
961 self.status = CharClassesStatus::LineComment;
962 return Some((FullCodeCharKind::InComment, item));
966 Some((char_kind, item))
970 /// An iterator over the lines of a string, paired with the char kind at the
972 pub struct LineClasses<'a> {
973 base: iter::Peekable<CharClasses<std::str::Chars<'a>>>,
974 kind: FullCodeCharKind,
977 impl<'a> LineClasses<'a> {
978 pub fn new(s: &'a str) -> Self {
980 base: CharClasses::new(s.chars()).peekable(),
981 kind: FullCodeCharKind::Normal,
986 impl<'a> Iterator for LineClasses<'a> {
987 type Item = (FullCodeCharKind, String);
989 fn next(&mut self) -> Option<Self::Item> {
992 let mut line = String::new();
994 while let Some((kind, c)) = self.base.next() {
1003 Some((self.kind, line))
1007 /// Iterator over functional and commented parts of a string. Any part of a string is either
1008 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
1009 /// comments is functional code. Line comments contain their ending newlines.
1010 struct UngroupedCommentCodeSlices<'a> {
1012 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
1015 impl<'a> UngroupedCommentCodeSlices<'a> {
1016 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
1017 UngroupedCommentCodeSlices {
1019 iter: CharClasses::new(code.char_indices()).peekable(),
1024 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
1025 type Item = (CodeCharKind, usize, &'a str);
1027 fn next(&mut self) -> Option<Self::Item> {
1028 let (kind, (start_idx, _)) = self.iter.next()?;
1030 FullCodeCharKind::Normal | FullCodeCharKind::InString => {
1031 // Consume all the Normal code
1032 while let Some(&(char_kind, _)) = self.iter.peek() {
1033 if char_kind.is_comment() {
1036 let _ = self.iter.next();
1039 FullCodeCharKind::StartComment => {
1040 // Consume the whole comment
1041 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
1045 let slice = match self.iter.peek() {
1046 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
1047 None => &self.slice[start_idx..],
1050 if kind.is_comment() {
1051 CodeCharKind::Comment
1053 CodeCharKind::Normal
1061 /// Iterator over an alternating sequence of functional and commented parts of
1062 /// a string. The first item is always a, possibly zero length, subslice of
1063 /// functional text. Line style comments contain their ending newlines.
1064 pub struct CommentCodeSlices<'a> {
1066 last_slice_kind: CodeCharKind,
1067 last_slice_end: usize,
1070 impl<'a> CommentCodeSlices<'a> {
1071 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
1074 last_slice_kind: CodeCharKind::Comment,
1080 impl<'a> Iterator for CommentCodeSlices<'a> {
1081 type Item = (CodeCharKind, usize, &'a str);
1083 fn next(&mut self) -> Option<Self::Item> {
1084 if self.last_slice_end == self.slice.len() {
1088 let mut sub_slice_end = self.last_slice_end;
1089 let mut first_whitespace = None;
1090 let subslice = &self.slice[self.last_slice_end..];
1091 let mut iter = CharClasses::new(subslice.char_indices());
1093 for (kind, (i, c)) in &mut iter {
1094 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal
1095 && &subslice[..2] == "//"
1096 && [' ', '\t'].contains(&c);
1098 if is_comment_connector && first_whitespace.is_none() {
1099 first_whitespace = Some(i);
1102 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
1103 let last_index = match first_whitespace {
1107 sub_slice_end = self.last_slice_end + last_index;
1111 if !is_comment_connector {
1112 first_whitespace = None;
1116 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
1117 // This was the last subslice.
1118 sub_slice_end = match first_whitespace {
1119 Some(i) => self.last_slice_end + i,
1120 None => self.slice.len(),
1124 let kind = match self.last_slice_kind {
1125 CodeCharKind::Comment => CodeCharKind::Normal,
1126 CodeCharKind::Normal => CodeCharKind::Comment,
1130 self.last_slice_end,
1131 &self.slice[self.last_slice_end..sub_slice_end],
1133 self.last_slice_end = sub_slice_end;
1134 self.last_slice_kind = kind;
1140 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
1141 /// (if it fits in the width/offset, else return None), else return `new`
1142 pub fn recover_comment_removed(
1145 context: &RewriteContext,
1146 ) -> Option<String> {
1147 let snippet = context.snippet(span);
1148 if snippet != new && changed_comment_content(snippet, &new) {
1149 // We missed some comments. Warn and keep the original text.
1150 if context.config.error_on_unformatted() {
1151 context.report.append(
1152 context.source_map.span_to_filename(span).into(),
1153 vec![FormattingError::from_span(
1155 &context.source_map,
1156 ErrorKind::LostComment,
1160 Some(snippet.to_owned())
1166 pub fn filter_normal_code(code: &str) -> String {
1167 let mut buffer = String::with_capacity(code.len());
1168 LineClasses::new(code).for_each(|(kind, line)| match kind {
1169 FullCodeCharKind::Normal | FullCodeCharKind::InString => {
1170 buffer.push_str(&line);
1175 if !code.ends_with('\n') && buffer.ends_with('\n') {
1181 /// Return true if the two strings of code have the same payload of comments.
1182 /// The payload of comments is everything in the string except:
1183 /// - actual code (not comments)
1184 /// - comment start/end marks
1186 /// - '*' at the beginning of lines in block comments
1187 fn changed_comment_content(orig: &str, new: &str) -> bool {
1188 // Cannot write this as a fn since we cannot return types containing closures
1189 let code_comment_content = |code| {
1190 let slices = UngroupedCommentCodeSlices::new(code);
1192 .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
1193 .flat_map(|(_, _, s)| CommentReducer::new(s))
1195 let res = code_comment_content(orig).ne(code_comment_content(new));
1197 "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
1201 code_comment_content(orig).collect::<String>(),
1202 code_comment_content(new).collect::<String>()
1207 /// Iterator over the 'payload' characters of a comment.
1208 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
1209 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
1211 struct CommentReducer<'a> {
1213 at_start_line: bool,
1214 iter: std::str::Chars<'a>,
1217 impl<'a> CommentReducer<'a> {
1218 fn new(comment: &'a str) -> CommentReducer<'a> {
1219 let is_block = comment.starts_with("/*");
1220 let comment = remove_comment_header(comment);
1223 at_start_line: false, // There are no supplementary '*' on the first line
1224 iter: comment.chars(),
1229 impl<'a> Iterator for CommentReducer<'a> {
1232 fn next(&mut self) -> Option<Self::Item> {
1234 let mut c = self.iter.next()?;
1235 if self.is_block && self.at_start_line {
1236 while c.is_whitespace() {
1237 c = self.iter.next()?;
1239 // Ignore leading '*'
1241 c = self.iter.next()?;
1243 } else if c == '\n' {
1244 self.at_start_line = true;
1246 if !c.is_whitespace() {
1253 fn remove_comment_header(comment: &str) -> &str {
1254 if comment.starts_with("///") || comment.starts_with("//!") {
1256 } else if comment.starts_with("//") {
1258 } else if (comment.starts_with("/**") && !comment.starts_with("/**/"))
1259 || comment.starts_with("/*!")
1261 &comment[3..comment.len() - 2]
1264 comment.starts_with("/*"),
1265 format!("string '{}' is not a comment", comment)
1267 &comment[2..comment.len() - 2]
1274 use shape::{Indent, Shape};
1278 let mut iter = CharClasses::new("//\n\n".chars());
1280 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
1281 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
1282 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
1283 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
1284 assert_eq!(None, iter.next());
1288 fn comment_code_slices() {
1289 let input = "code(); /* test */ 1 + 1";
1290 let mut iter = CommentCodeSlices::new(input);
1292 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
1294 (CodeCharKind::Comment, 8, "/* test */"),
1295 iter.next().unwrap()
1297 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
1298 assert_eq!(None, iter.next());
1302 fn comment_code_slices_two() {
1303 let input = "// comment\n test();";
1304 let mut iter = CommentCodeSlices::new(input);
1306 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
1308 (CodeCharKind::Comment, 0, "// comment\n"),
1309 iter.next().unwrap()
1312 (CodeCharKind::Normal, 11, " test();"),
1313 iter.next().unwrap()
1315 assert_eq!(None, iter.next());
1319 fn comment_code_slices_three() {
1320 let input = "1 // comment\n // comment2\n\n";
1321 let mut iter = CommentCodeSlices::new(input);
1323 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
1325 (CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
1326 iter.next().unwrap()
1328 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
1329 assert_eq!(None, iter.next());
1334 fn format_comments() {
1335 let mut config: ::config::Config = Default::default();
1336 config.set().wrap_comments(true);
1337 config.set().normalize_comments(true);
1339 let comment = rewrite_comment(" //test",
1341 Shape::legacy(100, Indent::new(0, 100)),
1343 assert_eq!("/* test */", comment);
1345 let comment = rewrite_comment("// comment on a",
1347 Shape::legacy(10, Indent::empty()),
1349 assert_eq!("// comment\n// on a", comment);
1351 let comment = rewrite_comment("// A multi line comment\n // between args.",
1353 Shape::legacy(60, Indent::new(0, 12)),
1355 assert_eq!("// A multi line comment\n // between args.", comment);
1357 let input = "// comment";
1360 let comment = rewrite_comment(input,
1362 Shape::legacy(9, Indent::new(0, 69)),
1364 assert_eq!(expected, comment);
1366 let comment = rewrite_comment("/* trimmed */",
1368 Shape::legacy(100, Indent::new(0, 100)),
1370 assert_eq!("/* trimmed */", comment);
1373 // This is probably intended to be a non-test fn, but it is not used. I'm
1374 // keeping it around unless it helps us test stuff.
1375 fn uncommented(text: &str) -> String {
1376 CharClasses::new(text.chars())
1377 .filter_map(|(s, c)| match s {
1378 FullCodeCharKind::Normal | FullCodeCharKind::InString => Some(c),
1384 fn test_uncommented() {
1385 assert_eq!(&uncommented("abc/*...*/"), "abc");
1387 &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
1390 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
1394 fn test_contains_comment() {
1395 assert_eq!(contains_comment("abc"), false);
1396 assert_eq!(contains_comment("abc // qsdf"), true);
1397 assert_eq!(contains_comment("abc /* kqsdf"), true);
1398 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
1402 fn test_find_uncommented() {
1403 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
1404 assert_eq!(expected, haystack.find_uncommented(needle));
1407 check("/*/ */test", "test", Some(6));
1408 check("//test\ntest", "test", Some(7));
1409 check("/* comment only */", "whatever", None);
1411 "/* comment */ some text /* more commentary */ result",
1415 check("sup // sup", "p", Some(2));
1416 check("sup", "x", None);
1417 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
1418 check("/*sup yo? \n sup*/ sup", "p", Some(20));
1419 check("hel/*lohello*/lo", "hello", None);
1420 check("acb", "ab", None);
1421 check(",/*A*/ ", ",", Some(0));
1422 check("abc", "abc", Some(0));
1423 check("/* abc */", "abc", None);
1424 check("/**/abc/* */", "abc", Some(4));
1425 check("\"/* abc */\"", "abc", Some(4));
1426 check("\"/* abc", "abc", Some(4));
1430 fn test_remove_trailing_white_spaces() {
1431 let s = format!(" r#\"\n test\n \"#");
1432 assert_eq!(remove_trailing_white_spaces(&s), s);
1436 fn test_filter_normal_code() {
1439 println!("hello, world");
1442 assert_eq!(s, filter_normal_code(s));
1443 let s_with_comment = r#"
1446 println!("hello, world");
1449 assert_eq!(s, filter_normal_code(s_with_comment));