1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Formatting and tools for comments.
13 use std::{self, iter, borrow::Cow};
15 use syntax::codemap::Span;
18 use rewrite::RewriteContext;
19 use shape::{Indent, Shape};
20 use string::{rewrite_string, StringFormat};
21 use utils::{count_newlines, first_line_width, last_line_width};
23 fn is_custom_comment(comment: &str) -> bool {
24 if !comment.starts_with("//") {
26 } else if let Some(c) = comment.chars().nth(2) {
27 !c.is_alphanumeric() && !c.is_whitespace()
33 #[derive(Copy, Clone, PartialEq, Eq)]
34 pub enum CommentStyle<'a> {
44 fn custom_opener(s: &str) -> &str {
45 s.lines().next().map_or("", |first_line| {
48 .map_or(first_line, |space_index| &first_line[0..space_index + 1])
52 impl<'a> CommentStyle<'a> {
53 pub fn is_doc_comment(&self) -> bool {
55 CommentStyle::TripleSlash | CommentStyle::Doc => true,
60 pub fn opener(&self) -> &'a str {
62 CommentStyle::DoubleSlash => "// ",
63 CommentStyle::TripleSlash => "/// ",
64 CommentStyle::Doc => "//! ",
65 CommentStyle::SingleBullet => "/* ",
66 CommentStyle::DoubleBullet => "/** ",
67 CommentStyle::Exclamation => "/*! ",
68 CommentStyle::Custom(opener) => opener,
72 pub fn closer(&self) -> &'a str {
74 CommentStyle::DoubleSlash
75 | CommentStyle::TripleSlash
76 | CommentStyle::Custom(..)
77 | CommentStyle::Doc => "",
78 CommentStyle::DoubleBullet => " **/",
79 CommentStyle::SingleBullet | CommentStyle::Exclamation => " */",
83 pub fn line_start(&self) -> &'a str {
85 CommentStyle::DoubleSlash => "// ",
86 CommentStyle::TripleSlash => "/// ",
87 CommentStyle::Doc => "//! ",
88 CommentStyle::SingleBullet | CommentStyle::Exclamation => " * ",
89 CommentStyle::DoubleBullet => " ** ",
90 CommentStyle::Custom(opener) => opener,
94 pub fn to_str_tuplet(&self) -> (&'a str, &'a str, &'a str) {
95 (self.opener(), self.closer(), self.line_start())
98 pub fn line_with_same_comment_style(&self, line: &str, normalize_comments: bool) -> bool {
100 CommentStyle::DoubleSlash | CommentStyle::TripleSlash | CommentStyle::Doc => {
101 line.trim_left().starts_with(self.line_start().trim_left())
102 || comment_style(line, normalize_comments) == *self
104 CommentStyle::DoubleBullet | CommentStyle::SingleBullet | CommentStyle::Exclamation => {
105 line.trim_left().starts_with(self.closer().trim_left())
106 || line.trim_left().starts_with(self.line_start().trim_left())
107 || comment_style(line, normalize_comments) == *self
109 CommentStyle::Custom(opener) => line.trim_left().starts_with(opener.trim_right()),
114 fn comment_style(orig: &str, normalize_comments: bool) -> CommentStyle {
115 if !normalize_comments {
116 if orig.starts_with("/**") && !orig.starts_with("/**/") {
117 CommentStyle::DoubleBullet
118 } else if orig.starts_with("/*!") {
119 CommentStyle::Exclamation
120 } else if orig.starts_with("/*") {
121 CommentStyle::SingleBullet
122 } else if orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/') {
123 CommentStyle::TripleSlash
124 } else if orig.starts_with("//!") {
126 } else if is_custom_comment(orig) {
127 CommentStyle::Custom(custom_opener(orig))
129 CommentStyle::DoubleSlash
131 } else if (orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/'))
132 || (orig.starts_with("/**") && !orig.starts_with("/**/"))
134 CommentStyle::TripleSlash
135 } else if orig.starts_with("//!") || orig.starts_with("/*!") {
137 } else if is_custom_comment(orig) {
138 CommentStyle::Custom(custom_opener(orig))
140 CommentStyle::DoubleSlash
144 /// Combine `prev_str` and `next_str` into a single `String`. `span` may contain
145 /// comments between two strings. If there are such comments, then that will be
146 /// recovered. If `allow_extend` is true and there is no comment between the two
147 /// strings, then they will be put on a single line as long as doing so does not
148 /// exceed max width.
149 pub fn combine_strs_with_missing_comments(
150 context: &RewriteContext,
156 ) -> Option<String> {
158 String::with_capacity(prev_str.len() + next_str.len() + shape.indent.width() + 128);
159 result.push_str(prev_str);
160 let mut allow_one_line = !prev_str.contains('\n') && !next_str.contains('\n');
161 let first_sep = if prev_str.is_empty() || next_str.is_empty() {
166 let mut one_line_width =
167 last_line_width(prev_str) + first_line_width(next_str) + first_sep.len();
169 let config = context.config;
170 let indent = shape.indent;
171 let missing_comment = rewrite_missing_comment(span, shape, context)?;
173 if missing_comment.is_empty() {
174 if allow_extend && prev_str.len() + first_sep.len() + next_str.len() <= shape.width {
175 result.push_str(first_sep);
176 } else if !prev_str.is_empty() {
177 result.push_str(&indent.to_string_with_newline(config))
179 result.push_str(next_str);
183 // We have a missing comment between the first expression and the second expression.
185 // Peek the the original source code and find out whether there is a newline between the first
186 // expression and the second expression or the missing comment. We will preserve the original
187 // layout whenever possible.
188 let original_snippet = context.snippet(span);
189 let prefer_same_line = if let Some(pos) = original_snippet.chars().position(|c| c == '/') {
190 !original_snippet[..pos].contains('\n')
192 !original_snippet.contains('\n')
195 one_line_width -= first_sep.len();
196 let first_sep = if prev_str.is_empty() || missing_comment.is_empty() {
199 let one_line_width = last_line_width(prev_str) + first_line_width(&missing_comment) + 1;
200 if prefer_same_line && one_line_width <= shape.width {
203 indent.to_string_with_newline(config)
206 result.push_str(&first_sep);
207 result.push_str(&missing_comment);
209 let second_sep = if missing_comment.is_empty() || next_str.is_empty() {
211 } else if missing_comment.starts_with("//") {
212 indent.to_string_with_newline(config)
214 one_line_width += missing_comment.len() + first_sep.len() + 1;
215 allow_one_line &= !missing_comment.starts_with("//") && !missing_comment.contains('\n');
216 if prefer_same_line && allow_one_line && one_line_width <= shape.width {
219 indent.to_string_with_newline(config)
222 result.push_str(&second_sep);
223 result.push_str(next_str);
228 pub fn rewrite_doc_comment(orig: &str, shape: Shape, config: &Config) -> Option<String> {
229 _rewrite_comment(orig, false, shape, config, true)
232 pub fn rewrite_comment(
237 ) -> Option<String> {
238 _rewrite_comment(orig, block_style, shape, config, false)
246 is_doc_comment: bool,
247 ) -> Option<String> {
248 // If there are lines without a starting sigil, we won't format them correctly
249 // so in that case we won't even re-align (if !config.normalize_comments()) and
250 // we should stop now.
251 let num_bare_lines = orig.lines()
252 .map(|line| line.trim())
253 .filter(|l| !(l.starts_with('*') || l.starts_with("//") || l.starts_with("/*")))
255 if num_bare_lines > 0 && !config.normalize_comments() {
256 return Some(orig.to_owned());
258 if !config.normalize_comments() && !config.wrap_comments() {
259 return light_rewrite_comment(orig, shape.indent, config, is_doc_comment);
262 identify_comment(orig, block_style, shape, config, is_doc_comment)
270 is_doc_comment: bool,
271 ) -> Option<String> {
272 let style = comment_style(orig, false);
273 let first_group = orig.lines()
274 .take_while(|l| style.line_with_same_comment_style(l, false))
277 let rest = orig.lines()
278 .skip(first_group.lines().count())
282 let first_group_str = rewrite_comment_inner(
288 is_doc_comment || style.is_doc_comment(),
291 Some(first_group_str)
293 identify_comment(&rest, block_style, shape, config, is_doc_comment).map(|rest_str| {
297 shape.indent.to_string(config),
304 fn rewrite_comment_inner(
310 is_doc_comment: bool,
311 ) -> Option<String> {
312 let (opener, closer, line_start) = if block_style {
313 CommentStyle::SingleBullet.to_str_tuplet()
315 comment_style(orig, config.normalize_comments()).to_str_tuplet()
318 let max_chars = shape
320 .checked_sub(closer.len() + opener.len())
322 let indent_str = shape.indent.to_string_with_newline(config);
323 let fmt_indent = shape.indent + (opener.len() - line_start.len());
324 let mut fmt = StringFormat {
329 shape: Shape::legacy(max_chars, fmt_indent),
334 let line_breaks = count_newlines(orig.trim_right());
335 let lines = orig.lines()
337 .map(|(i, mut line)| {
338 line = trim_right_unless_two_whitespaces(line.trim_left(), is_doc_comment);
340 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
341 line = line[..(line.len() - 2)].trim_right();
346 .map(|s| left_trim_comment_line(s, &style))
347 .map(|(line, has_leading_whitespace)| {
348 if orig.starts_with("/*") && line_breaks == 0 {
351 has_leading_whitespace || config.normalize_comments(),
354 (line, has_leading_whitespace || config.normalize_comments())
358 let mut result = String::with_capacity(orig.len() * 2);
359 result.push_str(opener);
360 let mut code_block_buffer = String::with_capacity(128);
361 let mut is_prev_line_multi_line = false;
362 let mut inside_code_block = false;
363 let comment_line_separator = format!("{}{}", indent_str, line_start);
364 let join_code_block_with_comment_line_separator = |s: &str| {
365 let mut result = String::with_capacity(s.len() + 128);
366 let mut iter = s.lines().peekable();
367 while let Some(line) = iter.next() {
368 result.push_str(line);
369 result.push_str(match iter.peek() {
370 Some(next_line) if next_line.is_empty() => comment_line_separator.trim_right(),
371 Some(..) => &comment_line_separator,
378 for (i, (line, has_leading_whitespace)) in lines.enumerate() {
379 let is_last = i == count_newlines(orig);
381 if inside_code_block {
382 if line.starts_with("```") {
383 inside_code_block = false;
384 result.push_str(&comment_line_separator);
385 let code_block = ::format_code_block(&code_block_buffer, config)
386 .unwrap_or_else(|| code_block_buffer.to_owned());
387 result.push_str(&join_code_block_with_comment_line_separator(&code_block));
388 code_block_buffer.clear();
389 result.push_str(&comment_line_separator);
390 result.push_str(line);
392 code_block_buffer.push_str(line);
393 code_block_buffer.push('\n');
398 inside_code_block = line.starts_with("```rust");
400 if result == opener {
401 let force_leading_whitespace = opener == "/* " && count_newlines(orig) == 0;
402 if !has_leading_whitespace && !force_leading_whitespace && result.ends_with(' ') {
408 } else if is_prev_line_multi_line && !line.is_empty() {
410 } else if is_last && !closer.is_empty() && line.is_empty() {
411 result.push_str(&indent_str);
413 result.push_str(&comment_line_separator);
414 if !has_leading_whitespace && result.ends_with(' ') {
420 if config.wrap_comments() && line.len() > fmt.shape.width && !has_url(line) {
421 match rewrite_string(line, &fmt, Some(max_chars)) {
423 is_prev_line_multi_line = s.contains('\n');
426 None if is_prev_line_multi_line => {
427 // We failed to put the current `line` next to the previous `line`.
428 // Remove the trailing space, then start rewrite on the next line.
430 result.push_str(&comment_line_separator);
431 fmt.shape = Shape::legacy(max_chars, fmt_indent);
432 match rewrite_string(line, &fmt, Some(max_chars)) {
434 is_prev_line_multi_line = s.contains('\n');
438 is_prev_line_multi_line = false;
439 result.push_str(line);
444 is_prev_line_multi_line = false;
445 result.push_str(line);
449 fmt.shape = if is_prev_line_multi_line {
451 let offset = 1 + last_line_width(&result) - line_start.len();
453 width: max_chars.checked_sub(offset).unwrap_or(0),
455 offset: fmt.shape.offset + offset,
458 Shape::legacy(max_chars, fmt_indent)
461 if line.is_empty() && result.ends_with(' ') && !is_last {
462 // Remove space if this is an empty comment or a doc comment.
465 result.push_str(line);
466 fmt.shape = Shape::legacy(max_chars, fmt_indent);
467 is_prev_line_multi_line = false;
471 result.push_str(closer);
472 if result.ends_with(opener) && opener.ends_with(' ') {
480 /// Returns true if the given string MAY include URLs or alike.
481 fn has_url(s: &str) -> bool {
482 // This function may return false positive, but should get its job done in most cases.
483 s.contains("https://") || s.contains("http://") || s.contains("ftp://") || s.contains("file://")
486 /// Given the span, rewrite the missing comment inside it if available.
487 /// Note that the given span must only include comments (or leading/trailing whitespaces).
488 pub fn rewrite_missing_comment(
491 context: &RewriteContext,
492 ) -> Option<String> {
493 let missing_snippet = context.snippet(span);
494 let trimmed_snippet = missing_snippet.trim();
495 if !trimmed_snippet.is_empty() {
496 rewrite_comment(trimmed_snippet, false, shape, context.config)
502 /// Recover the missing comments in the specified span, if available.
503 /// The layout of the comments will be preserved as long as it does not break the code
504 /// and its total width does not exceed the max width.
505 pub fn recover_missing_comment_in_span(
508 context: &RewriteContext,
510 ) -> Option<String> {
511 let missing_comment = rewrite_missing_comment(span, shape, context)?;
512 if missing_comment.is_empty() {
515 let missing_snippet = context.snippet(span);
516 let pos = missing_snippet.chars().position(|c| c == '/').unwrap_or(0);
518 let total_width = missing_comment.len() + used_width + 1;
519 let force_new_line_before_comment =
520 missing_snippet[..pos].contains('\n') || total_width > context.config.max_width();
521 let sep = if force_new_line_before_comment {
522 shape.indent.to_string_with_newline(context.config)
526 Some(format!("{}{}", sep, missing_comment))
530 /// Trim trailing whitespaces unless they consist of two or more whitespaces.
531 fn trim_right_unless_two_whitespaces(s: &str, is_doc_comment: bool) -> &str {
532 if is_doc_comment && s.ends_with(" ") {
539 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
540 fn light_rewrite_comment(
544 is_doc_comment: bool,
545 ) -> Option<String> {
546 let lines: Vec<&str> = orig.lines()
548 // This is basically just l.trim(), but in the case that a line starts
549 // with `*` we want to leave one space before it, so it aligns with the
551 let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
552 let left_trimmed = if let Some(fnw) = first_non_whitespace {
553 if l.as_bytes()[fnw] == b'*' && fnw > 0 {
561 // Preserve markdown's double-space line break syntax in doc comment.
562 trim_right_unless_two_whitespaces(left_trimmed, is_doc_comment)
565 Some(lines.join(&format!("\n{}", offset.to_string(config))))
568 /// Trims comment characters and possibly a single space from the left of a string.
569 /// Does not trim all whitespace. If a single space is trimmed from the left of the string,
570 /// this function returns true.
571 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle) -> (&'a str, bool) {
572 if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ")
573 || line.starts_with("/** ")
576 } else if let CommentStyle::Custom(opener) = *style {
577 if line.starts_with(opener) {
578 (&line[opener.len()..], true)
580 (&line[opener.trim_right().len()..], false)
582 } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!")
583 || line.starts_with("///") || line.starts_with("** ")
584 || line.starts_with("/*!")
585 || (line.starts_with("/**") && !line.starts_with("/**/"))
587 (&line[3..], line.chars().nth(2).unwrap() == ' ')
588 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//")
589 || line.starts_with("**")
591 (&line[2..], line.chars().nth(1).unwrap() == ' ')
592 } else if line.starts_with('*') {
595 (line, line.starts_with(' '))
599 pub trait FindUncommented {
600 fn find_uncommented(&self, pat: &str) -> Option<usize>;
603 impl FindUncommented for str {
604 fn find_uncommented(&self, pat: &str) -> Option<usize> {
605 let mut needle_iter = pat.chars();
606 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
607 match needle_iter.next() {
609 return Some(i - pat.len());
611 Some(c) => match kind {
612 FullCodeCharKind::Normal | FullCodeCharKind::InString if b == c => {}
614 needle_iter = pat.chars();
620 // Handle case where the pattern is a suffix of the search string
621 match needle_iter.next() {
623 None => Some(self.len() - pat.len()),
628 // Returns the first byte position after the first comment. The given string
629 // is expected to be prefixed by a comment, including delimiters.
630 // Good: "/* /* inner */ outer */ code();"
631 // Bad: "code(); // hello\n world!"
632 pub fn find_comment_end(s: &str) -> Option<usize> {
633 let mut iter = CharClasses::new(s.char_indices());
634 for (kind, (i, _c)) in &mut iter {
635 if kind == FullCodeCharKind::Normal || kind == FullCodeCharKind::InString {
640 // Handle case where the comment ends at the end of s.
641 if iter.status == CharClassesStatus::Normal {
648 /// Returns true if text contains any comment.
649 pub fn contains_comment(text: &str) -> bool {
650 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
653 /// Remove trailing spaces from the specified snippet. We do not remove spaces
654 /// inside strings or comments.
655 pub fn remove_trailing_white_spaces(text: &str) -> String {
656 let mut buffer = String::with_capacity(text.len());
657 let mut space_buffer = String::with_capacity(128);
658 for (char_kind, c) in CharClasses::new(text.chars()) {
661 if char_kind == FullCodeCharKind::InString {
662 buffer.push_str(&space_buffer);
664 space_buffer.clear();
667 _ if c.is_whitespace() => {
668 space_buffer.push(c);
671 if !space_buffer.is_empty() {
672 buffer.push_str(&space_buffer);
673 space_buffer.clear();
682 pub struct CharClasses<T>
687 base: iter::Peekable<T>,
688 status: CharClassesStatus,
692 fn get_char(&self) -> char;
695 impl RichChar for char {
696 fn get_char(&self) -> char {
701 impl RichChar for (usize, char) {
702 fn get_char(&self) -> char {
707 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
708 enum CharClassesStatus {
714 // The u32 is the nesting deepness of the comment
716 // Status when the '/' has been consumed, but not yet the '*', deepness is
717 // the new deepness (after the comment opening).
718 BlockCommentOpening(u32),
719 // Status when the '*' has been consumed, but not yet the '/', deepness is
720 // the new deepness (after the comment closing).
721 BlockCommentClosing(u32),
725 /// Distinguish between functional part of code and comments
726 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
727 pub enum CodeCharKind {
732 /// Distinguish between functional part of code and comments,
733 /// describing opening and closing of comments for ease when chunking
734 /// code from tagged characters
735 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
736 pub enum FullCodeCharKind {
738 /// The first character of a comment, there is only one for a comment (always '/')
740 /// Any character inside a comment including the second character of comment
741 /// marks ("//", "/*")
743 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
749 impl FullCodeCharKind {
750 pub fn is_comment(&self) -> bool {
752 FullCodeCharKind::StartComment
753 | FullCodeCharKind::InComment
754 | FullCodeCharKind::EndComment => true,
759 pub fn is_string(&self) -> bool {
760 *self == FullCodeCharKind::InString
763 fn to_codecharkind(&self) -> CodeCharKind {
764 if self.is_comment() {
765 CodeCharKind::Comment
772 impl<T> CharClasses<T>
777 pub fn new(base: T) -> CharClasses<T> {
779 base: base.peekable(),
780 status: CharClassesStatus::Normal,
785 impl<T> Iterator for CharClasses<T>
790 type Item = (FullCodeCharKind, T::Item);
792 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
793 let item = self.base.next()?;
794 let chr = item.get_char();
795 let mut char_kind = FullCodeCharKind::Normal;
796 self.status = match self.status {
797 CharClassesStatus::LitString => match chr {
798 '"' => CharClassesStatus::Normal,
800 char_kind = FullCodeCharKind::InString;
801 CharClassesStatus::LitStringEscape
804 char_kind = FullCodeCharKind::InString;
805 CharClassesStatus::LitString
808 CharClassesStatus::LitStringEscape => {
809 char_kind = FullCodeCharKind::InString;
810 CharClassesStatus::LitString
812 CharClassesStatus::LitChar => match chr {
813 '\\' => CharClassesStatus::LitCharEscape,
814 '\'' => CharClassesStatus::Normal,
815 _ => CharClassesStatus::LitChar,
817 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
818 CharClassesStatus::Normal => match chr {
820 char_kind = FullCodeCharKind::InString;
821 CharClassesStatus::LitString
823 '\'' => CharClassesStatus::LitChar,
824 '/' => match self.base.peek() {
825 Some(next) if next.get_char() == '*' => {
826 self.status = CharClassesStatus::BlockCommentOpening(1);
827 return Some((FullCodeCharKind::StartComment, item));
829 Some(next) if next.get_char() == '/' => {
830 self.status = CharClassesStatus::LineComment;
831 return Some((FullCodeCharKind::StartComment, item));
833 _ => CharClassesStatus::Normal,
835 _ => CharClassesStatus::Normal,
837 CharClassesStatus::BlockComment(deepness) => {
838 assert_ne!(deepness, 0);
839 self.status = match self.base.peek() {
840 Some(next) if next.get_char() == '/' && chr == '*' => {
841 CharClassesStatus::BlockCommentClosing(deepness - 1)
843 Some(next) if next.get_char() == '*' && chr == '/' => {
844 CharClassesStatus::BlockCommentOpening(deepness + 1)
846 _ => CharClassesStatus::BlockComment(deepness),
848 return Some((FullCodeCharKind::InComment, item));
850 CharClassesStatus::BlockCommentOpening(deepness) => {
851 assert_eq!(chr, '*');
852 self.status = CharClassesStatus::BlockComment(deepness);
853 return Some((FullCodeCharKind::InComment, item));
855 CharClassesStatus::BlockCommentClosing(deepness) => {
856 assert_eq!(chr, '/');
858 self.status = CharClassesStatus::Normal;
859 return Some((FullCodeCharKind::EndComment, item));
861 self.status = CharClassesStatus::BlockComment(deepness);
862 return Some((FullCodeCharKind::InComment, item));
865 CharClassesStatus::LineComment => match chr {
867 self.status = CharClassesStatus::Normal;
868 return Some((FullCodeCharKind::EndComment, item));
871 self.status = CharClassesStatus::LineComment;
872 return Some((FullCodeCharKind::InComment, item));
876 Some((char_kind, item))
880 /// Iterator over functional and commented parts of a string. Any part of a string is either
881 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
882 /// comments is functional code. Line comments contain their ending newlines.
883 struct UngroupedCommentCodeSlices<'a> {
885 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
888 impl<'a> UngroupedCommentCodeSlices<'a> {
889 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
890 UngroupedCommentCodeSlices {
892 iter: CharClasses::new(code.char_indices()).peekable(),
897 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
898 type Item = (CodeCharKind, usize, &'a str);
900 fn next(&mut self) -> Option<Self::Item> {
901 let (kind, (start_idx, _)) = self.iter.next()?;
903 FullCodeCharKind::Normal | FullCodeCharKind::InString => {
904 // Consume all the Normal code
905 while let Some(&(char_kind, _)) = self.iter.peek() {
906 if char_kind.is_comment() {
909 let _ = self.iter.next();
912 FullCodeCharKind::StartComment => {
913 // Consume the whole comment
914 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
918 let slice = match self.iter.peek() {
919 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
920 None => &self.slice[start_idx..],
923 if kind.is_comment() {
924 CodeCharKind::Comment
934 /// Iterator over an alternating sequence of functional and commented parts of
935 /// a string. The first item is always a, possibly zero length, subslice of
936 /// functional text. Line style comments contain their ending newlines.
937 pub struct CommentCodeSlices<'a> {
939 last_slice_kind: CodeCharKind,
940 last_slice_end: usize,
943 impl<'a> CommentCodeSlices<'a> {
944 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
947 last_slice_kind: CodeCharKind::Comment,
953 impl<'a> Iterator for CommentCodeSlices<'a> {
954 type Item = (CodeCharKind, usize, &'a str);
956 fn next(&mut self) -> Option<Self::Item> {
957 if self.last_slice_end == self.slice.len() {
961 let mut sub_slice_end = self.last_slice_end;
962 let mut first_whitespace = None;
963 let subslice = &self.slice[self.last_slice_end..];
964 let mut iter = CharClasses::new(subslice.char_indices());
966 for (kind, (i, c)) in &mut iter {
967 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal
968 && &subslice[..2] == "//"
969 && [' ', '\t'].contains(&c);
971 if is_comment_connector && first_whitespace.is_none() {
972 first_whitespace = Some(i);
975 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
976 let last_index = match first_whitespace {
980 sub_slice_end = self.last_slice_end + last_index;
984 if !is_comment_connector {
985 first_whitespace = None;
989 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
990 // This was the last subslice.
991 sub_slice_end = match first_whitespace {
992 Some(i) => self.last_slice_end + i,
993 None => self.slice.len(),
997 let kind = match self.last_slice_kind {
998 CodeCharKind::Comment => CodeCharKind::Normal,
999 CodeCharKind::Normal => CodeCharKind::Comment,
1003 self.last_slice_end,
1004 &self.slice[self.last_slice_end..sub_slice_end],
1006 self.last_slice_end = sub_slice_end;
1007 self.last_slice_kind = kind;
1013 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
1014 /// (if it fits in the width/offset, else return None), else return `new`
1015 pub fn recover_comment_removed(
1018 context: &RewriteContext,
1019 ) -> Option<String> {
1020 let snippet = context.snippet(span);
1021 if snippet != new && changed_comment_content(snippet, &new) {
1022 // We missed some comments. Keep the original text.
1023 Some(snippet.to_owned())
1029 /// Return true if the two strings of code have the same payload of comments.
1030 /// The payload of comments is everything in the string except:
1031 /// - actual code (not comments)
1032 /// - comment start/end marks
1034 /// - '*' at the beginning of lines in block comments
1035 fn changed_comment_content(orig: &str, new: &str) -> bool {
1036 // Cannot write this as a fn since we cannot return types containing closures
1037 let code_comment_content = |code| {
1038 let slices = UngroupedCommentCodeSlices::new(code);
1040 .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
1041 .flat_map(|(_, _, s)| CommentReducer::new(s))
1043 let res = code_comment_content(orig).ne(code_comment_content(new));
1045 "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
1049 code_comment_content(orig).collect::<String>(),
1050 code_comment_content(new).collect::<String>()
1055 /// Iterator over the 'payload' characters of a comment.
1056 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
1057 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
1059 struct CommentReducer<'a> {
1061 at_start_line: bool,
1062 iter: std::str::Chars<'a>,
1065 impl<'a> CommentReducer<'a> {
1066 fn new(comment: &'a str) -> CommentReducer<'a> {
1067 let is_block = comment.starts_with("/*");
1068 let comment = remove_comment_header(comment);
1071 at_start_line: false, // There are no supplementary '*' on the first line
1072 iter: comment.chars(),
1077 impl<'a> Iterator for CommentReducer<'a> {
1079 fn next(&mut self) -> Option<Self::Item> {
1081 let mut c = self.iter.next()?;
1082 if self.is_block && self.at_start_line {
1083 while c.is_whitespace() {
1084 c = self.iter.next()?;
1086 // Ignore leading '*'
1088 c = self.iter.next()?;
1090 } else if c == '\n' {
1091 self.at_start_line = true;
1093 if !c.is_whitespace() {
1100 fn remove_comment_header(comment: &str) -> &str {
1101 if comment.starts_with("///") || comment.starts_with("//!") {
1103 } else if comment.starts_with("//") {
1105 } else if (comment.starts_with("/**") && !comment.starts_with("/**/"))
1106 || comment.starts_with("/*!")
1108 &comment[3..comment.len() - 2]
1111 comment.starts_with("/*"),
1112 format!("string '{}' is not a comment", comment)
1114 &comment[2..comment.len() - 2]
1120 use super::{contains_comment, rewrite_comment, CharClasses, CodeCharKind, CommentCodeSlices,
1121 FindUncommented, FullCodeCharKind};
1122 use shape::{Indent, Shape};
1126 let mut iter = CharClasses::new("//\n\n".chars());
1128 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
1129 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
1130 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
1131 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
1132 assert_eq!(None, iter.next());
1136 fn comment_code_slices() {
1137 let input = "code(); /* test */ 1 + 1";
1138 let mut iter = CommentCodeSlices::new(input);
1140 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
1142 (CodeCharKind::Comment, 8, "/* test */"),
1143 iter.next().unwrap()
1145 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
1146 assert_eq!(None, iter.next());
1150 fn comment_code_slices_two() {
1151 let input = "// comment\n test();";
1152 let mut iter = CommentCodeSlices::new(input);
1154 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
1156 (CodeCharKind::Comment, 0, "// comment\n"),
1157 iter.next().unwrap()
1160 (CodeCharKind::Normal, 11, " test();"),
1161 iter.next().unwrap()
1163 assert_eq!(None, iter.next());
1167 fn comment_code_slices_three() {
1168 let input = "1 // comment\n // comment2\n\n";
1169 let mut iter = CommentCodeSlices::new(input);
1171 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
1173 (CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
1174 iter.next().unwrap()
1176 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
1177 assert_eq!(None, iter.next());
1181 #[cfg_attr(rustfmt, rustfmt_skip)]
1182 fn format_comments() {
1183 let mut config: ::config::Config = Default::default();
1184 config.set().wrap_comments(true);
1185 config.set().normalize_comments(true);
1187 let comment = rewrite_comment(" //test",
1189 Shape::legacy(100, Indent::new(0, 100)),
1191 assert_eq!("/* test */", comment);
1193 let comment = rewrite_comment("// comment on a",
1195 Shape::legacy(10, Indent::empty()),
1197 assert_eq!("// comment\n// on a", comment);
1199 let comment = rewrite_comment("// A multi line comment\n // between args.",
1201 Shape::legacy(60, Indent::new(0, 12)),
1203 assert_eq!("// A multi line comment\n // between args.", comment);
1205 let input = "// comment";
1208 let comment = rewrite_comment(input,
1210 Shape::legacy(9, Indent::new(0, 69)),
1212 assert_eq!(expected, comment);
1214 let comment = rewrite_comment("/* trimmed */",
1216 Shape::legacy(100, Indent::new(0, 100)),
1218 assert_eq!("/* trimmed */", comment);
1221 // This is probably intended to be a non-test fn, but it is not used. I'm
1222 // keeping it around unless it helps us test stuff.
1223 fn uncommented(text: &str) -> String {
1224 CharClasses::new(text.chars())
1225 .filter_map(|(s, c)| match s {
1226 FullCodeCharKind::Normal | FullCodeCharKind::InString => Some(c),
1233 fn test_uncommented() {
1234 assert_eq!(&uncommented("abc/*...*/"), "abc");
1236 &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
1239 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
1243 fn test_contains_comment() {
1244 assert_eq!(contains_comment("abc"), false);
1245 assert_eq!(contains_comment("abc // qsdf"), true);
1246 assert_eq!(contains_comment("abc /* kqsdf"), true);
1247 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
1251 fn test_find_uncommented() {
1252 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
1253 assert_eq!(expected, haystack.find_uncommented(needle));
1256 check("/*/ */test", "test", Some(6));
1257 check("//test\ntest", "test", Some(7));
1258 check("/* comment only */", "whatever", None);
1260 "/* comment */ some text /* more commentary */ result",
1264 check("sup // sup", "p", Some(2));
1265 check("sup", "x", None);
1266 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
1267 check("/*sup yo? \n sup*/ sup", "p", Some(20));
1268 check("hel/*lohello*/lo", "hello", None);
1269 check("acb", "ab", None);
1270 check(",/*A*/ ", ",", Some(0));
1271 check("abc", "abc", Some(0));
1272 check("/* abc */", "abc", None);
1273 check("/**/abc/* */", "abc", Some(4));
1274 check("\"/* abc */\"", "abc", Some(4));
1275 check("\"/* abc", "abc", Some(4));