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 /// Returns true if the commenting style covers a line only.
56 pub fn is_line_comment(&self) -> bool {
58 CommentStyle::DoubleSlash
59 | CommentStyle::TripleSlash
61 | CommentStyle::Custom(_) => true,
66 /// Returns true if the commenting style can span over multiple lines.
67 pub fn is_block_comment(&self) -> bool {
69 CommentStyle::SingleBullet | CommentStyle::DoubleBullet | CommentStyle::Exclamation => {
76 pub fn is_doc_comment(&self) -> bool {
78 CommentStyle::TripleSlash | CommentStyle::Doc => true,
83 pub fn opener(&self) -> &'a str {
85 CommentStyle::DoubleSlash => "// ",
86 CommentStyle::TripleSlash => "/// ",
87 CommentStyle::Doc => "//! ",
88 CommentStyle::SingleBullet => "/* ",
89 CommentStyle::DoubleBullet => "/** ",
90 CommentStyle::Exclamation => "/*! ",
91 CommentStyle::Custom(opener) => opener,
95 pub fn closer(&self) -> &'a str {
97 CommentStyle::DoubleSlash
98 | CommentStyle::TripleSlash
99 | CommentStyle::Custom(..)
100 | CommentStyle::Doc => "",
101 CommentStyle::DoubleBullet => " **/",
102 CommentStyle::SingleBullet | CommentStyle::Exclamation => " */",
106 pub fn line_start(&self) -> &'a str {
108 CommentStyle::DoubleSlash => "// ",
109 CommentStyle::TripleSlash => "/// ",
110 CommentStyle::Doc => "//! ",
111 CommentStyle::SingleBullet | CommentStyle::Exclamation => " * ",
112 CommentStyle::DoubleBullet => " ** ",
113 CommentStyle::Custom(opener) => opener,
117 pub fn to_str_tuplet(&self) -> (&'a str, &'a str, &'a str) {
118 (self.opener(), self.closer(), self.line_start())
122 fn comment_style(orig: &str, normalize_comments: bool) -> CommentStyle {
123 if !normalize_comments {
124 if orig.starts_with("/**") && !orig.starts_with("/**/") {
125 CommentStyle::DoubleBullet
126 } else if orig.starts_with("/*!") {
127 CommentStyle::Exclamation
128 } else if orig.starts_with("/*") {
129 CommentStyle::SingleBullet
130 } else if orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/') {
131 CommentStyle::TripleSlash
132 } else if orig.starts_with("//!") {
134 } else if is_custom_comment(orig) {
135 CommentStyle::Custom(custom_opener(orig))
137 CommentStyle::DoubleSlash
139 } else if (orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/'))
140 || (orig.starts_with("/**") && !orig.starts_with("/**/"))
142 CommentStyle::TripleSlash
143 } else if orig.starts_with("//!") || orig.starts_with("/*!") {
145 } else if is_custom_comment(orig) {
146 CommentStyle::Custom(custom_opener(orig))
148 CommentStyle::DoubleSlash
152 /// Combine `prev_str` and `next_str` into a single `String`. `span` may contain
153 /// comments between two strings. If there are such comments, then that will be
154 /// recovered. If `allow_extend` is true and there is no comment between the two
155 /// strings, then they will be put on a single line as long as doing so does not
156 /// exceed max width.
157 pub fn combine_strs_with_missing_comments(
158 context: &RewriteContext,
164 ) -> Option<String> {
166 String::with_capacity(prev_str.len() + next_str.len() + shape.indent.width() + 128);
167 result.push_str(prev_str);
168 let mut allow_one_line = !prev_str.contains('\n') && !next_str.contains('\n');
169 let first_sep = if prev_str.is_empty() || next_str.is_empty() {
174 let mut one_line_width =
175 last_line_width(prev_str) + first_line_width(next_str) + first_sep.len();
177 let config = context.config;
178 let indent = shape.indent;
179 let missing_comment = rewrite_missing_comment(span, shape, context)?;
181 if missing_comment.is_empty() {
182 if allow_extend && prev_str.len() + first_sep.len() + next_str.len() <= shape.width {
183 result.push_str(first_sep);
184 } else if !prev_str.is_empty() {
185 result.push_str(&indent.to_string_with_newline(config))
187 result.push_str(next_str);
191 // We have a missing comment between the first expression and the second expression.
193 // Peek the the original source code and find out whether there is a newline between the first
194 // expression and the second expression or the missing comment. We will preserve the original
195 // layout whenever possible.
196 let original_snippet = context.snippet(span);
197 let prefer_same_line = if let Some(pos) = original_snippet.find('/') {
198 !original_snippet[..pos].contains('\n')
200 !original_snippet.contains('\n')
203 one_line_width -= first_sep.len();
204 let first_sep = if prev_str.is_empty() || missing_comment.is_empty() {
207 let one_line_width = last_line_width(prev_str) + first_line_width(&missing_comment) + 1;
208 if prefer_same_line && one_line_width <= shape.width {
211 indent.to_string_with_newline(config)
214 result.push_str(&first_sep);
215 result.push_str(&missing_comment);
217 let second_sep = if missing_comment.is_empty() || next_str.is_empty() {
219 } else if missing_comment.starts_with("//") {
220 indent.to_string_with_newline(config)
222 one_line_width += missing_comment.len() + first_sep.len() + 1;
223 allow_one_line &= !missing_comment.starts_with("//") && !missing_comment.contains('\n');
224 if prefer_same_line && allow_one_line && one_line_width <= shape.width {
227 indent.to_string_with_newline(config)
230 result.push_str(&second_sep);
231 result.push_str(next_str);
236 pub fn rewrite_doc_comment(orig: &str, shape: Shape, config: &Config) -> Option<String> {
237 identify_comment(orig, false, shape, config, true)
240 pub fn rewrite_comment(
245 ) -> Option<String> {
246 identify_comment(orig, block_style, shape, config, false)
254 is_doc_comment: bool,
255 ) -> Option<String> {
256 let style = comment_style(orig, false);
258 // Computes the len of line taking into account a newline if the line is part of a paragraph.
259 fn compute_len(orig: &str, line: &str) -> usize {
260 if orig.len() > line.len() {
261 if orig.as_bytes()[line.len()] == b'\r' {
271 // Get the first group of line comments having the same commenting style.
273 // Returns a tuple with:
274 // - a boolean indicating if there is a blank line
275 // - a number indicating the size of the first group of comments
276 fn consume_same_line_comments(
281 let mut first_group_ending = 0;
284 for line in orig.lines() {
285 let trimmed_line = line.trim_left();
286 if trimmed_line.is_empty() {
289 } else if trimmed_line.starts_with(line_start)
290 || comment_style(trimmed_line, false) == style
292 first_group_ending += compute_len(&orig[first_group_ending..], line);
297 (hbl, first_group_ending)
300 let (has_bare_lines, first_group_ending) = match style {
301 CommentStyle::DoubleSlash | CommentStyle::TripleSlash | CommentStyle::Doc => {
302 let line_start = style.line_start().trim_left();
303 consume_same_line_comments(style, orig, line_start)
305 CommentStyle::Custom(opener) => {
306 let trimmed_opener = opener.trim_right();
307 consume_same_line_comments(style, orig, trimmed_opener)
309 // for a block comment, search for the closing symbol
310 CommentStyle::DoubleBullet | CommentStyle::SingleBullet | CommentStyle::Exclamation => {
311 let closer = style.closer().trim_left();
312 let mut closing_symbol_offset = 0;
314 for line in orig.lines() {
315 closing_symbol_offset += compute_len(&orig[closing_symbol_offset..], line);
316 let trimmed_line = line.trim_left();
317 if !trimmed_line.starts_with('*')
318 && !trimmed_line.starts_with("//")
319 && !trimmed_line.starts_with("/*")
323 if trimmed_line.ends_with(closer) {
327 (hbl, closing_symbol_offset)
331 let (first_group, rest) = orig.split_at(first_group_ending);
332 let rewritten_first_group =
333 if !config.normalize_comments() && has_bare_lines && style.is_block_comment() {
334 light_rewrite_block_comment_with_bare_lines(first_group, shape, config)?
335 } else if !config.normalize_comments() && !config.wrap_comments() {
336 light_rewrite_comment(first_group, shape.indent, config, is_doc_comment)?
338 rewrite_comment_inner(
344 is_doc_comment || style.is_doc_comment(),
348 Some(rewritten_first_group)
350 identify_comment(rest.trim_left(), block_style, shape, config, is_doc_comment).map(
354 rewritten_first_group,
355 // insert back the blank line
356 if has_bare_lines && style.is_line_comment() {
361 shape.indent.to_string(config),
369 /// Trims a minimum of leading whitespaces so that the content layout is kept and aligns to indent.
370 fn light_rewrite_block_comment_with_bare_lines(
374 ) -> Option<String> {
375 let prefix_whitespace_min = orig
377 // skip the line with the starting sigil since the leading whitespace is removed
378 // otherwise, the minimum would always be zero
380 .filter(|line| !line.is_empty())
383 for c in line.chars() {
386 '\t' => width += config.tab_spaces(),
394 let indent_str = shape.indent.to_string(config);
395 let mut lines = orig.lines();
396 let first_line = lines.next()?;
402 &line[prefix_whitespace_min..]
405 .collect::<Vec<&str>>()
406 .join(&format!("\n{}", indent_str));
407 Some(format!("{}\n{}{}", first_line, indent_str, rest))
410 /// Attributes for code blocks in rustdoc.
411 /// See https://doc.rust-lang.org/rustdoc/print.html#attributes
412 enum CodeBlockAttribute {
421 impl CodeBlockAttribute {
422 fn new(attribute: &str) -> CodeBlockAttribute {
424 "rust" | "" => CodeBlockAttribute::Rust,
425 "ignore" => CodeBlockAttribute::Ignore,
426 "text" => CodeBlockAttribute::Text,
427 "should_panic" => CodeBlockAttribute::ShouldPanic,
428 "no_run" => CodeBlockAttribute::NoRun,
429 "compile_fail" => CodeBlockAttribute::CompileFail,
430 _ => CodeBlockAttribute::Text,
435 fn rewrite_comment_inner(
441 is_doc_comment: bool,
442 ) -> Option<String> {
443 let (opener, closer, line_start) = if block_style {
444 CommentStyle::SingleBullet.to_str_tuplet()
446 comment_style(orig, config.normalize_comments()).to_str_tuplet()
449 let max_chars = shape
451 .checked_sub(closer.len() + opener.len())
453 let indent_str = shape.indent.to_string_with_newline(config);
454 let fmt_indent = shape.indent + (opener.len() - line_start.len());
455 let mut fmt = StringFormat {
460 shape: Shape::legacy(max_chars, fmt_indent),
465 let line_breaks = count_newlines(orig.trim_right());
469 .map(|(i, mut line)| {
470 line = trim_right_unless_two_whitespaces(line.trim_left(), is_doc_comment);
472 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
473 line = line[..(line.len() - 2)].trim_right();
478 .map(|s| left_trim_comment_line(s, &style))
479 .map(|(line, has_leading_whitespace)| {
480 if orig.starts_with("/*") && line_breaks == 0 {
483 has_leading_whitespace || config.normalize_comments(),
486 (line, has_leading_whitespace || config.normalize_comments())
490 let mut result = String::with_capacity(orig.len() * 2);
491 result.push_str(opener);
492 let mut code_block_buffer = String::with_capacity(128);
493 let mut is_prev_line_multi_line = false;
494 let mut code_block_attr = None;
495 let comment_line_separator = format!("{}{}", indent_str, line_start);
496 let join_code_block_with_comment_line_separator = |s: &str| {
497 let mut result = String::with_capacity(s.len() + 128);
498 let mut iter = s.lines().peekable();
499 while let Some(line) = iter.next() {
500 result.push_str(line);
501 result.push_str(match iter.peek() {
502 Some(next_line) if next_line.is_empty() => comment_line_separator.trim_right(),
503 Some(..) => &comment_line_separator,
510 for (i, (line, has_leading_whitespace)) in lines.enumerate() {
511 let is_last = i == count_newlines(orig);
513 if let Some(ref attr) = code_block_attr {
514 if line.starts_with("```") {
515 let code_block = match attr {
516 CodeBlockAttribute::Ignore | CodeBlockAttribute::Text => {
517 trim_custom_comment_prefix(&code_block_buffer)
519 _ if code_block_buffer.is_empty() => String::new(),
521 let mut config = config.clone();
522 config.set().wrap_comments(false);
523 match ::format_code_block(&code_block_buffer, &config) {
524 Some(ref s) => trim_custom_comment_prefix(s),
525 None => trim_custom_comment_prefix(&code_block_buffer),
529 if !code_block.is_empty() {
530 result.push_str(&comment_line_separator);
531 result.push_str(&join_code_block_with_comment_line_separator(&code_block));
533 code_block_buffer.clear();
534 result.push_str(&comment_line_separator);
535 result.push_str(line);
536 code_block_attr = None;
538 code_block_buffer.push_str(&hide_sharp_behind_comment(line));
539 code_block_buffer.push('\n');
542 // There is a code block that is not properly enclosed by backticks.
543 // We will leave them untouched.
544 result.push_str(&comment_line_separator);
545 result.push_str(&join_code_block_with_comment_line_separator(
546 &trim_custom_comment_prefix(&code_block_buffer),
553 code_block_attr = if line.starts_with("```") {
554 Some(CodeBlockAttribute::new(&line[3..]))
559 if result == opener {
560 let force_leading_whitespace = opener == "/* " && count_newlines(orig) == 0;
561 if !has_leading_whitespace && !force_leading_whitespace && result.ends_with(' ') {
567 } else if is_prev_line_multi_line && !line.is_empty() {
569 } else if is_last && line.is_empty() {
570 // trailing blank lines are unwanted
571 if !closer.is_empty() {
572 result.push_str(&indent_str);
576 result.push_str(&comment_line_separator);
577 if !has_leading_whitespace && result.ends_with(' ') {
583 if config.wrap_comments() && line.len() > fmt.shape.width && !has_url(line) {
584 match rewrite_string(line, &fmt) {
586 is_prev_line_multi_line = s.contains('\n');
589 None if is_prev_line_multi_line => {
590 // We failed to put the current `line` next to the previous `line`.
591 // Remove the trailing space, then start rewrite on the next line.
593 result.push_str(&comment_line_separator);
594 fmt.shape = Shape::legacy(max_chars, fmt_indent);
595 match rewrite_string(line, &fmt) {
597 is_prev_line_multi_line = s.contains('\n');
601 is_prev_line_multi_line = false;
602 result.push_str(line);
607 is_prev_line_multi_line = false;
608 result.push_str(line);
612 fmt.shape = if is_prev_line_multi_line {
614 let offset = 1 + last_line_width(&result) - line_start.len();
616 width: max_chars.saturating_sub(offset),
618 offset: fmt.shape.offset + offset,
621 Shape::legacy(max_chars, fmt_indent)
624 if line.is_empty() && result.ends_with(' ') && !is_last {
625 // Remove space if this is an empty comment or a doc comment.
628 result.push_str(line);
629 fmt.shape = Shape::legacy(max_chars, fmt_indent);
630 is_prev_line_multi_line = false;
634 result.push_str(closer);
635 if result.ends_with(opener) && opener.ends_with(' ') {
643 const RUSTFMT_CUSTOM_COMMENT_PREFIX: &str = "//#### ";
645 fn hide_sharp_behind_comment(s: &str) -> Cow<str> {
646 if s.trim_left().starts_with("# ") {
647 Cow::from(format!("{}{}", RUSTFMT_CUSTOM_COMMENT_PREFIX, s))
653 fn trim_custom_comment_prefix(s: &str) -> String {
656 let left_trimmed = line.trim_left();
657 if left_trimmed.starts_with(RUSTFMT_CUSTOM_COMMENT_PREFIX) {
658 left_trimmed.trim_left_matches(RUSTFMT_CUSTOM_COMMENT_PREFIX)
667 /// Returns true if the given string MAY include URLs or alike.
668 fn has_url(s: &str) -> bool {
669 // This function may return false positive, but should get its job done in most cases.
670 s.contains("https://") || s.contains("http://") || s.contains("ftp://") || s.contains("file://")
673 /// Given the span, rewrite the missing comment inside it if available.
674 /// Note that the given span must only include comments (or leading/trailing whitespaces).
675 pub fn rewrite_missing_comment(
678 context: &RewriteContext,
679 ) -> Option<String> {
680 let missing_snippet = context.snippet(span);
681 let trimmed_snippet = missing_snippet.trim();
682 if !trimmed_snippet.is_empty() {
683 rewrite_comment(trimmed_snippet, false, shape, context.config)
689 /// Recover the missing comments in the specified span, if available.
690 /// The layout of the comments will be preserved as long as it does not break the code
691 /// and its total width does not exceed the max width.
692 pub fn recover_missing_comment_in_span(
695 context: &RewriteContext,
697 ) -> Option<String> {
698 let missing_comment = rewrite_missing_comment(span, shape, context)?;
699 if missing_comment.is_empty() {
702 let missing_snippet = context.snippet(span);
703 let pos = missing_snippet.find('/').unwrap_or(0);
705 let total_width = missing_comment.len() + used_width + 1;
706 let force_new_line_before_comment =
707 missing_snippet[..pos].contains('\n') || total_width > context.config.max_width();
708 let sep = if force_new_line_before_comment {
709 shape.indent.to_string_with_newline(context.config)
713 Some(format!("{}{}", sep, missing_comment))
717 /// Trim trailing whitespaces unless they consist of two or more whitespaces.
718 fn trim_right_unless_two_whitespaces(s: &str, is_doc_comment: bool) -> &str {
719 if is_doc_comment && s.ends_with(" ") {
726 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
727 fn light_rewrite_comment(
731 is_doc_comment: bool,
732 ) -> Option<String> {
733 let lines: Vec<&str> = orig
736 // This is basically just l.trim(), but in the case that a line starts
737 // with `*` we want to leave one space before it, so it aligns with the
739 let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
740 let left_trimmed = if let Some(fnw) = first_non_whitespace {
741 if l.as_bytes()[fnw] == b'*' && fnw > 0 {
749 // Preserve markdown's double-space line break syntax in doc comment.
750 trim_right_unless_two_whitespaces(left_trimmed, is_doc_comment)
753 Some(lines.join(&format!("\n{}", offset.to_string(config))))
756 /// Trims comment characters and possibly a single space from the left of a string.
757 /// Does not trim all whitespace. If a single space is trimmed from the left of the string,
758 /// this function returns true.
759 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle) -> (&'a str, bool) {
760 if line.starts_with("//! ")
761 || line.starts_with("/// ")
762 || line.starts_with("/*! ")
763 || line.starts_with("/** ")
766 } else if let CommentStyle::Custom(opener) = *style {
767 if line.starts_with(opener) {
768 (&line[opener.len()..], true)
770 (&line[opener.trim_right().len()..], false)
772 } else if line.starts_with("/* ")
773 || line.starts_with("// ")
774 || line.starts_with("//!")
775 || line.starts_with("///")
776 || line.starts_with("** ")
777 || line.starts_with("/*!")
778 || (line.starts_with("/**") && !line.starts_with("/**/"))
780 (&line[3..], line.chars().nth(2).unwrap() == ' ')
781 } else if line.starts_with("/*")
782 || line.starts_with("* ")
783 || line.starts_with("//")
784 || line.starts_with("**")
786 (&line[2..], line.chars().nth(1).unwrap() == ' ')
787 } else if line.starts_with('*') {
790 (line, line.starts_with(' '))
794 pub trait FindUncommented {
795 fn find_uncommented(&self, pat: &str) -> Option<usize>;
798 impl FindUncommented for str {
799 fn find_uncommented(&self, pat: &str) -> Option<usize> {
800 let mut needle_iter = pat.chars();
801 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
802 match needle_iter.next() {
804 return Some(i - pat.len());
806 Some(c) => match kind {
807 FullCodeCharKind::Normal | FullCodeCharKind::InString if b == c => {}
809 needle_iter = pat.chars();
815 // Handle case where the pattern is a suffix of the search string
816 match needle_iter.next() {
818 None => Some(self.len() - pat.len()),
823 // Returns the first byte position after the first comment. The given string
824 // is expected to be prefixed by a comment, including delimiters.
825 // Good: "/* /* inner */ outer */ code();"
826 // Bad: "code(); // hello\n world!"
827 pub fn find_comment_end(s: &str) -> Option<usize> {
828 let mut iter = CharClasses::new(s.char_indices());
829 for (kind, (i, _c)) in &mut iter {
830 if kind == FullCodeCharKind::Normal || kind == FullCodeCharKind::InString {
835 // Handle case where the comment ends at the end of s.
836 if iter.status == CharClassesStatus::Normal {
843 /// Returns true if text contains any comment.
844 pub fn contains_comment(text: &str) -> bool {
845 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
848 /// Remove trailing spaces from the specified snippet. We do not remove spaces
849 /// inside strings or comments.
850 pub fn remove_trailing_white_spaces(text: &str) -> String {
851 let mut buffer = String::with_capacity(text.len());
852 let mut space_buffer = String::with_capacity(128);
853 for (char_kind, c) in CharClasses::new(text.chars()) {
856 if char_kind == FullCodeCharKind::InString {
857 buffer.push_str(&space_buffer);
859 space_buffer.clear();
862 _ if c.is_whitespace() => {
863 space_buffer.push(c);
866 if !space_buffer.is_empty() {
867 buffer.push_str(&space_buffer);
868 space_buffer.clear();
877 pub struct CharClasses<T>
883 status: CharClassesStatus,
887 fn get_char(&self) -> char;
890 impl RichChar for char {
891 fn get_char(&self) -> char {
896 impl RichChar for (usize, char) {
897 fn get_char(&self) -> char {
902 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
903 enum CharClassesStatus {
908 RawStringPrefix(u32),
909 RawStringSuffix(u32),
912 // The u32 is the nesting deepness of the comment
914 // Status when the '/' has been consumed, but not yet the '*', deepness is
915 // the new deepness (after the comment opening).
916 BlockCommentOpening(u32),
917 // Status when the '*' has been consumed, but not yet the '/', deepness is
918 // the new deepness (after the comment closing).
919 BlockCommentClosing(u32),
923 /// Distinguish between functional part of code and comments
924 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
925 pub enum CodeCharKind {
930 /// Distinguish between functional part of code and comments,
931 /// describing opening and closing of comments for ease when chunking
932 /// code from tagged characters
933 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
934 pub enum FullCodeCharKind {
936 /// The first character of a comment, there is only one for a comment (always '/')
938 /// Any character inside a comment including the second character of comment
939 /// marks ("//", "/*")
941 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
943 /// Start of a mutlitine string
945 /// End of a mutlitine string
951 impl FullCodeCharKind {
952 pub fn is_comment(self) -> bool {
954 FullCodeCharKind::StartComment
955 | FullCodeCharKind::InComment
956 | FullCodeCharKind::EndComment => true,
961 pub fn is_string(self) -> bool {
962 self == FullCodeCharKind::InString || self == FullCodeCharKind::StartString
965 fn to_codecharkind(self) -> CodeCharKind {
966 if self.is_comment() {
967 CodeCharKind::Comment
974 impl<T> CharClasses<T>
979 pub fn new(base: T) -> CharClasses<T> {
981 base: multipeek(base),
982 status: CharClassesStatus::Normal,
987 fn is_raw_string_suffix<T>(iter: &mut MultiPeek<T>, count: u32) -> bool
994 Some(c) if c.get_char() == '#' => continue,
1001 impl<T> Iterator for CharClasses<T>
1006 type Item = (FullCodeCharKind, T::Item);
1008 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
1009 let item = self.base.next()?;
1010 let chr = item.get_char();
1011 let mut char_kind = FullCodeCharKind::Normal;
1012 self.status = match self.status {
1013 CharClassesStatus::LitRawString(sharps) => {
1014 char_kind = FullCodeCharKind::InString;
1018 char_kind = FullCodeCharKind::Normal;
1019 CharClassesStatus::Normal
1020 } else if is_raw_string_suffix(&mut self.base, sharps) {
1021 CharClassesStatus::RawStringSuffix(sharps)
1023 CharClassesStatus::LitRawString(sharps)
1026 _ => CharClassesStatus::LitRawString(sharps),
1029 CharClassesStatus::RawStringPrefix(sharps) => {
1030 char_kind = FullCodeCharKind::InString;
1032 '#' => CharClassesStatus::RawStringPrefix(sharps + 1),
1033 '"' => CharClassesStatus::LitRawString(sharps),
1034 _ => CharClassesStatus::Normal, // Unreachable.
1037 CharClassesStatus::RawStringSuffix(sharps) => {
1041 CharClassesStatus::Normal
1043 char_kind = FullCodeCharKind::InString;
1044 CharClassesStatus::RawStringSuffix(sharps - 1)
1047 _ => CharClassesStatus::Normal, // Unreachable
1050 CharClassesStatus::LitString => {
1051 char_kind = FullCodeCharKind::InString;
1053 '"' => CharClassesStatus::Normal,
1054 '\\' => CharClassesStatus::LitStringEscape,
1055 _ => CharClassesStatus::LitString,
1058 CharClassesStatus::LitStringEscape => {
1059 char_kind = FullCodeCharKind::InString;
1060 CharClassesStatus::LitString
1062 CharClassesStatus::LitChar => match chr {
1063 '\\' => CharClassesStatus::LitCharEscape,
1064 '\'' => CharClassesStatus::Normal,
1065 _ => CharClassesStatus::LitChar,
1067 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
1068 CharClassesStatus::Normal => match chr {
1069 'r' => match self.base.peek().map(|c| c.get_char()) {
1070 Some('#') | Some('"') => {
1071 char_kind = FullCodeCharKind::InString;
1072 CharClassesStatus::RawStringPrefix(0)
1074 _ => CharClassesStatus::Normal,
1077 char_kind = FullCodeCharKind::InString;
1078 CharClassesStatus::LitString
1081 // HACK: Work around mut borrow.
1082 match self.base.peek() {
1083 Some(next) if next.get_char() == '\\' => {
1084 self.status = CharClassesStatus::LitChar;
1085 return Some((char_kind, item));
1090 match self.base.peek() {
1091 Some(next) if next.get_char() == '\'' => CharClassesStatus::LitChar,
1092 _ => CharClassesStatus::Normal,
1095 '/' => match self.base.peek() {
1096 Some(next) if next.get_char() == '*' => {
1097 self.status = CharClassesStatus::BlockCommentOpening(1);
1098 return Some((FullCodeCharKind::StartComment, item));
1100 Some(next) if next.get_char() == '/' => {
1101 self.status = CharClassesStatus::LineComment;
1102 return Some((FullCodeCharKind::StartComment, item));
1104 _ => CharClassesStatus::Normal,
1106 _ => CharClassesStatus::Normal,
1108 CharClassesStatus::BlockComment(deepness) => {
1109 assert_ne!(deepness, 0);
1110 self.status = match self.base.peek() {
1111 Some(next) if next.get_char() == '/' && chr == '*' => {
1112 CharClassesStatus::BlockCommentClosing(deepness - 1)
1114 Some(next) if next.get_char() == '*' && chr == '/' => {
1115 CharClassesStatus::BlockCommentOpening(deepness + 1)
1117 _ => CharClassesStatus::BlockComment(deepness),
1119 return Some((FullCodeCharKind::InComment, item));
1121 CharClassesStatus::BlockCommentOpening(deepness) => {
1122 assert_eq!(chr, '*');
1123 self.status = CharClassesStatus::BlockComment(deepness);
1124 return Some((FullCodeCharKind::InComment, item));
1126 CharClassesStatus::BlockCommentClosing(deepness) => {
1127 assert_eq!(chr, '/');
1129 self.status = CharClassesStatus::Normal;
1130 return Some((FullCodeCharKind::EndComment, item));
1132 self.status = CharClassesStatus::BlockComment(deepness);
1133 return Some((FullCodeCharKind::InComment, item));
1136 CharClassesStatus::LineComment => match chr {
1138 self.status = CharClassesStatus::Normal;
1139 return Some((FullCodeCharKind::EndComment, item));
1142 self.status = CharClassesStatus::LineComment;
1143 return Some((FullCodeCharKind::InComment, item));
1147 Some((char_kind, item))
1151 /// An iterator over the lines of a string, paired with the char kind at the
1152 /// end of the line.
1153 pub struct LineClasses<'a> {
1154 base: iter::Peekable<CharClasses<std::str::Chars<'a>>>,
1155 kind: FullCodeCharKind,
1158 impl<'a> LineClasses<'a> {
1159 pub fn new(s: &'a str) -> Self {
1161 base: CharClasses::new(s.chars()).peekable(),
1162 kind: FullCodeCharKind::Normal,
1167 impl<'a> Iterator for LineClasses<'a> {
1168 type Item = (FullCodeCharKind, String);
1170 fn next(&mut self) -> Option<Self::Item> {
1173 let mut line = String::new();
1175 let start_class = match self.base.peek() {
1176 Some((kind, _)) => *kind,
1177 None => FullCodeCharKind::Normal,
1180 while let Some((kind, c)) = self.base.next() {
1182 self.kind = match (start_class, kind) {
1183 (FullCodeCharKind::Normal, FullCodeCharKind::InString) => {
1184 FullCodeCharKind::StartString
1186 (FullCodeCharKind::InString, FullCodeCharKind::Normal) => {
1187 FullCodeCharKind::EndString
1197 Some((self.kind, line))
1201 /// Iterator over functional and commented parts of a string. Any part of a string is either
1202 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
1203 /// comments is functional code. Line comments contain their ending newlines.
1204 struct UngroupedCommentCodeSlices<'a> {
1206 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
1209 impl<'a> UngroupedCommentCodeSlices<'a> {
1210 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
1211 UngroupedCommentCodeSlices {
1213 iter: CharClasses::new(code.char_indices()).peekable(),
1218 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
1219 type Item = (CodeCharKind, usize, &'a str);
1221 fn next(&mut self) -> Option<Self::Item> {
1222 let (kind, (start_idx, _)) = self.iter.next()?;
1224 FullCodeCharKind::Normal | FullCodeCharKind::InString => {
1225 // Consume all the Normal code
1226 while let Some(&(char_kind, _)) = self.iter.peek() {
1227 if char_kind.is_comment() {
1230 let _ = self.iter.next();
1233 FullCodeCharKind::StartComment => {
1234 // Consume the whole comment
1235 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
1239 let slice = match self.iter.peek() {
1240 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
1241 None => &self.slice[start_idx..],
1244 if kind.is_comment() {
1245 CodeCharKind::Comment
1247 CodeCharKind::Normal
1255 /// Iterator over an alternating sequence of functional and commented parts of
1256 /// a string. The first item is always a, possibly zero length, subslice of
1257 /// functional text. Line style comments contain their ending newlines.
1258 pub struct CommentCodeSlices<'a> {
1260 last_slice_kind: CodeCharKind,
1261 last_slice_end: usize,
1264 impl<'a> CommentCodeSlices<'a> {
1265 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
1268 last_slice_kind: CodeCharKind::Comment,
1274 impl<'a> Iterator for CommentCodeSlices<'a> {
1275 type Item = (CodeCharKind, usize, &'a str);
1277 fn next(&mut self) -> Option<Self::Item> {
1278 if self.last_slice_end == self.slice.len() {
1282 let mut sub_slice_end = self.last_slice_end;
1283 let mut first_whitespace = None;
1284 let subslice = &self.slice[self.last_slice_end..];
1285 let mut iter = CharClasses::new(subslice.char_indices());
1287 for (kind, (i, c)) in &mut iter {
1288 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal
1289 && &subslice[..2] == "//"
1290 && [' ', '\t'].contains(&c);
1292 if is_comment_connector && first_whitespace.is_none() {
1293 first_whitespace = Some(i);
1296 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
1297 let last_index = match first_whitespace {
1301 sub_slice_end = self.last_slice_end + last_index;
1305 if !is_comment_connector {
1306 first_whitespace = None;
1310 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
1311 // This was the last subslice.
1312 sub_slice_end = match first_whitespace {
1313 Some(i) => self.last_slice_end + i,
1314 None => self.slice.len(),
1318 let kind = match self.last_slice_kind {
1319 CodeCharKind::Comment => CodeCharKind::Normal,
1320 CodeCharKind::Normal => CodeCharKind::Comment,
1324 self.last_slice_end,
1325 &self.slice[self.last_slice_end..sub_slice_end],
1327 self.last_slice_end = sub_slice_end;
1328 self.last_slice_kind = kind;
1334 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
1335 /// (if it fits in the width/offset, else return None), else return `new`
1336 pub fn recover_comment_removed(
1339 context: &RewriteContext,
1340 ) -> Option<String> {
1341 let snippet = context.snippet(span);
1342 if snippet != new && changed_comment_content(snippet, &new) {
1343 // We missed some comments. Warn and keep the original text.
1344 if context.config.error_on_unformatted() {
1345 context.report.append(
1346 context.source_map.span_to_filename(span).into(),
1347 vec![FormattingError::from_span(
1349 &context.source_map,
1350 ErrorKind::LostComment,
1354 Some(snippet.to_owned())
1360 pub fn filter_normal_code(code: &str) -> String {
1361 let mut buffer = String::with_capacity(code.len());
1362 LineClasses::new(code).for_each(|(kind, line)| match kind {
1363 FullCodeCharKind::Normal
1364 | FullCodeCharKind::StartString
1365 | FullCodeCharKind::InString
1366 | FullCodeCharKind::EndString => {
1367 buffer.push_str(&line);
1372 if !code.ends_with('\n') && buffer.ends_with('\n') {
1378 /// Return true if the two strings of code have the same payload of comments.
1379 /// The payload of comments is everything in the string except:
1380 /// - actual code (not comments)
1381 /// - comment start/end marks
1383 /// - '*' at the beginning of lines in block comments
1384 fn changed_comment_content(orig: &str, new: &str) -> bool {
1385 // Cannot write this as a fn since we cannot return types containing closures
1386 let code_comment_content = |code| {
1387 let slices = UngroupedCommentCodeSlices::new(code);
1389 .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
1390 .flat_map(|(_, _, s)| CommentReducer::new(s))
1392 let res = code_comment_content(orig).ne(code_comment_content(new));
1394 "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
1398 code_comment_content(orig).collect::<String>(),
1399 code_comment_content(new).collect::<String>()
1404 /// Iterator over the 'payload' characters of a comment.
1405 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
1406 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
1408 struct CommentReducer<'a> {
1410 at_start_line: bool,
1411 iter: std::str::Chars<'a>,
1414 impl<'a> CommentReducer<'a> {
1415 fn new(comment: &'a str) -> CommentReducer<'a> {
1416 let is_block = comment.starts_with("/*");
1417 let comment = remove_comment_header(comment);
1420 at_start_line: false, // There are no supplementary '*' on the first line
1421 iter: comment.chars(),
1426 impl<'a> Iterator for CommentReducer<'a> {
1429 fn next(&mut self) -> Option<Self::Item> {
1431 let mut c = self.iter.next()?;
1432 if self.is_block && self.at_start_line {
1433 while c.is_whitespace() {
1434 c = self.iter.next()?;
1436 // Ignore leading '*'
1438 c = self.iter.next()?;
1440 } else if c == '\n' {
1441 self.at_start_line = true;
1443 if !c.is_whitespace() {
1450 fn remove_comment_header(comment: &str) -> &str {
1451 if comment.starts_with("///") || comment.starts_with("//!") {
1453 } else if comment.starts_with("//") {
1455 } else if (comment.starts_with("/**") && !comment.starts_with("/**/"))
1456 || comment.starts_with("/*!")
1458 &comment[3..comment.len() - 2]
1461 comment.starts_with("/*"),
1462 format!("string '{}' is not a comment", comment)
1464 &comment[2..comment.len() - 2]
1471 use shape::{Indent, Shape};
1475 let mut iter = CharClasses::new("//\n\n".chars());
1477 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
1478 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
1479 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
1480 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
1481 assert_eq!(None, iter.next());
1485 fn comment_code_slices() {
1486 let input = "code(); /* test */ 1 + 1";
1487 let mut iter = CommentCodeSlices::new(input);
1489 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
1491 (CodeCharKind::Comment, 8, "/* test */"),
1492 iter.next().unwrap()
1494 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
1495 assert_eq!(None, iter.next());
1499 fn comment_code_slices_two() {
1500 let input = "// comment\n test();";
1501 let mut iter = CommentCodeSlices::new(input);
1503 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
1505 (CodeCharKind::Comment, 0, "// comment\n"),
1506 iter.next().unwrap()
1509 (CodeCharKind::Normal, 11, " test();"),
1510 iter.next().unwrap()
1512 assert_eq!(None, iter.next());
1516 fn comment_code_slices_three() {
1517 let input = "1 // comment\n // comment2\n\n";
1518 let mut iter = CommentCodeSlices::new(input);
1520 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
1522 (CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
1523 iter.next().unwrap()
1525 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
1526 assert_eq!(None, iter.next());
1531 fn format_comments() {
1532 let mut wrap_normalize_config: ::config::Config = Default::default();
1533 wrap_normalize_config.set().wrap_comments(true);
1534 wrap_normalize_config.set().normalize_comments(true);
1536 let mut wrap_config: ::config::Config = Default::default();
1537 wrap_config.set().wrap_comments(true);
1539 let comment = rewrite_comment(" //test",
1541 Shape::legacy(100, Indent::new(0, 100)),
1542 &wrap_normalize_config).unwrap();
1543 assert_eq!("/* test */", comment);
1545 let comment = rewrite_comment("// comment on a",
1547 Shape::legacy(10, Indent::empty()),
1548 &wrap_normalize_config).unwrap();
1549 assert_eq!("// comment\n// on a", comment);
1551 let comment = rewrite_comment("// A multi line comment\n // between args.",
1553 Shape::legacy(60, Indent::new(0, 12)),
1554 &wrap_normalize_config).unwrap();
1555 assert_eq!("// A multi line comment\n // between args.", comment);
1557 let input = "// comment";
1560 let comment = rewrite_comment(input,
1562 Shape::legacy(9, Indent::new(0, 69)),
1563 &wrap_normalize_config).unwrap();
1564 assert_eq!(expected, comment);
1566 let comment = rewrite_comment("/* trimmed */",
1568 Shape::legacy(100, Indent::new(0, 100)),
1569 &wrap_normalize_config).unwrap();
1570 assert_eq!("/* trimmed */", comment);
1572 // check that different comment style are properly recognised
1573 let comment = rewrite_comment(r#"/// test1
1579 Shape::legacy(100, Indent::new(0, 0)),
1580 &wrap_normalize_config).unwrap();
1581 assert_eq!("/// test1\n/// test2\n// test3", comment);
1583 // check that the blank line marks the end of a commented paragraph
1584 let comment = rewrite_comment(r#"// test1
1588 Shape::legacy(100, Indent::new(0, 0)),
1589 &wrap_normalize_config).unwrap();
1590 assert_eq!("// test1\n\n// test2", comment);
1592 // check that the blank line marks the end of a custom-commented paragraph
1593 let comment = rewrite_comment(r#"//@ test1
1597 Shape::legacy(100, Indent::new(0, 0)),
1598 &wrap_normalize_config).unwrap();
1599 assert_eq!("//@ test1\n\n//@ test2", comment);
1601 // check that bare lines are just indented but left unchanged otherwise
1602 let comment = rewrite_comment(r#"// test1
1609 Shape::legacy(100, Indent::new(0, 0)),
1610 &wrap_config).unwrap();
1611 assert_eq!("// test1\n/*\n a bare line!\n\n another bare line!\n*/", comment);
1614 // This is probably intended to be a non-test fn, but it is not used. I'm
1615 // keeping it around unless it helps us test stuff.
1616 fn uncommented(text: &str) -> String {
1617 CharClasses::new(text.chars())
1618 .filter_map(|(s, c)| match s {
1619 FullCodeCharKind::Normal | FullCodeCharKind::InString => Some(c),
1626 fn test_uncommented() {
1627 assert_eq!(&uncommented("abc/*...*/"), "abc");
1629 &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
1632 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
1636 fn test_contains_comment() {
1637 assert_eq!(contains_comment("abc"), false);
1638 assert_eq!(contains_comment("abc // qsdf"), true);
1639 assert_eq!(contains_comment("abc /* kqsdf"), true);
1640 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
1644 fn test_find_uncommented() {
1645 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
1646 assert_eq!(expected, haystack.find_uncommented(needle));
1649 check("/*/ */test", "test", Some(6));
1650 check("//test\ntest", "test", Some(7));
1651 check("/* comment only */", "whatever", None);
1653 "/* comment */ some text /* more commentary */ result",
1657 check("sup // sup", "p", Some(2));
1658 check("sup", "x", None);
1659 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
1660 check("/*sup yo? \n sup*/ sup", "p", Some(20));
1661 check("hel/*lohello*/lo", "hello", None);
1662 check("acb", "ab", None);
1663 check(",/*A*/ ", ",", Some(0));
1664 check("abc", "abc", Some(0));
1665 check("/* abc */", "abc", None);
1666 check("/**/abc/* */", "abc", Some(4));
1667 check("\"/* abc */\"", "abc", Some(4));
1668 check("\"/* abc", "abc", Some(4));
1672 fn test_remove_trailing_white_spaces() {
1673 let s = " r#\"\n test\n \"#";
1674 assert_eq!(remove_trailing_white_spaces(&s), s);
1678 fn test_filter_normal_code() {
1681 println!("hello, world");
1684 assert_eq!(s, filter_normal_code(s));
1685 let s_with_comment = r#"
1688 println!("hello, world");
1691 assert_eq!(s, filter_normal_code(s_with_comment));