1 // Formatting and tools for comments.
3 use std::{self, borrow::Cow, iter};
5 use itertools::{multipeek, MultiPeek};
8 use crate::config::Config;
9 use crate::rewrite::RewriteContext;
10 use crate::shape::{Indent, Shape};
11 use crate::string::{rewrite_string, StringFormat};
13 count_newlines, first_line_width, last_line_width, trim_left_preserve_layout, unicode_str_width,
15 use crate::{ErrorKind, FormattingError};
17 fn is_custom_comment(comment: &str) -> bool {
18 if !comment.starts_with("//") {
20 } else if let Some(c) = comment.chars().nth(2) {
21 !c.is_alphanumeric() && !c.is_whitespace()
27 #[derive(Copy, Clone, PartialEq, Eq)]
28 pub(crate) enum CommentStyle<'a> {
38 fn custom_opener(s: &str) -> &str {
39 s.lines().next().map_or("", |first_line| {
42 .map_or(first_line, |space_index| &first_line[0..=space_index])
46 impl<'a> CommentStyle<'a> {
47 /// Returns `true` if the commenting style covers a line only.
48 pub(crate) fn is_line_comment(&self) -> bool {
50 CommentStyle::DoubleSlash
51 | CommentStyle::TripleSlash
53 | CommentStyle::Custom(_) => true,
58 /// Returns `true` if the commenting style can span over multiple lines.
59 pub(crate) fn is_block_comment(&self) -> bool {
61 CommentStyle::SingleBullet | CommentStyle::DoubleBullet | CommentStyle::Exclamation => {
68 /// Returns `true` if the commenting style is for documentation.
69 pub(crate) fn is_doc_comment(&self) -> bool {
71 CommentStyle::TripleSlash | CommentStyle::Doc => true,
76 pub(crate) fn opener(&self) -> &'a str {
78 CommentStyle::DoubleSlash => "// ",
79 CommentStyle::TripleSlash => "/// ",
80 CommentStyle::Doc => "//! ",
81 CommentStyle::SingleBullet => "/* ",
82 CommentStyle::DoubleBullet => "/** ",
83 CommentStyle::Exclamation => "/*! ",
84 CommentStyle::Custom(opener) => opener,
88 pub(crate) fn closer(&self) -> &'a str {
90 CommentStyle::DoubleSlash
91 | CommentStyle::TripleSlash
92 | CommentStyle::Custom(..)
93 | CommentStyle::Doc => "",
94 CommentStyle::DoubleBullet => " **/",
95 CommentStyle::SingleBullet | CommentStyle::Exclamation => " */",
99 pub(crate) fn line_start(&self) -> &'a str {
101 CommentStyle::DoubleSlash => "// ",
102 CommentStyle::TripleSlash => "/// ",
103 CommentStyle::Doc => "//! ",
104 CommentStyle::SingleBullet | CommentStyle::Exclamation => " * ",
105 CommentStyle::DoubleBullet => " ** ",
106 CommentStyle::Custom(opener) => opener,
110 pub(crate) fn to_str_tuplet(&self) -> (&'a str, &'a str, &'a str) {
111 (self.opener(), self.closer(), self.line_start())
115 pub(crate) fn comment_style(orig: &str, normalize_comments: bool) -> CommentStyle<'_> {
116 if !normalize_comments {
117 if orig.starts_with("/**") && !orig.starts_with("/**/") {
118 CommentStyle::DoubleBullet
119 } else if orig.starts_with("/*!") {
120 CommentStyle::Exclamation
121 } else if orig.starts_with("/*") {
122 CommentStyle::SingleBullet
123 } else if orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/') {
124 CommentStyle::TripleSlash
125 } else if orig.starts_with("//!") {
127 } else if is_custom_comment(orig) {
128 CommentStyle::Custom(custom_opener(orig))
130 CommentStyle::DoubleSlash
132 } else if (orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/'))
133 || (orig.starts_with("/**") && !orig.starts_with("/**/"))
135 CommentStyle::TripleSlash
136 } else if orig.starts_with("//!") || orig.starts_with("/*!") {
138 } else if is_custom_comment(orig) {
139 CommentStyle::Custom(custom_opener(orig))
141 CommentStyle::DoubleSlash
145 /// Returns true if the last line of the passed string finishes with a block-comment.
146 pub(crate) fn is_last_comment_block(s: &str) -> bool {
147 s.trim_end().ends_with("*/")
150 /// Combine `prev_str` and `next_str` into a single `String`. `span` may contain
151 /// comments between two strings. If there are such comments, then that will be
152 /// recovered. If `allow_extend` is true and there is no comment between the two
153 /// strings, then they will be put on a single line as long as doing so does not
154 /// exceed max width.
155 pub(crate) fn combine_strs_with_missing_comments(
156 context: &RewriteContext<'_>,
162 ) -> Option<String> {
164 "combine_strs_with_missing_comments `{}` `{}` {:?} {:?}",
172 String::with_capacity(prev_str.len() + next_str.len() + shape.indent.width() + 128);
173 result.push_str(prev_str);
174 let mut allow_one_line = !prev_str.contains('\n') && !next_str.contains('\n');
175 let first_sep = if prev_str.is_empty() || next_str.is_empty() {
180 let mut one_line_width =
181 last_line_width(prev_str) + first_line_width(next_str) + first_sep.len();
183 let config = context.config;
184 let indent = shape.indent;
185 let missing_comment = rewrite_missing_comment(span, shape, context)?;
187 if missing_comment.is_empty() {
188 if allow_extend && prev_str.len() + first_sep.len() + next_str.len() <= shape.width {
189 result.push_str(first_sep);
190 } else if !prev_str.is_empty() {
191 result.push_str(&indent.to_string_with_newline(config))
193 result.push_str(next_str);
197 // We have a missing comment between the first expression and the second expression.
199 // Peek the the original source code and find out whether there is a newline between the first
200 // expression and the second expression or the missing comment. We will preserve the original
201 // layout whenever possible.
202 let original_snippet = context.snippet(span);
203 let prefer_same_line = if let Some(pos) = original_snippet.find('/') {
204 !original_snippet[..pos].contains('\n')
206 !original_snippet.contains('\n')
209 one_line_width -= first_sep.len();
210 let first_sep = if prev_str.is_empty() || missing_comment.is_empty() {
213 let one_line_width = last_line_width(prev_str) + first_line_width(&missing_comment) + 1;
214 if prefer_same_line && one_line_width <= shape.width {
217 indent.to_string_with_newline(config)
220 result.push_str(&first_sep);
221 result.push_str(&missing_comment);
223 let second_sep = if missing_comment.is_empty() || next_str.is_empty() {
225 } else if missing_comment.starts_with("//") {
226 indent.to_string_with_newline(config)
228 one_line_width += missing_comment.len() + first_sep.len() + 1;
229 allow_one_line &= !missing_comment.starts_with("//") && !missing_comment.contains('\n');
230 if prefer_same_line && allow_one_line && one_line_width <= shape.width {
233 indent.to_string_with_newline(config)
236 result.push_str(&second_sep);
237 result.push_str(next_str);
242 pub(crate) fn rewrite_doc_comment(orig: &str, shape: Shape, config: &Config) -> Option<String> {
243 identify_comment(orig, false, shape, config, true)
246 pub(crate) fn rewrite_comment(
251 ) -> Option<String> {
252 identify_comment(orig, block_style, shape, config, false)
260 is_doc_comment: bool,
261 ) -> Option<String> {
262 let style = comment_style(orig, false);
264 // Computes the byte length of line taking into account a newline if the line is part of a
266 fn compute_len(orig: &str, line: &str) -> usize {
267 if orig.len() > line.len() {
268 if orig.as_bytes()[line.len()] == b'\r' {
278 // Get the first group of line comments having the same commenting style.
280 // Returns a tuple with:
281 // - a boolean indicating if there is a blank line
282 // - a number indicating the size of the first group of comments
283 fn consume_same_line_comments(
284 style: CommentStyle<'_>,
288 let mut first_group_ending = 0;
291 for line in orig.lines() {
292 let trimmed_line = line.trim_start();
293 if trimmed_line.is_empty() {
296 } else if trimmed_line.starts_with(line_start)
297 || comment_style(trimmed_line, false) == style
299 first_group_ending += compute_len(&orig[first_group_ending..], line);
304 (hbl, first_group_ending)
307 let (has_bare_lines, first_group_ending) = match style {
308 CommentStyle::DoubleSlash | CommentStyle::TripleSlash | CommentStyle::Doc => {
309 let line_start = style.line_start().trim_start();
310 consume_same_line_comments(style, orig, line_start)
312 CommentStyle::Custom(opener) => {
313 let trimmed_opener = opener.trim_end();
314 consume_same_line_comments(style, orig, trimmed_opener)
316 // for a block comment, search for the closing symbol
317 CommentStyle::DoubleBullet | CommentStyle::SingleBullet | CommentStyle::Exclamation => {
318 let closer = style.closer().trim_start();
319 let mut count = orig.matches(closer).count();
320 let mut closing_symbol_offset = 0;
322 let mut first = true;
323 for line in orig.lines() {
324 closing_symbol_offset += compute_len(&orig[closing_symbol_offset..], line);
325 let mut trimmed_line = line.trim_start();
326 if !trimmed_line.starts_with('*')
327 && !trimmed_line.starts_with("//")
328 && !trimmed_line.starts_with("/*")
333 // Remove opener from consideration when searching for closer
335 let opener = style.opener().trim_end();
336 trimmed_line = &trimmed_line[opener.len()..];
339 if trimmed_line.ends_with(closer) {
346 (hbl, closing_symbol_offset)
350 let (first_group, rest) = orig.split_at(first_group_ending);
351 let rewritten_first_group =
352 if !config.normalize_comments() && has_bare_lines && style.is_block_comment() {
353 trim_left_preserve_layout(first_group, shape.indent, config)?
354 } else if !config.normalize_comments()
355 && !config.wrap_comments()
356 && !config.format_code_in_doc_comments()
358 light_rewrite_comment(first_group, shape.indent, config, is_doc_comment)
360 rewrite_comment_inner(
366 is_doc_comment || style.is_doc_comment(),
370 Some(rewritten_first_group)
382 rewritten_first_group,
383 // insert back the blank line
384 if has_bare_lines && style.is_line_comment() {
389 shape.indent.to_string(config),
396 /// Attributes for code blocks in rustdoc.
397 /// See https://doc.rust-lang.org/rustdoc/print.html#attributes
398 enum CodeBlockAttribute {
407 impl CodeBlockAttribute {
408 fn new(attribute: &str) -> CodeBlockAttribute {
410 "rust" | "" => CodeBlockAttribute::Rust,
411 "ignore" => CodeBlockAttribute::Ignore,
412 "text" => CodeBlockAttribute::Text,
413 "should_panic" => CodeBlockAttribute::ShouldPanic,
414 "no_run" => CodeBlockAttribute::NoRun,
415 "compile_fail" => CodeBlockAttribute::CompileFail,
416 _ => CodeBlockAttribute::Text,
421 /// Block that is formatted as an item.
423 /// An item starts with either a star `*` or a dash `-`. Different level of indentation are
424 /// handled by shrinking the shape accordingly.
425 struct ItemizedBlock {
426 /// the lines that are identified as part of an itemized block
428 /// the number of whitespaces up to the item sigil
430 /// the string that marks the start of an item
432 /// sequence of whitespaces to prefix new lines that are part of the item
437 /// Returns `true` if the line is formatted as an item
438 fn is_itemized_line(line: &str) -> bool {
439 let trimmed = line.trim_start();
440 trimmed.starts_with("* ") || trimmed.starts_with("- ")
443 /// Creates a new ItemizedBlock described with the given line.
444 /// The `is_itemized_line` needs to be called first.
445 fn new(line: &str) -> ItemizedBlock {
446 let space_to_sigil = line.chars().take_while(|c| c.is_whitespace()).count();
447 let indent = space_to_sigil + 2;
449 lines: vec![line[indent..].to_string()],
451 opener: line[..indent].to_string(),
452 line_start: " ".repeat(indent),
456 /// Returns a `StringFormat` used for formatting the content of an item.
457 fn create_string_format<'a>(&'a self, fmt: &'a StringFormat<'_>) -> StringFormat<'a> {
463 shape: Shape::legacy(fmt.shape.width.saturating_sub(self.indent), Indent::empty()),
469 /// Returns `true` if the line is part of the current itemized block.
470 /// If it is, then it is added to the internal lines list.
471 fn add_line(&mut self, line: &str) -> bool {
472 if !ItemizedBlock::is_itemized_line(line)
473 && self.indent <= line.chars().take_while(|c| c.is_whitespace()).count()
475 self.lines.push(line.to_string());
481 /// Returns the block as a string, with each line trimmed at the start.
482 fn trimmed_block_as_string(&self) -> String {
485 .map(|line| format!("{} ", line.trim_start()))
489 /// Returns the block as a string under its original form.
490 fn original_block_as_string(&self) -> String {
491 self.lines.join("\n")
495 struct CommentRewrite<'a> {
497 code_block_buffer: String,
498 is_prev_line_multi_line: bool,
499 code_block_attr: Option<CodeBlockAttribute>,
500 item_block: Option<ItemizedBlock>,
501 comment_line_separator: String,
505 fmt: StringFormat<'a>,
512 impl<'a> CommentRewrite<'a> {
518 ) -> CommentRewrite<'a> {
519 let (opener, closer, line_start) = if block_style {
520 CommentStyle::SingleBullet.to_str_tuplet()
522 comment_style(orig, config.normalize_comments()).to_str_tuplet()
525 let max_width = shape
527 .checked_sub(closer.len() + opener.len())
529 let indent_str = shape.indent.to_string_with_newline(config).to_string();
530 let fmt_indent = shape.indent + (opener.len() - line_start.len());
532 let mut cr = CommentRewrite {
533 result: String::with_capacity(orig.len() * 2),
534 code_block_buffer: String::with_capacity(128),
535 is_prev_line_multi_line: false,
536 code_block_attr: None,
538 comment_line_separator: format!("{}{}", indent_str, line_start),
548 shape: Shape::legacy(max_width, fmt_indent),
553 opener: opener.to_owned(),
554 closer: closer.to_owned(),
555 line_start: line_start.to_owned(),
557 cr.result.push_str(opener);
561 fn join_block(s: &str, sep: &str) -> String {
562 let mut result = String::with_capacity(s.len() + 128);
563 let mut iter = s.lines().peekable();
564 while let Some(line) = iter.next() {
565 result.push_str(line);
566 result.push_str(match iter.peek() {
567 Some(next_line) if next_line.is_empty() => sep.trim_end(),
575 fn finish(mut self) -> String {
576 if !self.code_block_buffer.is_empty() {
577 // There is a code block that is not properly enclosed by backticks.
578 // We will leave them untouched.
579 self.result.push_str(&self.comment_line_separator);
580 self.result.push_str(&Self::join_block(
581 &trim_custom_comment_prefix(&self.code_block_buffer),
582 &self.comment_line_separator,
586 if let Some(ref ib) = self.item_block {
587 // the last few lines are part of an itemized block
588 self.fmt.shape = Shape::legacy(self.max_width, self.fmt_indent);
589 let item_fmt = ib.create_string_format(&self.fmt);
590 self.result.push_str(&self.comment_line_separator);
591 self.result.push_str(&ib.opener);
592 match rewrite_string(
593 &ib.trimmed_block_as_string(),
595 self.max_width.saturating_sub(ib.indent),
597 Some(s) => self.result.push_str(&Self::join_block(
599 &format!("{}{}", self.comment_line_separator, ib.line_start),
601 None => self.result.push_str(&Self::join_block(
602 &ib.original_block_as_string(),
603 &self.comment_line_separator,
608 self.result.push_str(&self.closer);
609 if self.result.ends_with(&self.opener) && self.opener.ends_with(' ') {
622 has_leading_whitespace: bool,
624 let is_last = i == count_newlines(orig);
626 if let Some(ref mut ib) = self.item_block {
627 if ib.add_line(&line) {
630 self.is_prev_line_multi_line = false;
631 self.fmt.shape = Shape::legacy(self.max_width, self.fmt_indent);
632 let item_fmt = ib.create_string_format(&self.fmt);
633 self.result.push_str(&self.comment_line_separator);
634 self.result.push_str(&ib.opener);
635 match rewrite_string(
636 &ib.trimmed_block_as_string(),
638 self.max_width.saturating_sub(ib.indent),
640 Some(s) => self.result.push_str(&Self::join_block(
642 &format!("{}{}", self.comment_line_separator, ib.line_start),
644 None => self.result.push_str(&Self::join_block(
645 &ib.original_block_as_string(),
646 &self.comment_line_separator,
649 } else if self.code_block_attr.is_some() {
650 if line.starts_with("```") {
651 let code_block = match self.code_block_attr.as_ref().unwrap() {
652 CodeBlockAttribute::Ignore | CodeBlockAttribute::Text => {
653 trim_custom_comment_prefix(&self.code_block_buffer)
655 _ if self.code_block_buffer.is_empty() => String::new(),
657 let mut config = self.fmt.config.clone();
658 config.set().wrap_comments(false);
659 if config.format_code_in_doc_comments() {
661 crate::format_code_block(&self.code_block_buffer, &config)
663 trim_custom_comment_prefix(&s.snippet)
665 trim_custom_comment_prefix(&self.code_block_buffer)
668 trim_custom_comment_prefix(&self.code_block_buffer)
672 if !code_block.is_empty() {
673 self.result.push_str(&self.comment_line_separator);
675 .push_str(&Self::join_block(&code_block, &self.comment_line_separator));
677 self.code_block_buffer.clear();
678 self.result.push_str(&self.comment_line_separator);
679 self.result.push_str(line);
680 self.code_block_attr = None;
682 self.code_block_buffer
683 .push_str(&hide_sharp_behind_comment(line));
684 self.code_block_buffer.push('\n');
689 self.code_block_attr = None;
690 self.item_block = None;
691 if line.starts_with("```") {
692 self.code_block_attr = Some(CodeBlockAttribute::new(&line[3..]))
693 } else if self.fmt.config.wrap_comments() && ItemizedBlock::is_itemized_line(&line) {
694 let ib = ItemizedBlock::new(&line);
695 self.item_block = Some(ib);
699 if self.result == self.opener {
700 let force_leading_whitespace = &self.opener == "/* " && count_newlines(orig) == 0;
701 if !has_leading_whitespace && !force_leading_whitespace && self.result.ends_with(' ') {
707 } else if self.is_prev_line_multi_line && !line.is_empty() {
708 self.result.push(' ')
709 } else if is_last && line.is_empty() {
710 // trailing blank lines are unwanted
711 if !self.closer.is_empty() {
712 self.result.push_str(&self.indent_str);
716 self.result.push_str(&self.comment_line_separator);
717 if !has_leading_whitespace && self.result.ends_with(' ') {
722 if self.fmt.config.wrap_comments()
723 && unicode_str_width(line) > self.fmt.shape.width
726 match rewrite_string(line, &self.fmt, self.max_width) {
728 self.is_prev_line_multi_line = s.contains('\n');
729 self.result.push_str(s);
731 None if self.is_prev_line_multi_line => {
732 // We failed to put the current `line` next to the previous `line`.
733 // Remove the trailing space, then start rewrite on the next line.
735 self.result.push_str(&self.comment_line_separator);
736 self.fmt.shape = Shape::legacy(self.max_width, self.fmt_indent);
737 match rewrite_string(line, &self.fmt, self.max_width) {
739 self.is_prev_line_multi_line = s.contains('\n');
740 self.result.push_str(s);
743 self.is_prev_line_multi_line = false;
744 self.result.push_str(line);
749 self.is_prev_line_multi_line = false;
750 self.result.push_str(line);
754 self.fmt.shape = if self.is_prev_line_multi_line {
756 let offset = 1 + last_line_width(&self.result) - self.line_start.len();
758 width: self.max_width.saturating_sub(offset),
759 indent: self.fmt_indent,
760 offset: self.fmt.shape.offset + offset,
763 Shape::legacy(self.max_width, self.fmt_indent)
766 if line.is_empty() && self.result.ends_with(' ') && !is_last {
767 // Remove space if this is an empty comment or a doc comment.
770 self.result.push_str(line);
771 self.fmt.shape = Shape::legacy(self.max_width, self.fmt_indent);
772 self.is_prev_line_multi_line = false;
779 fn rewrite_comment_inner(
782 style: CommentStyle<'_>,
785 is_doc_comment: bool,
786 ) -> Option<String> {
787 let mut rewriter = CommentRewrite::new(orig, block_style, shape, config);
789 let line_breaks = count_newlines(orig.trim_end());
793 .map(|(i, mut line)| {
794 line = trim_end_unless_two_whitespaces(line.trim_start(), is_doc_comment);
796 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
797 line = line[..(line.len() - 2)].trim_end();
802 .map(|s| left_trim_comment_line(s, &style))
803 .map(|(line, has_leading_whitespace)| {
804 if orig.starts_with("/*") && line_breaks == 0 {
807 has_leading_whitespace || config.normalize_comments(),
810 (line, has_leading_whitespace || config.normalize_comments())
814 for (i, (line, has_leading_whitespace)) in lines.enumerate() {
815 if rewriter.handle_line(orig, i, line, has_leading_whitespace) {
820 Some(rewriter.finish())
823 const RUSTFMT_CUSTOM_COMMENT_PREFIX: &str = "//#### ";
825 fn hide_sharp_behind_comment(s: &str) -> Cow<'_, str> {
826 let s_trimmed = s.trim();
827 if s_trimmed.starts_with("# ") || s_trimmed == "#" {
828 Cow::from(format!("{}{}", RUSTFMT_CUSTOM_COMMENT_PREFIX, s))
834 fn trim_custom_comment_prefix(s: &str) -> String {
837 let left_trimmed = line.trim_start();
838 if left_trimmed.starts_with(RUSTFMT_CUSTOM_COMMENT_PREFIX) {
839 left_trimmed.trim_start_matches(RUSTFMT_CUSTOM_COMMENT_PREFIX)
848 /// Returns `true` if the given string MAY include URLs or alike.
849 fn has_url(s: &str) -> bool {
850 // This function may return false positive, but should get its job done in most cases.
851 s.contains("https://") || s.contains("http://") || s.contains("ftp://") || s.contains("file://")
854 /// Given the span, rewrite the missing comment inside it if available.
855 /// Note that the given span must only include comments (or leading/trailing whitespaces).
856 pub(crate) fn rewrite_missing_comment(
859 context: &RewriteContext<'_>,
860 ) -> Option<String> {
861 let missing_snippet = context.snippet(span);
862 let trimmed_snippet = missing_snippet.trim();
863 // check the span starts with a comment
864 let pos = trimmed_snippet.find('/');
865 if !trimmed_snippet.is_empty() && pos.is_some() {
866 rewrite_comment(trimmed_snippet, false, shape, context.config)
872 /// Recover the missing comments in the specified span, if available.
873 /// The layout of the comments will be preserved as long as it does not break the code
874 /// and its total width does not exceed the max width.
875 pub(crate) fn recover_missing_comment_in_span(
878 context: &RewriteContext<'_>,
880 ) -> Option<String> {
881 let missing_comment = rewrite_missing_comment(span, shape, context)?;
882 if missing_comment.is_empty() {
885 let missing_snippet = context.snippet(span);
886 let pos = missing_snippet.find('/')?;
888 let total_width = missing_comment.len() + used_width + 1;
889 let force_new_line_before_comment =
890 missing_snippet[..pos].contains('\n') || total_width > context.config.max_width();
891 let sep = if force_new_line_before_comment {
892 shape.indent.to_string_with_newline(context.config)
896 Some(format!("{}{}", sep, missing_comment))
900 /// Trim trailing whitespaces unless they consist of two or more whitespaces.
901 fn trim_end_unless_two_whitespaces(s: &str, is_doc_comment: bool) -> &str {
902 if is_doc_comment && s.ends_with(" ") {
909 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
910 fn light_rewrite_comment(
914 is_doc_comment: bool,
916 let lines: Vec<&str> = orig
919 // This is basically just l.trim(), but in the case that a line starts
920 // with `*` we want to leave one space before it, so it aligns with the
922 let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
923 let left_trimmed = if let Some(fnw) = first_non_whitespace {
924 if l.as_bytes()[fnw] == b'*' && fnw > 0 {
932 // Preserve markdown's double-space line break syntax in doc comment.
933 trim_end_unless_two_whitespaces(left_trimmed, is_doc_comment)
936 lines.join(&format!("\n{}", offset.to_string(config)))
939 /// Trims comment characters and possibly a single space from the left of a string.
940 /// Does not trim all whitespace. If a single space is trimmed from the left of the string,
941 /// this function returns true.
942 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle<'_>) -> (&'a str, bool) {
943 if line.starts_with("//! ")
944 || line.starts_with("/// ")
945 || line.starts_with("/*! ")
946 || line.starts_with("/** ")
949 } else if let CommentStyle::Custom(opener) = *style {
950 if line.starts_with(opener) {
951 (&line[opener.len()..], true)
953 (&line[opener.trim_end().len()..], false)
955 } else if line.starts_with("/* ")
956 || line.starts_with("// ")
957 || line.starts_with("//!")
958 || line.starts_with("///")
959 || line.starts_with("** ")
960 || line.starts_with("/*!")
961 || (line.starts_with("/**") && !line.starts_with("/**/"))
963 (&line[3..], line.chars().nth(2).unwrap() == ' ')
964 } else if line.starts_with("/*")
965 || line.starts_with("* ")
966 || line.starts_with("//")
967 || line.starts_with("**")
969 (&line[2..], line.chars().nth(1).unwrap() == ' ')
970 } else if line.starts_with('*') {
973 (line, line.starts_with(' '))
977 pub(crate) trait FindUncommented {
978 fn find_uncommented(&self, pat: &str) -> Option<usize>;
981 impl FindUncommented for str {
982 fn find_uncommented(&self, pat: &str) -> Option<usize> {
983 let mut needle_iter = pat.chars();
984 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
985 match needle_iter.next() {
987 return Some(i - pat.len());
989 Some(c) => match kind {
990 FullCodeCharKind::Normal | FullCodeCharKind::InString if b == c => {}
992 needle_iter = pat.chars();
998 // Handle case where the pattern is a suffix of the search string
999 match needle_iter.next() {
1001 None => Some(self.len() - pat.len()),
1006 // Returns the first byte position after the first comment. The given string
1007 // is expected to be prefixed by a comment, including delimiters.
1008 // Good: `/* /* inner */ outer */ code();`
1009 // Bad: `code(); // hello\n world!`
1010 pub(crate) fn find_comment_end(s: &str) -> Option<usize> {
1011 let mut iter = CharClasses::new(s.char_indices());
1012 for (kind, (i, _c)) in &mut iter {
1013 if kind == FullCodeCharKind::Normal || kind == FullCodeCharKind::InString {
1018 // Handle case where the comment ends at the end of `s`.
1019 if iter.status == CharClassesStatus::Normal {
1026 /// Returns `true` if text contains any comment.
1027 pub(crate) fn contains_comment(text: &str) -> bool {
1028 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
1031 pub(crate) struct CharClasses<T>
1037 status: CharClassesStatus,
1040 pub(crate) trait RichChar {
1041 fn get_char(&self) -> char;
1044 impl RichChar for char {
1045 fn get_char(&self) -> char {
1050 impl RichChar for (usize, char) {
1051 fn get_char(&self) -> char {
1056 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
1057 enum CharClassesStatus {
1059 /// Character is within a string
1062 /// Character is within a raw string
1064 RawStringPrefix(u32),
1065 RawStringSuffix(u32),
1068 /// Character inside a block comment, with the integer indicating the nesting deepness of the
1071 /// Character inside a block-commented string, with the integer indicating the nesting deepness
1073 StringInBlockComment(u32),
1074 /// Status when the '/' has been consumed, but not yet the '*', deepness is
1075 /// the new deepness (after the comment opening).
1076 BlockCommentOpening(u32),
1077 /// Status when the '*' has been consumed, but not yet the '/', deepness is
1078 /// the new deepness (after the comment closing).
1079 BlockCommentClosing(u32),
1080 /// Character is within a line comment
1084 /// Distinguish between functional part of code and comments
1085 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
1086 pub(crate) enum CodeCharKind {
1091 /// Distinguish between functional part of code and comments,
1092 /// describing opening and closing of comments for ease when chunking
1093 /// code from tagged characters
1094 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
1095 pub(crate) enum FullCodeCharKind {
1097 /// The first character of a comment, there is only one for a comment (always '/')
1099 /// Any character inside a comment including the second character of comment
1100 /// marks ("//", "/*")
1102 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
1104 /// Start of a mutlitine string inside a comment
1105 StartStringCommented,
1106 /// End of a mutlitine string inside a comment
1108 /// Inside a commented string
1110 /// Start of a mutlitine string
1112 /// End of a mutlitine string
1114 /// Inside a string.
1118 impl FullCodeCharKind {
1119 pub(crate) fn is_comment(self) -> bool {
1121 FullCodeCharKind::StartComment
1122 | FullCodeCharKind::InComment
1123 | FullCodeCharKind::EndComment
1124 | FullCodeCharKind::StartStringCommented
1125 | FullCodeCharKind::InStringCommented
1126 | FullCodeCharKind::EndStringCommented => true,
1131 /// Returns true if the character is inside a comment
1132 pub(crate) fn inside_comment(self) -> bool {
1134 FullCodeCharKind::InComment
1135 | FullCodeCharKind::StartStringCommented
1136 | FullCodeCharKind::InStringCommented
1137 | FullCodeCharKind::EndStringCommented => true,
1142 pub(crate) fn is_string(self) -> bool {
1143 self == FullCodeCharKind::InString || self == FullCodeCharKind::StartString
1146 /// Returns true if the character is within a commented string
1147 pub(crate) fn is_commented_string(self) -> bool {
1148 self == FullCodeCharKind::InStringCommented
1149 || self == FullCodeCharKind::StartStringCommented
1152 fn to_codecharkind(self) -> CodeCharKind {
1153 if self.is_comment() {
1154 CodeCharKind::Comment
1156 CodeCharKind::Normal
1161 impl<T> CharClasses<T>
1166 pub(crate) fn new(base: T) -> CharClasses<T> {
1168 base: multipeek(base),
1169 status: CharClassesStatus::Normal,
1174 fn is_raw_string_suffix<T>(iter: &mut MultiPeek<T>, count: u32) -> bool
1181 Some(c) if c.get_char() == '#' => continue,
1188 impl<T> Iterator for CharClasses<T>
1193 type Item = (FullCodeCharKind, T::Item);
1195 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
1196 let item = self.base.next()?;
1197 let chr = item.get_char();
1198 let mut char_kind = FullCodeCharKind::Normal;
1199 self.status = match self.status {
1200 CharClassesStatus::LitRawString(sharps) => {
1201 char_kind = FullCodeCharKind::InString;
1205 char_kind = FullCodeCharKind::Normal;
1206 CharClassesStatus::Normal
1207 } else if is_raw_string_suffix(&mut self.base, sharps) {
1208 CharClassesStatus::RawStringSuffix(sharps)
1210 CharClassesStatus::LitRawString(sharps)
1213 _ => CharClassesStatus::LitRawString(sharps),
1216 CharClassesStatus::RawStringPrefix(sharps) => {
1217 char_kind = FullCodeCharKind::InString;
1219 '#' => CharClassesStatus::RawStringPrefix(sharps + 1),
1220 '"' => CharClassesStatus::LitRawString(sharps),
1221 _ => CharClassesStatus::Normal, // Unreachable.
1224 CharClassesStatus::RawStringSuffix(sharps) => {
1228 CharClassesStatus::Normal
1230 char_kind = FullCodeCharKind::InString;
1231 CharClassesStatus::RawStringSuffix(sharps - 1)
1234 _ => CharClassesStatus::Normal, // Unreachable
1237 CharClassesStatus::LitString => {
1238 char_kind = FullCodeCharKind::InString;
1240 '"' => CharClassesStatus::Normal,
1241 '\\' => CharClassesStatus::LitStringEscape,
1242 _ => CharClassesStatus::LitString,
1245 CharClassesStatus::LitStringEscape => {
1246 char_kind = FullCodeCharKind::InString;
1247 CharClassesStatus::LitString
1249 CharClassesStatus::LitChar => match chr {
1250 '\\' => CharClassesStatus::LitCharEscape,
1251 '\'' => CharClassesStatus::Normal,
1252 _ => CharClassesStatus::LitChar,
1254 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
1255 CharClassesStatus::Normal => match chr {
1256 'r' => match self.base.peek().map(RichChar::get_char) {
1257 Some('#') | Some('"') => {
1258 char_kind = FullCodeCharKind::InString;
1259 CharClassesStatus::RawStringPrefix(0)
1261 _ => CharClassesStatus::Normal,
1264 char_kind = FullCodeCharKind::InString;
1265 CharClassesStatus::LitString
1268 // HACK: Work around mut borrow.
1269 match self.base.peek() {
1270 Some(next) if next.get_char() == '\\' => {
1271 self.status = CharClassesStatus::LitChar;
1272 return Some((char_kind, item));
1277 match self.base.peek() {
1278 Some(next) if next.get_char() == '\'' => CharClassesStatus::LitChar,
1279 _ => CharClassesStatus::Normal,
1282 '/' => match self.base.peek() {
1283 Some(next) if next.get_char() == '*' => {
1284 self.status = CharClassesStatus::BlockCommentOpening(1);
1285 return Some((FullCodeCharKind::StartComment, item));
1287 Some(next) if next.get_char() == '/' => {
1288 self.status = CharClassesStatus::LineComment;
1289 return Some((FullCodeCharKind::StartComment, item));
1291 _ => CharClassesStatus::Normal,
1293 _ => CharClassesStatus::Normal,
1295 CharClassesStatus::StringInBlockComment(deepness) => {
1296 char_kind = FullCodeCharKind::InStringCommented;
1298 CharClassesStatus::BlockComment(deepness)
1300 CharClassesStatus::StringInBlockComment(deepness)
1303 CharClassesStatus::BlockComment(deepness) => {
1304 assert_ne!(deepness, 0);
1305 char_kind = FullCodeCharKind::InComment;
1306 match self.base.peek() {
1307 Some(next) if next.get_char() == '/' && chr == '*' => {
1308 CharClassesStatus::BlockCommentClosing(deepness - 1)
1310 Some(next) if next.get_char() == '*' && chr == '/' => {
1311 CharClassesStatus::BlockCommentOpening(deepness + 1)
1313 _ if chr == '"' => CharClassesStatus::StringInBlockComment(deepness),
1317 CharClassesStatus::BlockCommentOpening(deepness) => {
1318 assert_eq!(chr, '*');
1319 self.status = CharClassesStatus::BlockComment(deepness);
1320 return Some((FullCodeCharKind::InComment, item));
1322 CharClassesStatus::BlockCommentClosing(deepness) => {
1323 assert_eq!(chr, '/');
1325 self.status = CharClassesStatus::Normal;
1326 return Some((FullCodeCharKind::EndComment, item));
1328 self.status = CharClassesStatus::BlockComment(deepness);
1329 return Some((FullCodeCharKind::InComment, item));
1332 CharClassesStatus::LineComment => match chr {
1334 self.status = CharClassesStatus::Normal;
1335 return Some((FullCodeCharKind::EndComment, item));
1338 self.status = CharClassesStatus::LineComment;
1339 return Some((FullCodeCharKind::InComment, item));
1343 Some((char_kind, item))
1347 /// An iterator over the lines of a string, paired with the char kind at the
1348 /// end of the line.
1349 pub(crate) struct LineClasses<'a> {
1350 base: iter::Peekable<CharClasses<std::str::Chars<'a>>>,
1351 kind: FullCodeCharKind,
1354 impl<'a> LineClasses<'a> {
1355 pub(crate) fn new(s: &'a str) -> Self {
1357 base: CharClasses::new(s.chars()).peekable(),
1358 kind: FullCodeCharKind::Normal,
1363 impl<'a> Iterator for LineClasses<'a> {
1364 type Item = (FullCodeCharKind, String);
1366 fn next(&mut self) -> Option<Self::Item> {
1369 let mut line = String::new();
1371 let start_kind = match self.base.peek() {
1372 Some((kind, _)) => *kind,
1373 None => unreachable!(),
1376 while let Some((kind, c)) = self.base.next() {
1377 // needed to set the kind of the ending character on the last line
1380 self.kind = match (start_kind, kind) {
1381 (FullCodeCharKind::Normal, FullCodeCharKind::InString) => {
1382 FullCodeCharKind::StartString
1384 (FullCodeCharKind::InString, FullCodeCharKind::Normal) => {
1385 FullCodeCharKind::EndString
1387 (FullCodeCharKind::InComment, FullCodeCharKind::InStringCommented) => {
1388 FullCodeCharKind::StartStringCommented
1390 (FullCodeCharKind::InStringCommented, FullCodeCharKind::InComment) => {
1391 FullCodeCharKind::EndStringCommented
1400 // Workaround for CRLF newline.
1401 if line.ends_with('\r') {
1405 Some((self.kind, line))
1409 /// Iterator over functional and commented parts of a string. Any part of a string is either
1410 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
1411 /// comments is functional code. Line comments contain their ending newlines.
1412 struct UngroupedCommentCodeSlices<'a> {
1414 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
1417 impl<'a> UngroupedCommentCodeSlices<'a> {
1418 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
1419 UngroupedCommentCodeSlices {
1421 iter: CharClasses::new(code.char_indices()).peekable(),
1426 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
1427 type Item = (CodeCharKind, usize, &'a str);
1429 fn next(&mut self) -> Option<Self::Item> {
1430 let (kind, (start_idx, _)) = self.iter.next()?;
1432 FullCodeCharKind::Normal | FullCodeCharKind::InString => {
1433 // Consume all the Normal code
1434 while let Some(&(char_kind, _)) = self.iter.peek() {
1435 if char_kind.is_comment() {
1438 let _ = self.iter.next();
1441 FullCodeCharKind::StartComment => {
1442 // Consume the whole comment
1444 match self.iter.next() {
1445 Some((kind, ..)) if kind.inside_comment() => continue,
1452 let slice = match self.iter.peek() {
1453 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
1454 None => &self.slice[start_idx..],
1457 if kind.is_comment() {
1458 CodeCharKind::Comment
1460 CodeCharKind::Normal
1468 /// Iterator over an alternating sequence of functional and commented parts of
1469 /// a string. The first item is always a, possibly zero length, subslice of
1470 /// functional text. Line style comments contain their ending newlines.
1471 pub(crate) struct CommentCodeSlices<'a> {
1473 last_slice_kind: CodeCharKind,
1474 last_slice_end: usize,
1477 impl<'a> CommentCodeSlices<'a> {
1478 pub(crate) fn new(slice: &'a str) -> CommentCodeSlices<'a> {
1481 last_slice_kind: CodeCharKind::Comment,
1487 impl<'a> Iterator for CommentCodeSlices<'a> {
1488 type Item = (CodeCharKind, usize, &'a str);
1490 fn next(&mut self) -> Option<Self::Item> {
1491 if self.last_slice_end == self.slice.len() {
1495 let mut sub_slice_end = self.last_slice_end;
1496 let mut first_whitespace = None;
1497 let subslice = &self.slice[self.last_slice_end..];
1498 let mut iter = CharClasses::new(subslice.char_indices());
1500 for (kind, (i, c)) in &mut iter {
1501 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal
1502 && &subslice[..2] == "//"
1503 && [' ', '\t'].contains(&c);
1505 if is_comment_connector && first_whitespace.is_none() {
1506 first_whitespace = Some(i);
1509 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
1510 let last_index = match first_whitespace {
1514 sub_slice_end = self.last_slice_end + last_index;
1518 if !is_comment_connector {
1519 first_whitespace = None;
1523 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
1524 // This was the last subslice.
1525 sub_slice_end = match first_whitespace {
1526 Some(i) => self.last_slice_end + i,
1527 None => self.slice.len(),
1531 let kind = match self.last_slice_kind {
1532 CodeCharKind::Comment => CodeCharKind::Normal,
1533 CodeCharKind::Normal => CodeCharKind::Comment,
1537 self.last_slice_end,
1538 &self.slice[self.last_slice_end..sub_slice_end],
1540 self.last_slice_end = sub_slice_end;
1541 self.last_slice_kind = kind;
1547 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
1548 /// (if it fits in the width/offset, else return `None`), else return `new`
1549 pub(crate) fn recover_comment_removed(
1552 context: &RewriteContext<'_>,
1553 ) -> Option<String> {
1554 let snippet = context.snippet(span);
1555 if snippet != new && changed_comment_content(snippet, &new) {
1556 // We missed some comments. Warn and keep the original text.
1557 if context.config.error_on_unformatted() {
1558 context.report.append(
1559 context.parse_sess.span_to_filename(span),
1560 vec![FormattingError::from_span(
1562 &context.parse_sess,
1563 ErrorKind::LostComment,
1567 Some(snippet.to_owned())
1573 pub(crate) fn filter_normal_code(code: &str) -> String {
1574 let mut buffer = String::with_capacity(code.len());
1575 LineClasses::new(code).for_each(|(kind, line)| match kind {
1576 FullCodeCharKind::Normal
1577 | FullCodeCharKind::StartString
1578 | FullCodeCharKind::InString
1579 | FullCodeCharKind::EndString => {
1580 buffer.push_str(&line);
1585 if !code.ends_with('\n') && buffer.ends_with('\n') {
1591 /// Returns `true` if the two strings of code have the same payload of comments.
1592 /// The payload of comments is everything in the string except:
1593 /// - actual code (not comments),
1594 /// - comment start/end marks,
1596 /// - '*' at the beginning of lines in block comments.
1597 fn changed_comment_content(orig: &str, new: &str) -> bool {
1598 // Cannot write this as a fn since we cannot return types containing closures.
1599 let code_comment_content = |code| {
1600 let slices = UngroupedCommentCodeSlices::new(code);
1602 .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
1603 .flat_map(|(_, _, s)| CommentReducer::new(s))
1605 let res = code_comment_content(orig).ne(code_comment_content(new));
1607 "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
1611 code_comment_content(orig).collect::<String>(),
1612 code_comment_content(new).collect::<String>()
1617 /// Iterator over the 'payload' characters of a comment.
1618 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
1619 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
1621 struct CommentReducer<'a> {
1623 at_start_line: bool,
1624 iter: std::str::Chars<'a>,
1627 impl<'a> CommentReducer<'a> {
1628 fn new(comment: &'a str) -> CommentReducer<'a> {
1629 let is_block = comment.starts_with("/*");
1630 let comment = remove_comment_header(comment);
1633 // There are no supplementary '*' on the first line.
1634 at_start_line: false,
1635 iter: comment.chars(),
1640 impl<'a> Iterator for CommentReducer<'a> {
1643 fn next(&mut self) -> Option<Self::Item> {
1645 let mut c = self.iter.next()?;
1646 if self.is_block && self.at_start_line {
1647 while c.is_whitespace() {
1648 c = self.iter.next()?;
1650 // Ignore leading '*'.
1652 c = self.iter.next()?;
1654 } else if c == '\n' {
1655 self.at_start_line = true;
1657 if !c.is_whitespace() {
1664 fn remove_comment_header(comment: &str) -> &str {
1665 if comment.starts_with("///") || comment.starts_with("//!") {
1667 } else if comment.starts_with("//") {
1669 } else if (comment.starts_with("/**") && !comment.starts_with("/**/"))
1670 || comment.starts_with("/*!")
1672 &comment[3..comment.len() - 2]
1675 comment.starts_with("/*"),
1676 format!("string '{}' is not a comment", comment)
1678 &comment[2..comment.len() - 2]
1685 use crate::shape::{Indent, Shape};
1689 let mut iter = CharClasses::new("//\n\n".chars());
1691 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
1692 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
1693 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
1694 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
1695 assert_eq!(None, iter.next());
1699 fn comment_code_slices() {
1700 let input = "code(); /* test */ 1 + 1";
1701 let mut iter = CommentCodeSlices::new(input);
1703 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
1705 (CodeCharKind::Comment, 8, "/* test */"),
1706 iter.next().unwrap()
1708 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
1709 assert_eq!(None, iter.next());
1713 fn comment_code_slices_two() {
1714 let input = "// comment\n test();";
1715 let mut iter = CommentCodeSlices::new(input);
1717 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
1719 (CodeCharKind::Comment, 0, "// comment\n"),
1720 iter.next().unwrap()
1723 (CodeCharKind::Normal, 11, " test();"),
1724 iter.next().unwrap()
1726 assert_eq!(None, iter.next());
1730 fn comment_code_slices_three() {
1731 let input = "1 // comment\n // comment2\n\n";
1732 let mut iter = CommentCodeSlices::new(input);
1734 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
1736 (CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
1737 iter.next().unwrap()
1739 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
1740 assert_eq!(None, iter.next());
1745 fn format_doc_comments() {
1746 let mut wrap_normalize_config: crate::config::Config = Default::default();
1747 wrap_normalize_config.set().wrap_comments(true);
1748 wrap_normalize_config.set().normalize_comments(true);
1750 let mut wrap_config: crate::config::Config = Default::default();
1751 wrap_config.set().wrap_comments(true);
1753 let comment = rewrite_comment(" //test",
1755 Shape::legacy(100, Indent::new(0, 100)),
1756 &wrap_normalize_config).unwrap();
1757 assert_eq!("/* test */", comment);
1759 let comment = rewrite_comment("// comment on a",
1761 Shape::legacy(10, Indent::empty()),
1762 &wrap_normalize_config).unwrap();
1763 assert_eq!("// comment\n// on a", comment);
1765 let comment = rewrite_comment("// A multi line comment\n // between args.",
1767 Shape::legacy(60, Indent::new(0, 12)),
1768 &wrap_normalize_config).unwrap();
1769 assert_eq!("// A multi line comment\n // between args.", comment);
1771 let input = "// comment";
1774 let comment = rewrite_comment(input,
1776 Shape::legacy(9, Indent::new(0, 69)),
1777 &wrap_normalize_config).unwrap();
1778 assert_eq!(expected, comment);
1780 let comment = rewrite_comment("/* trimmed */",
1782 Shape::legacy(100, Indent::new(0, 100)),
1783 &wrap_normalize_config).unwrap();
1784 assert_eq!("/* trimmed */", comment);
1786 // Check that different comment style are properly recognised.
1787 let comment = rewrite_comment(r#"/// test1
1793 Shape::legacy(100, Indent::new(0, 0)),
1794 &wrap_normalize_config).unwrap();
1795 assert_eq!("/// test1\n/// test2\n// test3", comment);
1797 // Check that the blank line marks the end of a commented paragraph.
1798 let comment = rewrite_comment(r#"// test1
1802 Shape::legacy(100, Indent::new(0, 0)),
1803 &wrap_normalize_config).unwrap();
1804 assert_eq!("// test1\n\n// test2", comment);
1806 // Check that the blank line marks the end of a custom-commented paragraph.
1807 let comment = rewrite_comment(r#"//@ test1
1811 Shape::legacy(100, Indent::new(0, 0)),
1812 &wrap_normalize_config).unwrap();
1813 assert_eq!("//@ test1\n\n//@ test2", comment);
1815 // Check that bare lines are just indented but otherwise left unchanged.
1816 let comment = rewrite_comment(r#"// test1
1823 Shape::legacy(100, Indent::new(0, 0)),
1824 &wrap_config).unwrap();
1825 assert_eq!("// test1\n/*\n a bare line!\n\n another bare line!\n*/", comment);
1828 // This is probably intended to be a non-test fn, but it is not used.
1829 // We should keep this around unless it helps us test stuff to remove it.
1830 fn uncommented(text: &str) -> String {
1831 CharClasses::new(text.chars())
1832 .filter_map(|(s, c)| match s {
1833 FullCodeCharKind::Normal | FullCodeCharKind::InString => Some(c),
1840 fn test_uncommented() {
1841 assert_eq!(&uncommented("abc/*...*/"), "abc");
1843 &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
1846 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
1850 fn test_contains_comment() {
1851 assert_eq!(contains_comment("abc"), false);
1852 assert_eq!(contains_comment("abc // qsdf"), true);
1853 assert_eq!(contains_comment("abc /* kqsdf"), true);
1854 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
1858 fn test_find_uncommented() {
1859 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
1860 assert_eq!(expected, haystack.find_uncommented(needle));
1863 check("/*/ */test", "test", Some(6));
1864 check("//test\ntest", "test", Some(7));
1865 check("/* comment only */", "whatever", None);
1867 "/* comment */ some text /* more commentary */ result",
1871 check("sup // sup", "p", Some(2));
1872 check("sup", "x", None);
1873 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
1874 check("/*sup yo? \n sup*/ sup", "p", Some(20));
1875 check("hel/*lohello*/lo", "hello", None);
1876 check("acb", "ab", None);
1877 check(",/*A*/ ", ",", Some(0));
1878 check("abc", "abc", Some(0));
1879 check("/* abc */", "abc", None);
1880 check("/**/abc/* */", "abc", Some(4));
1881 check("\"/* abc */\"", "abc", Some(4));
1882 check("\"/* abc", "abc", Some(4));
1886 fn test_filter_normal_code() {
1889 println!("hello, world");
1892 assert_eq!(s, filter_normal_code(s));
1893 let s_with_comment = r#"
1896 println!("hello, world");
1899 assert_eq!(s, filter_normal_code(s_with_comment));