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])
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();
374 .map(|s| left_trim_comment_line(s, &style))
375 .map(|(line, has_leading_whitespace)| {
376 if orig.starts_with("/*") && line_breaks == 0 {
379 has_leading_whitespace || config.normalize_comments(),
382 (line, has_leading_whitespace || config.normalize_comments())
386 let mut result = String::with_capacity(orig.len() * 2);
387 result.push_str(opener);
388 let mut code_block_buffer = String::with_capacity(128);
389 let mut is_prev_line_multi_line = false;
390 let mut inside_code_block = false;
391 let comment_line_separator = format!("{}{}", indent_str, line_start);
392 let join_code_block_with_comment_line_separator = |s: &str| {
393 let mut result = String::with_capacity(s.len() + 128);
394 let mut iter = s.lines().peekable();
395 while let Some(line) = iter.next() {
396 result.push_str(line);
397 result.push_str(match iter.peek() {
398 Some(next_line) if next_line.is_empty() => comment_line_separator.trim_right(),
399 Some(..) => &comment_line_separator,
406 for (i, (line, has_leading_whitespace)) in lines.enumerate() {
407 let is_last = i == count_newlines(orig);
409 if inside_code_block {
410 if line.starts_with("```") {
411 inside_code_block = false;
412 result.push_str(&comment_line_separator);
414 let mut config = config.clone();
415 config.set().wrap_comments(false);
416 match ::format_code_block(&code_block_buffer, &config) {
417 Some(ref s) => trim_custom_comment_prefix(s),
418 None => trim_custom_comment_prefix(&code_block_buffer),
421 result.push_str(&join_code_block_with_comment_line_separator(&code_block));
422 code_block_buffer.clear();
423 result.push_str(&comment_line_separator);
424 result.push_str(line);
426 code_block_buffer.push_str(&hide_sharp_behind_comment(line));
427 code_block_buffer.push('\n');
430 // There is an code block that is not properly enclosed by backticks.
431 // We will leave them untouched.
432 result.push_str(&comment_line_separator);
433 result.push_str(&join_code_block_with_comment_line_separator(
434 &trim_custom_comment_prefix(&code_block_buffer),
441 inside_code_block = line.starts_with("```");
443 if result == opener {
444 let force_leading_whitespace = opener == "/* " && count_newlines(orig) == 0;
445 if !has_leading_whitespace && !force_leading_whitespace && result.ends_with(' ') {
451 } else if is_prev_line_multi_line && !line.is_empty() {
453 } else if is_last && line.is_empty() {
454 // trailing blank lines are unwanted
455 if !closer.is_empty() {
456 result.push_str(&indent_str);
460 result.push_str(&comment_line_separator);
461 if !has_leading_whitespace && result.ends_with(' ') {
467 if config.wrap_comments() && line.len() > fmt.shape.width && !has_url(line) {
468 match rewrite_string(line, &fmt) {
470 is_prev_line_multi_line = s.contains('\n');
473 None if is_prev_line_multi_line => {
474 // We failed to put the current `line` next to the previous `line`.
475 // Remove the trailing space, then start rewrite on the next line.
477 result.push_str(&comment_line_separator);
478 fmt.shape = Shape::legacy(max_chars, fmt_indent);
479 match rewrite_string(line, &fmt) {
481 is_prev_line_multi_line = s.contains('\n');
485 is_prev_line_multi_line = false;
486 result.push_str(line);
491 is_prev_line_multi_line = false;
492 result.push_str(line);
496 fmt.shape = if is_prev_line_multi_line {
498 let offset = 1 + last_line_width(&result) - line_start.len();
500 width: max_chars.saturating_sub(offset),
502 offset: fmt.shape.offset + offset,
505 Shape::legacy(max_chars, fmt_indent)
508 if line.is_empty() && result.ends_with(' ') && !is_last {
509 // Remove space if this is an empty comment or a doc comment.
512 result.push_str(line);
513 fmt.shape = Shape::legacy(max_chars, fmt_indent);
514 is_prev_line_multi_line = false;
518 result.push_str(closer);
519 if result.ends_with(opener) && opener.ends_with(' ') {
527 const RUSTFMT_CUSTOM_COMMENT_PREFIX: &str = "//#### ";
529 fn hide_sharp_behind_comment(s: &str) -> Cow<str> {
530 if s.trim_left().starts_with("# ") {
531 Cow::from(format!("{}{}", RUSTFMT_CUSTOM_COMMENT_PREFIX, s))
537 fn trim_custom_comment_prefix(s: &str) -> String {
540 let left_trimmed = line.trim_left();
541 if left_trimmed.starts_with(RUSTFMT_CUSTOM_COMMENT_PREFIX) {
542 left_trimmed.trim_left_matches(RUSTFMT_CUSTOM_COMMENT_PREFIX)
551 /// Returns true if the given string MAY include URLs or alike.
552 fn has_url(s: &str) -> bool {
553 // This function may return false positive, but should get its job done in most cases.
554 s.contains("https://") || s.contains("http://") || s.contains("ftp://") || s.contains("file://")
557 /// Given the span, rewrite the missing comment inside it if available.
558 /// Note that the given span must only include comments (or leading/trailing whitespaces).
559 pub fn rewrite_missing_comment(
562 context: &RewriteContext,
563 ) -> Option<String> {
564 let missing_snippet = context.snippet(span);
565 let trimmed_snippet = missing_snippet.trim();
566 if !trimmed_snippet.is_empty() {
567 rewrite_comment(trimmed_snippet, false, shape, context.config)
573 /// Recover the missing comments in the specified span, if available.
574 /// The layout of the comments will be preserved as long as it does not break the code
575 /// and its total width does not exceed the max width.
576 pub fn recover_missing_comment_in_span(
579 context: &RewriteContext,
581 ) -> Option<String> {
582 let missing_comment = rewrite_missing_comment(span, shape, context)?;
583 if missing_comment.is_empty() {
586 let missing_snippet = context.snippet(span);
587 let pos = missing_snippet.find('/').unwrap_or(0);
589 let total_width = missing_comment.len() + used_width + 1;
590 let force_new_line_before_comment =
591 missing_snippet[..pos].contains('\n') || total_width > context.config.max_width();
592 let sep = if force_new_line_before_comment {
593 shape.indent.to_string_with_newline(context.config)
597 Some(format!("{}{}", sep, missing_comment))
601 /// Trim trailing whitespaces unless they consist of two or more whitespaces.
602 fn trim_right_unless_two_whitespaces(s: &str, is_doc_comment: bool) -> &str {
603 if is_doc_comment && s.ends_with(" ") {
610 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
611 fn light_rewrite_comment(
615 is_doc_comment: bool,
616 ) -> Option<String> {
617 let lines: Vec<&str> = orig
620 // This is basically just l.trim(), but in the case that a line starts
621 // with `*` we want to leave one space before it, so it aligns with the
623 let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
624 let left_trimmed = if let Some(fnw) = first_non_whitespace {
625 if l.as_bytes()[fnw] == b'*' && fnw > 0 {
633 // Preserve markdown's double-space line break syntax in doc comment.
634 trim_right_unless_two_whitespaces(left_trimmed, is_doc_comment)
637 Some(lines.join(&format!("\n{}", offset.to_string(config))))
640 /// Trims comment characters and possibly a single space from the left of a string.
641 /// Does not trim all whitespace. If a single space is trimmed from the left of the string,
642 /// this function returns true.
643 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle) -> (&'a str, bool) {
644 if line.starts_with("//! ")
645 || line.starts_with("/// ")
646 || line.starts_with("/*! ")
647 || line.starts_with("/** ")
650 } else if let CommentStyle::Custom(opener) = *style {
651 if line.starts_with(opener) {
652 (&line[opener.len()..], true)
654 (&line[opener.trim_right().len()..], false)
656 } else if line.starts_with("/* ")
657 || line.starts_with("// ")
658 || line.starts_with("//!")
659 || line.starts_with("///")
660 || line.starts_with("** ")
661 || line.starts_with("/*!")
662 || (line.starts_with("/**") && !line.starts_with("/**/"))
664 (&line[3..], line.chars().nth(2).unwrap() == ' ')
665 } else if line.starts_with("/*")
666 || line.starts_with("* ")
667 || line.starts_with("//")
668 || line.starts_with("**")
670 (&line[2..], line.chars().nth(1).unwrap() == ' ')
671 } else if line.starts_with('*') {
674 (line, line.starts_with(' '))
678 pub trait FindUncommented {
679 fn find_uncommented(&self, pat: &str) -> Option<usize>;
682 impl FindUncommented for str {
683 fn find_uncommented(&self, pat: &str) -> Option<usize> {
684 let mut needle_iter = pat.chars();
685 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
686 match needle_iter.next() {
688 return Some(i - pat.len());
690 Some(c) => match kind {
691 FullCodeCharKind::Normal | FullCodeCharKind::InString if b == c => {}
693 needle_iter = pat.chars();
699 // Handle case where the pattern is a suffix of the search string
700 match needle_iter.next() {
702 None => Some(self.len() - pat.len()),
707 // Returns the first byte position after the first comment. The given string
708 // is expected to be prefixed by a comment, including delimiters.
709 // Good: "/* /* inner */ outer */ code();"
710 // Bad: "code(); // hello\n world!"
711 pub fn find_comment_end(s: &str) -> Option<usize> {
712 let mut iter = CharClasses::new(s.char_indices());
713 for (kind, (i, _c)) in &mut iter {
714 if kind == FullCodeCharKind::Normal || kind == FullCodeCharKind::InString {
719 // Handle case where the comment ends at the end of s.
720 if iter.status == CharClassesStatus::Normal {
727 /// Returns true if text contains any comment.
728 pub fn contains_comment(text: &str) -> bool {
729 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
732 /// Remove trailing spaces from the specified snippet. We do not remove spaces
733 /// inside strings or comments.
734 pub fn remove_trailing_white_spaces(text: &str) -> String {
735 let mut buffer = String::with_capacity(text.len());
736 let mut space_buffer = String::with_capacity(128);
737 for (char_kind, c) in CharClasses::new(text.chars()) {
740 if char_kind == FullCodeCharKind::InString {
741 buffer.push_str(&space_buffer);
743 space_buffer.clear();
746 _ if c.is_whitespace() => {
747 space_buffer.push(c);
750 if !space_buffer.is_empty() {
751 buffer.push_str(&space_buffer);
752 space_buffer.clear();
761 pub struct CharClasses<T>
767 status: CharClassesStatus,
771 fn get_char(&self) -> char;
774 impl RichChar for char {
775 fn get_char(&self) -> char {
780 impl RichChar for (usize, char) {
781 fn get_char(&self) -> char {
786 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
787 enum CharClassesStatus {
792 RawStringPrefix(u32),
793 RawStringSuffix(u32),
796 // The u32 is the nesting deepness of the comment
798 // Status when the '/' has been consumed, but not yet the '*', deepness is
799 // the new deepness (after the comment opening).
800 BlockCommentOpening(u32),
801 // Status when the '*' has been consumed, but not yet the '/', deepness is
802 // the new deepness (after the comment closing).
803 BlockCommentClosing(u32),
807 /// Distinguish between functional part of code and comments
808 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
809 pub enum CodeCharKind {
814 /// Distinguish between functional part of code and comments,
815 /// describing opening and closing of comments for ease when chunking
816 /// code from tagged characters
817 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
818 pub enum FullCodeCharKind {
820 /// The first character of a comment, there is only one for a comment (always '/')
822 /// Any character inside a comment including the second character of comment
823 /// marks ("//", "/*")
825 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
827 /// Start of a mutlitine string
829 /// End of a mutlitine string
835 impl FullCodeCharKind {
836 pub fn is_comment(self) -> bool {
838 FullCodeCharKind::StartComment
839 | FullCodeCharKind::InComment
840 | FullCodeCharKind::EndComment => true,
845 pub fn is_string(self) -> bool {
846 self == FullCodeCharKind::InString || self == FullCodeCharKind::StartString
849 fn to_codecharkind(self) -> CodeCharKind {
850 if self.is_comment() {
851 CodeCharKind::Comment
858 impl<T> CharClasses<T>
863 pub fn new(base: T) -> CharClasses<T> {
865 base: multipeek(base),
866 status: CharClassesStatus::Normal,
871 fn is_raw_string_suffix<T>(iter: &mut MultiPeek<T>, count: u32) -> bool
878 Some(c) if c.get_char() == '#' => continue,
885 impl<T> Iterator for CharClasses<T>
890 type Item = (FullCodeCharKind, T::Item);
892 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
893 let item = self.base.next()?;
894 let chr = item.get_char();
895 let mut char_kind = FullCodeCharKind::Normal;
896 self.status = match self.status {
897 CharClassesStatus::LitRawString(sharps) => {
898 char_kind = FullCodeCharKind::InString;
902 char_kind = FullCodeCharKind::Normal;
903 CharClassesStatus::Normal
904 } else if is_raw_string_suffix(&mut self.base, sharps) {
905 CharClassesStatus::RawStringSuffix(sharps)
907 CharClassesStatus::LitRawString(sharps)
910 _ => CharClassesStatus::LitRawString(sharps),
913 CharClassesStatus::RawStringPrefix(sharps) => {
914 char_kind = FullCodeCharKind::InString;
916 '#' => CharClassesStatus::RawStringPrefix(sharps + 1),
917 '"' => CharClassesStatus::LitRawString(sharps),
918 _ => CharClassesStatus::Normal, // Unreachable.
921 CharClassesStatus::RawStringSuffix(sharps) => {
925 CharClassesStatus::Normal
927 char_kind = FullCodeCharKind::InString;
928 CharClassesStatus::RawStringSuffix(sharps - 1)
931 _ => CharClassesStatus::Normal, // Unreachable
934 CharClassesStatus::LitString => {
935 char_kind = FullCodeCharKind::InString;
937 '"' => CharClassesStatus::Normal,
938 '\\' => CharClassesStatus::LitStringEscape,
939 _ => CharClassesStatus::LitString,
942 CharClassesStatus::LitStringEscape => {
943 char_kind = FullCodeCharKind::InString;
944 CharClassesStatus::LitString
946 CharClassesStatus::LitChar => match chr {
947 '\\' => CharClassesStatus::LitCharEscape,
948 '\'' => CharClassesStatus::Normal,
949 _ => CharClassesStatus::LitChar,
951 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
952 CharClassesStatus::Normal => match chr {
953 'r' => match self.base.peek().map(|c| c.get_char()) {
954 Some('#') | Some('"') => {
955 char_kind = FullCodeCharKind::InString;
956 CharClassesStatus::RawStringPrefix(0)
958 _ => CharClassesStatus::Normal,
961 char_kind = FullCodeCharKind::InString;
962 CharClassesStatus::LitString
965 // HACK: Work around mut borrow.
966 match self.base.peek() {
967 Some(next) if next.get_char() == '\\' => {
968 self.status = CharClassesStatus::LitChar;
969 return Some((char_kind, item));
974 match self.base.peek() {
975 Some(next) if next.get_char() == '\'' => CharClassesStatus::LitChar,
976 _ => CharClassesStatus::Normal,
979 '/' => match self.base.peek() {
980 Some(next) if next.get_char() == '*' => {
981 self.status = CharClassesStatus::BlockCommentOpening(1);
982 return Some((FullCodeCharKind::StartComment, item));
984 Some(next) if next.get_char() == '/' => {
985 self.status = CharClassesStatus::LineComment;
986 return Some((FullCodeCharKind::StartComment, item));
988 _ => CharClassesStatus::Normal,
990 _ => CharClassesStatus::Normal,
992 CharClassesStatus::BlockComment(deepness) => {
993 assert_ne!(deepness, 0);
994 self.status = match self.base.peek() {
995 Some(next) if next.get_char() == '/' && chr == '*' => {
996 CharClassesStatus::BlockCommentClosing(deepness - 1)
998 Some(next) if next.get_char() == '*' && chr == '/' => {
999 CharClassesStatus::BlockCommentOpening(deepness + 1)
1001 _ => CharClassesStatus::BlockComment(deepness),
1003 return Some((FullCodeCharKind::InComment, item));
1005 CharClassesStatus::BlockCommentOpening(deepness) => {
1006 assert_eq!(chr, '*');
1007 self.status = CharClassesStatus::BlockComment(deepness);
1008 return Some((FullCodeCharKind::InComment, item));
1010 CharClassesStatus::BlockCommentClosing(deepness) => {
1011 assert_eq!(chr, '/');
1013 self.status = CharClassesStatus::Normal;
1014 return Some((FullCodeCharKind::EndComment, item));
1016 self.status = CharClassesStatus::BlockComment(deepness);
1017 return Some((FullCodeCharKind::InComment, item));
1020 CharClassesStatus::LineComment => match chr {
1022 self.status = CharClassesStatus::Normal;
1023 return Some((FullCodeCharKind::EndComment, item));
1026 self.status = CharClassesStatus::LineComment;
1027 return Some((FullCodeCharKind::InComment, item));
1031 Some((char_kind, item))
1035 /// An iterator over the lines of a string, paired with the char kind at the
1036 /// end of the line.
1037 pub struct LineClasses<'a> {
1038 base: iter::Peekable<CharClasses<std::str::Chars<'a>>>,
1039 kind: FullCodeCharKind,
1042 impl<'a> LineClasses<'a> {
1043 pub fn new(s: &'a str) -> Self {
1045 base: CharClasses::new(s.chars()).peekable(),
1046 kind: FullCodeCharKind::Normal,
1051 impl<'a> Iterator for LineClasses<'a> {
1052 type Item = (FullCodeCharKind, String);
1054 fn next(&mut self) -> Option<Self::Item> {
1057 let mut line = String::new();
1059 let start_class = match self.base.peek() {
1060 Some((kind, _)) => *kind,
1061 None => FullCodeCharKind::Normal,
1064 while let Some((kind, c)) = self.base.next() {
1066 self.kind = match (start_class, kind) {
1067 (FullCodeCharKind::Normal, FullCodeCharKind::InString) => {
1068 FullCodeCharKind::StartString
1070 (FullCodeCharKind::InString, FullCodeCharKind::Normal) => {
1071 FullCodeCharKind::EndString
1081 Some((self.kind, line))
1085 /// Iterator over functional and commented parts of a string. Any part of a string is either
1086 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
1087 /// comments is functional code. Line comments contain their ending newlines.
1088 struct UngroupedCommentCodeSlices<'a> {
1090 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
1093 impl<'a> UngroupedCommentCodeSlices<'a> {
1094 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
1095 UngroupedCommentCodeSlices {
1097 iter: CharClasses::new(code.char_indices()).peekable(),
1102 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
1103 type Item = (CodeCharKind, usize, &'a str);
1105 fn next(&mut self) -> Option<Self::Item> {
1106 let (kind, (start_idx, _)) = self.iter.next()?;
1108 FullCodeCharKind::Normal | FullCodeCharKind::InString => {
1109 // Consume all the Normal code
1110 while let Some(&(char_kind, _)) = self.iter.peek() {
1111 if char_kind.is_comment() {
1114 let _ = self.iter.next();
1117 FullCodeCharKind::StartComment => {
1118 // Consume the whole comment
1119 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
1123 let slice = match self.iter.peek() {
1124 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
1125 None => &self.slice[start_idx..],
1128 if kind.is_comment() {
1129 CodeCharKind::Comment
1131 CodeCharKind::Normal
1139 /// Iterator over an alternating sequence of functional and commented parts of
1140 /// a string. The first item is always a, possibly zero length, subslice of
1141 /// functional text. Line style comments contain their ending newlines.
1142 pub struct CommentCodeSlices<'a> {
1144 last_slice_kind: CodeCharKind,
1145 last_slice_end: usize,
1148 impl<'a> CommentCodeSlices<'a> {
1149 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
1152 last_slice_kind: CodeCharKind::Comment,
1158 impl<'a> Iterator for CommentCodeSlices<'a> {
1159 type Item = (CodeCharKind, usize, &'a str);
1161 fn next(&mut self) -> Option<Self::Item> {
1162 if self.last_slice_end == self.slice.len() {
1166 let mut sub_slice_end = self.last_slice_end;
1167 let mut first_whitespace = None;
1168 let subslice = &self.slice[self.last_slice_end..];
1169 let mut iter = CharClasses::new(subslice.char_indices());
1171 for (kind, (i, c)) in &mut iter {
1172 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal
1173 && &subslice[..2] == "//"
1174 && [' ', '\t'].contains(&c);
1176 if is_comment_connector && first_whitespace.is_none() {
1177 first_whitespace = Some(i);
1180 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
1181 let last_index = match first_whitespace {
1185 sub_slice_end = self.last_slice_end + last_index;
1189 if !is_comment_connector {
1190 first_whitespace = None;
1194 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
1195 // This was the last subslice.
1196 sub_slice_end = match first_whitespace {
1197 Some(i) => self.last_slice_end + i,
1198 None => self.slice.len(),
1202 let kind = match self.last_slice_kind {
1203 CodeCharKind::Comment => CodeCharKind::Normal,
1204 CodeCharKind::Normal => CodeCharKind::Comment,
1208 self.last_slice_end,
1209 &self.slice[self.last_slice_end..sub_slice_end],
1211 self.last_slice_end = sub_slice_end;
1212 self.last_slice_kind = kind;
1218 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
1219 /// (if it fits in the width/offset, else return None), else return `new`
1220 pub fn recover_comment_removed(
1223 context: &RewriteContext,
1224 ) -> Option<String> {
1225 let snippet = context.snippet(span);
1226 if snippet != new && changed_comment_content(snippet, &new) {
1227 // We missed some comments. Warn and keep the original text.
1228 if context.config.error_on_unformatted() {
1229 context.report.append(
1230 context.source_map.span_to_filename(span).into(),
1231 vec![FormattingError::from_span(
1233 &context.source_map,
1234 ErrorKind::LostComment,
1238 Some(snippet.to_owned())
1244 pub fn filter_normal_code(code: &str) -> String {
1245 let mut buffer = String::with_capacity(code.len());
1246 LineClasses::new(code).for_each(|(kind, line)| match kind {
1247 FullCodeCharKind::Normal
1248 | FullCodeCharKind::StartString
1249 | FullCodeCharKind::InString
1250 | FullCodeCharKind::EndString => {
1251 buffer.push_str(&line);
1256 if !code.ends_with('\n') && buffer.ends_with('\n') {
1262 /// Return true if the two strings of code have the same payload of comments.
1263 /// The payload of comments is everything in the string except:
1264 /// - actual code (not comments)
1265 /// - comment start/end marks
1267 /// - '*' at the beginning of lines in block comments
1268 fn changed_comment_content(orig: &str, new: &str) -> bool {
1269 // Cannot write this as a fn since we cannot return types containing closures
1270 let code_comment_content = |code| {
1271 let slices = UngroupedCommentCodeSlices::new(code);
1273 .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
1274 .flat_map(|(_, _, s)| CommentReducer::new(s))
1276 let res = code_comment_content(orig).ne(code_comment_content(new));
1278 "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
1282 code_comment_content(orig).collect::<String>(),
1283 code_comment_content(new).collect::<String>()
1288 /// Iterator over the 'payload' characters of a comment.
1289 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
1290 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
1292 struct CommentReducer<'a> {
1294 at_start_line: bool,
1295 iter: std::str::Chars<'a>,
1298 impl<'a> CommentReducer<'a> {
1299 fn new(comment: &'a str) -> CommentReducer<'a> {
1300 let is_block = comment.starts_with("/*");
1301 let comment = remove_comment_header(comment);
1304 at_start_line: false, // There are no supplementary '*' on the first line
1305 iter: comment.chars(),
1310 impl<'a> Iterator for CommentReducer<'a> {
1313 fn next(&mut self) -> Option<Self::Item> {
1315 let mut c = self.iter.next()?;
1316 if self.is_block && self.at_start_line {
1317 while c.is_whitespace() {
1318 c = self.iter.next()?;
1320 // Ignore leading '*'
1322 c = self.iter.next()?;
1324 } else if c == '\n' {
1325 self.at_start_line = true;
1327 if !c.is_whitespace() {
1334 fn remove_comment_header(comment: &str) -> &str {
1335 if comment.starts_with("///") || comment.starts_with("//!") {
1337 } else if comment.starts_with("//") {
1339 } else if (comment.starts_with("/**") && !comment.starts_with("/**/"))
1340 || comment.starts_with("/*!")
1342 &comment[3..comment.len() - 2]
1345 comment.starts_with("/*"),
1346 format!("string '{}' is not a comment", comment)
1348 &comment[2..comment.len() - 2]
1355 use shape::{Indent, Shape};
1359 let mut iter = CharClasses::new("//\n\n".chars());
1361 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
1362 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
1363 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
1364 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
1365 assert_eq!(None, iter.next());
1369 fn comment_code_slices() {
1370 let input = "code(); /* test */ 1 + 1";
1371 let mut iter = CommentCodeSlices::new(input);
1373 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
1375 (CodeCharKind::Comment, 8, "/* test */"),
1376 iter.next().unwrap()
1378 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
1379 assert_eq!(None, iter.next());
1383 fn comment_code_slices_two() {
1384 let input = "// comment\n test();";
1385 let mut iter = CommentCodeSlices::new(input);
1387 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
1389 (CodeCharKind::Comment, 0, "// comment\n"),
1390 iter.next().unwrap()
1393 (CodeCharKind::Normal, 11, " test();"),
1394 iter.next().unwrap()
1396 assert_eq!(None, iter.next());
1400 fn comment_code_slices_three() {
1401 let input = "1 // comment\n // comment2\n\n";
1402 let mut iter = CommentCodeSlices::new(input);
1404 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
1406 (CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
1407 iter.next().unwrap()
1409 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
1410 assert_eq!(None, iter.next());
1415 fn format_comments() {
1416 let mut config: ::config::Config = Default::default();
1417 config.set().wrap_comments(true);
1418 config.set().normalize_comments(true);
1420 let comment = rewrite_comment(" //test",
1422 Shape::legacy(100, Indent::new(0, 100)),
1424 assert_eq!("/* test */", comment);
1426 let comment = rewrite_comment("// comment on a",
1428 Shape::legacy(10, Indent::empty()),
1430 assert_eq!("// comment\n// on a", comment);
1432 let comment = rewrite_comment("// A multi line comment\n // between args.",
1434 Shape::legacy(60, Indent::new(0, 12)),
1436 assert_eq!("// A multi line comment\n // between args.", comment);
1438 let input = "// comment";
1441 let comment = rewrite_comment(input,
1443 Shape::legacy(9, Indent::new(0, 69)),
1445 assert_eq!(expected, comment);
1447 let comment = rewrite_comment("/* trimmed */",
1449 Shape::legacy(100, Indent::new(0, 100)),
1451 assert_eq!("/* trimmed */", comment);
1454 // This is probably intended to be a non-test fn, but it is not used. I'm
1455 // keeping it around unless it helps us test stuff.
1456 fn uncommented(text: &str) -> String {
1457 CharClasses::new(text.chars())
1458 .filter_map(|(s, c)| match s {
1459 FullCodeCharKind::Normal | FullCodeCharKind::InString => Some(c),
1466 fn test_uncommented() {
1467 assert_eq!(&uncommented("abc/*...*/"), "abc");
1469 &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
1472 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
1476 fn test_contains_comment() {
1477 assert_eq!(contains_comment("abc"), false);
1478 assert_eq!(contains_comment("abc // qsdf"), true);
1479 assert_eq!(contains_comment("abc /* kqsdf"), true);
1480 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
1484 fn test_find_uncommented() {
1485 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
1486 assert_eq!(expected, haystack.find_uncommented(needle));
1489 check("/*/ */test", "test", Some(6));
1490 check("//test\ntest", "test", Some(7));
1491 check("/* comment only */", "whatever", None);
1493 "/* comment */ some text /* more commentary */ result",
1497 check("sup // sup", "p", Some(2));
1498 check("sup", "x", None);
1499 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
1500 check("/*sup yo? \n sup*/ sup", "p", Some(20));
1501 check("hel/*lohello*/lo", "hello", None);
1502 check("acb", "ab", None);
1503 check(",/*A*/ ", ",", Some(0));
1504 check("abc", "abc", Some(0));
1505 check("/* abc */", "abc", None);
1506 check("/**/abc/* */", "abc", Some(4));
1507 check("\"/* abc */\"", "abc", Some(4));
1508 check("\"/* abc", "abc", Some(4));
1512 fn test_remove_trailing_white_spaces() {
1513 let s = " r#\"\n test\n \"#";
1514 assert_eq!(remove_trailing_white_spaces(&s), s);
1518 fn test_filter_normal_code() {
1521 println!("hello, world");
1524 assert_eq!(s, filter_normal_code(s));
1525 let s_with_comment = r#"
1528 println!("hello, world");
1531 assert_eq!(s, filter_normal_code(s_with_comment));