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::SingleBullet | CommentStyle::DoubleBullet | CommentStyle::Exclamation => {
100 pub(crate) fn line_start(&self) -> &'a str {
102 CommentStyle::DoubleSlash => "// ",
103 CommentStyle::TripleSlash => "/// ",
104 CommentStyle::Doc => "//! ",
105 CommentStyle::SingleBullet | CommentStyle::DoubleBullet | CommentStyle::Exclamation => {
108 CommentStyle::Custom(opener) => opener,
112 pub(crate) fn to_str_tuplet(&self) -> (&'a str, &'a str, &'a str) {
113 (self.opener(), self.closer(), self.line_start())
117 pub(crate) fn comment_style(orig: &str, normalize_comments: bool) -> CommentStyle<'_> {
118 if !normalize_comments {
119 if orig.starts_with("/**") && !orig.starts_with("/**/") {
120 CommentStyle::DoubleBullet
121 } else if orig.starts_with("/*!") {
122 CommentStyle::Exclamation
123 } else if orig.starts_with("/*") {
124 CommentStyle::SingleBullet
125 } else if orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/') {
126 CommentStyle::TripleSlash
127 } else if orig.starts_with("//!") {
129 } else if is_custom_comment(orig) {
130 CommentStyle::Custom(custom_opener(orig))
132 CommentStyle::DoubleSlash
134 } else if (orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/'))
135 || (orig.starts_with("/**") && !orig.starts_with("/**/"))
137 CommentStyle::TripleSlash
138 } else if orig.starts_with("//!") || orig.starts_with("/*!") {
140 } else if is_custom_comment(orig) {
141 CommentStyle::Custom(custom_opener(orig))
143 CommentStyle::DoubleSlash
147 /// Returns true if the last line of the passed string finishes with a block-comment.
148 pub(crate) fn is_last_comment_block(s: &str) -> bool {
149 s.trim_end().ends_with("*/")
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(crate) fn combine_strs_with_missing_comments(
158 context: &RewriteContext<'_>,
164 ) -> Option<String> {
166 "combine_strs_with_missing_comments `{}` `{}` {:?} {:?}",
174 String::with_capacity(prev_str.len() + next_str.len() + shape.indent.width() + 128);
175 result.push_str(prev_str);
176 let mut allow_one_line = !prev_str.contains('\n') && !next_str.contains('\n');
177 let first_sep = if prev_str.is_empty() || next_str.is_empty() {
182 let mut one_line_width =
183 last_line_width(prev_str) + first_line_width(next_str) + first_sep.len();
185 let config = context.config;
186 let indent = shape.indent;
187 let missing_comment = rewrite_missing_comment(span, shape, context)?;
189 if missing_comment.is_empty() {
190 if allow_extend && prev_str.len() + first_sep.len() + next_str.len() <= shape.width {
191 result.push_str(first_sep);
192 } else if !prev_str.is_empty() {
193 result.push_str(&indent.to_string_with_newline(config))
195 result.push_str(next_str);
199 // We have a missing comment between the first expression and the second expression.
201 // Peek the the original source code and find out whether there is a newline between the first
202 // expression and the second expression or the missing comment. We will preserve the original
203 // layout whenever possible.
204 let original_snippet = context.snippet(span);
205 let prefer_same_line = if let Some(pos) = original_snippet.find('/') {
206 !original_snippet[..pos].contains('\n')
208 !original_snippet.contains('\n')
211 one_line_width -= first_sep.len();
212 let first_sep = if prev_str.is_empty() || missing_comment.is_empty() {
215 let one_line_width = last_line_width(prev_str) + first_line_width(&missing_comment) + 1;
216 if prefer_same_line && one_line_width <= shape.width {
219 indent.to_string_with_newline(config)
222 result.push_str(&first_sep);
223 result.push_str(&missing_comment);
225 let second_sep = if missing_comment.is_empty() || next_str.is_empty() {
227 } else if missing_comment.starts_with("//") {
228 indent.to_string_with_newline(config)
230 one_line_width += missing_comment.len() + first_sep.len() + 1;
231 allow_one_line &= !missing_comment.starts_with("//") && !missing_comment.contains('\n');
232 if prefer_same_line && allow_one_line && one_line_width <= shape.width {
235 indent.to_string_with_newline(config)
238 result.push_str(&second_sep);
239 result.push_str(next_str);
244 pub(crate) fn rewrite_doc_comment(orig: &str, shape: Shape, config: &Config) -> Option<String> {
245 identify_comment(orig, false, shape, config, true)
248 pub(crate) fn rewrite_comment(
253 ) -> Option<String> {
254 identify_comment(orig, block_style, shape, config, false)
262 is_doc_comment: bool,
263 ) -> Option<String> {
264 let style = comment_style(orig, false);
266 // Computes the byte length of line taking into account a newline if the line is part of a
268 fn compute_len(orig: &str, line: &str) -> usize {
269 if orig.len() > line.len() {
270 if orig.as_bytes()[line.len()] == b'\r' {
280 // Get the first group of line comments having the same commenting style.
282 // Returns a tuple with:
283 // - a boolean indicating if there is a blank line
284 // - a number indicating the size of the first group of comments
285 fn consume_same_line_comments(
286 style: CommentStyle<'_>,
290 let mut first_group_ending = 0;
293 for line in orig.lines() {
294 let trimmed_line = line.trim_start();
295 if trimmed_line.is_empty() {
298 } else if trimmed_line.starts_with(line_start)
299 || comment_style(trimmed_line, false) == style
301 first_group_ending += compute_len(&orig[first_group_ending..], line);
306 (hbl, first_group_ending)
309 let (has_bare_lines, first_group_ending) = match style {
310 CommentStyle::DoubleSlash | CommentStyle::TripleSlash | CommentStyle::Doc => {
311 let line_start = style.line_start().trim_start();
312 consume_same_line_comments(style, orig, line_start)
314 CommentStyle::Custom(opener) => {
315 let trimmed_opener = opener.trim_end();
316 consume_same_line_comments(style, orig, trimmed_opener)
318 // for a block comment, search for the closing symbol
319 CommentStyle::DoubleBullet | CommentStyle::SingleBullet | CommentStyle::Exclamation => {
320 let closer = style.closer().trim_start();
321 let mut count = orig.matches(closer).count();
322 let mut closing_symbol_offset = 0;
324 let mut first = true;
325 for line in orig.lines() {
326 closing_symbol_offset += compute_len(&orig[closing_symbol_offset..], line);
327 let mut trimmed_line = line.trim_start();
328 if !trimmed_line.starts_with('*')
329 && !trimmed_line.starts_with("//")
330 && !trimmed_line.starts_with("/*")
335 // Remove opener from consideration when searching for closer
337 let opener = style.opener().trim_end();
338 trimmed_line = &trimmed_line[opener.len()..];
341 if trimmed_line.ends_with(closer) {
348 (hbl, closing_symbol_offset)
352 let (first_group, rest) = orig.split_at(first_group_ending);
353 let rewritten_first_group =
354 if !config.normalize_comments() && has_bare_lines && style.is_block_comment() {
355 trim_left_preserve_layout(first_group, shape.indent, config)?
356 } else if !config.normalize_comments()
357 && !config.wrap_comments()
358 && !config.format_code_in_doc_comments()
360 light_rewrite_comment(first_group, shape.indent, config, is_doc_comment)
362 rewrite_comment_inner(
368 is_doc_comment || style.is_doc_comment(),
372 Some(rewritten_first_group)
384 rewritten_first_group,
385 // insert back the blank line
386 if has_bare_lines && style.is_line_comment() {
391 shape.indent.to_string(config),
398 /// Attributes for code blocks in rustdoc.
399 /// See https://doc.rust-lang.org/rustdoc/print.html#attributes
400 enum CodeBlockAttribute {
409 impl CodeBlockAttribute {
410 fn new(attribute: &str) -> CodeBlockAttribute {
412 "rust" | "" => CodeBlockAttribute::Rust,
413 "ignore" => CodeBlockAttribute::Ignore,
414 "text" => CodeBlockAttribute::Text,
415 "should_panic" => CodeBlockAttribute::ShouldPanic,
416 "no_run" => CodeBlockAttribute::NoRun,
417 "compile_fail" => CodeBlockAttribute::CompileFail,
418 _ => CodeBlockAttribute::Text,
423 /// Block that is formatted as an item.
425 /// An item starts with either a star `*` or a dash `-`. Different level of indentation are
426 /// handled by shrinking the shape accordingly.
427 struct ItemizedBlock {
428 /// the lines that are identified as part of an itemized block
430 /// the number of whitespaces up to the item sigil
432 /// the string that marks the start of an item
434 /// sequence of whitespaces to prefix new lines that are part of the item
439 /// Returns `true` if the line is formatted as an item
440 fn is_itemized_line(line: &str) -> bool {
441 let trimmed = line.trim_start();
442 trimmed.starts_with("* ") || trimmed.starts_with("- ")
445 /// Creates a new ItemizedBlock described with the given line.
446 /// The `is_itemized_line` needs to be called first.
447 fn new(line: &str) -> ItemizedBlock {
448 let space_to_sigil = line.chars().take_while(|c| c.is_whitespace()).count();
449 let indent = space_to_sigil + 2;
451 lines: vec![line[indent..].to_string()],
453 opener: line[..indent].to_string(),
454 line_start: " ".repeat(indent),
458 /// Returns a `StringFormat` used for formatting the content of an item.
459 fn create_string_format<'a>(&'a self, fmt: &'a StringFormat<'_>) -> StringFormat<'a> {
465 shape: Shape::legacy(fmt.shape.width.saturating_sub(self.indent), Indent::empty()),
471 /// Returns `true` if the line is part of the current itemized block.
472 /// If it is, then it is added to the internal lines list.
473 fn add_line(&mut self, line: &str) -> bool {
474 if !ItemizedBlock::is_itemized_line(line)
475 && self.indent <= line.chars().take_while(|c| c.is_whitespace()).count()
477 self.lines.push(line.to_string());
483 /// Returns the block as a string, with each line trimmed at the start.
484 fn trimmed_block_as_string(&self) -> String {
487 .map(|line| format!("{} ", line.trim_start()))
491 /// Returns the block as a string under its original form.
492 fn original_block_as_string(&self) -> String {
493 self.lines.join("\n")
497 struct CommentRewrite<'a> {
499 code_block_buffer: String,
500 is_prev_line_multi_line: bool,
501 code_block_attr: Option<CodeBlockAttribute>,
502 item_block: Option<ItemizedBlock>,
503 comment_line_separator: String,
507 fmt: StringFormat<'a>,
514 impl<'a> CommentRewrite<'a> {
520 ) -> CommentRewrite<'a> {
521 let (opener, closer, line_start) = if block_style {
522 CommentStyle::SingleBullet.to_str_tuplet()
524 comment_style(orig, config.normalize_comments()).to_str_tuplet()
527 let max_width = shape
529 .checked_sub(closer.len() + opener.len())
531 let indent_str = shape.indent.to_string_with_newline(config).to_string();
532 let fmt_indent = shape.indent + (opener.len() - line_start.len());
534 let mut cr = CommentRewrite {
535 result: String::with_capacity(orig.len() * 2),
536 code_block_buffer: String::with_capacity(128),
537 is_prev_line_multi_line: false,
538 code_block_attr: None,
540 comment_line_separator: format!("{}{}", indent_str, line_start),
550 shape: Shape::legacy(max_width, fmt_indent),
555 opener: opener.to_owned(),
556 closer: closer.to_owned(),
557 line_start: line_start.to_owned(),
559 cr.result.push_str(opener);
563 fn join_block(s: &str, sep: &str) -> String {
564 let mut result = String::with_capacity(s.len() + 128);
565 let mut iter = s.lines().peekable();
566 while let Some(line) = iter.next() {
567 result.push_str(line);
568 result.push_str(match iter.peek() {
569 Some(next_line) if next_line.is_empty() => sep.trim_end(),
577 fn finish(mut self) -> String {
578 if !self.code_block_buffer.is_empty() {
579 // There is a code block that is not properly enclosed by backticks.
580 // We will leave them untouched.
581 self.result.push_str(&self.comment_line_separator);
582 self.result.push_str(&Self::join_block(
583 &trim_custom_comment_prefix(&self.code_block_buffer),
584 &self.comment_line_separator,
588 if let Some(ref ib) = self.item_block {
589 // the last few lines are part of an itemized block
590 self.fmt.shape = Shape::legacy(self.max_width, self.fmt_indent);
591 let item_fmt = ib.create_string_format(&self.fmt);
592 self.result.push_str(&self.comment_line_separator);
593 self.result.push_str(&ib.opener);
594 match rewrite_string(
595 &ib.trimmed_block_as_string(),
597 self.max_width.saturating_sub(ib.indent),
599 Some(s) => self.result.push_str(&Self::join_block(
601 &format!("{}{}", self.comment_line_separator, ib.line_start),
603 None => self.result.push_str(&Self::join_block(
604 &ib.original_block_as_string(),
605 &self.comment_line_separator,
610 self.result.push_str(&self.closer);
611 if self.result.ends_with(&self.opener) && self.opener.ends_with(' ') {
624 has_leading_whitespace: bool,
626 let is_last = i == count_newlines(orig);
628 if let Some(ref mut ib) = self.item_block {
629 if ib.add_line(&line) {
632 self.is_prev_line_multi_line = false;
633 self.fmt.shape = Shape::legacy(self.max_width, self.fmt_indent);
634 let item_fmt = ib.create_string_format(&self.fmt);
635 self.result.push_str(&self.comment_line_separator);
636 self.result.push_str(&ib.opener);
637 match rewrite_string(
638 &ib.trimmed_block_as_string(),
640 self.max_width.saturating_sub(ib.indent),
642 Some(s) => self.result.push_str(&Self::join_block(
644 &format!("{}{}", self.comment_line_separator, ib.line_start),
646 None => self.result.push_str(&Self::join_block(
647 &ib.original_block_as_string(),
648 &self.comment_line_separator,
651 } else if self.code_block_attr.is_some() {
652 if line.starts_with("```") {
653 let code_block = match self.code_block_attr.as_ref().unwrap() {
654 CodeBlockAttribute::Ignore | CodeBlockAttribute::Text => {
655 trim_custom_comment_prefix(&self.code_block_buffer)
657 _ if self.code_block_buffer.is_empty() => String::new(),
659 let mut config = self.fmt.config.clone();
660 config.set().wrap_comments(false);
661 if config.format_code_in_doc_comments() {
663 crate::format_code_block(&self.code_block_buffer, &config)
665 trim_custom_comment_prefix(&s.snippet)
667 trim_custom_comment_prefix(&self.code_block_buffer)
670 trim_custom_comment_prefix(&self.code_block_buffer)
674 if !code_block.is_empty() {
675 self.result.push_str(&self.comment_line_separator);
677 .push_str(&Self::join_block(&code_block, &self.comment_line_separator));
679 self.code_block_buffer.clear();
680 self.result.push_str(&self.comment_line_separator);
681 self.result.push_str(line);
682 self.code_block_attr = None;
684 self.code_block_buffer
685 .push_str(&hide_sharp_behind_comment(line));
686 self.code_block_buffer.push('\n');
691 self.code_block_attr = None;
692 self.item_block = None;
693 if line.starts_with("```") {
694 self.code_block_attr = Some(CodeBlockAttribute::new(&line[3..]))
695 } else if self.fmt.config.wrap_comments() && ItemizedBlock::is_itemized_line(&line) {
696 let ib = ItemizedBlock::new(&line);
697 self.item_block = Some(ib);
701 if self.result == self.opener {
702 let force_leading_whitespace = &self.opener == "/* " && count_newlines(orig) == 0;
703 if !has_leading_whitespace && !force_leading_whitespace && self.result.ends_with(' ') {
709 } else if self.is_prev_line_multi_line && !line.is_empty() {
710 self.result.push(' ')
711 } else if is_last && line.is_empty() {
712 // trailing blank lines are unwanted
713 if !self.closer.is_empty() {
714 self.result.push_str(&self.indent_str);
718 self.result.push_str(&self.comment_line_separator);
719 if !has_leading_whitespace && self.result.ends_with(' ') {
724 if self.fmt.config.wrap_comments()
725 && unicode_str_width(line) > self.fmt.shape.width
728 match rewrite_string(line, &self.fmt, self.max_width) {
730 self.is_prev_line_multi_line = s.contains('\n');
731 self.result.push_str(s);
733 None if self.is_prev_line_multi_line => {
734 // We failed to put the current `line` next to the previous `line`.
735 // Remove the trailing space, then start rewrite on the next line.
737 self.result.push_str(&self.comment_line_separator);
738 self.fmt.shape = Shape::legacy(self.max_width, self.fmt_indent);
739 match rewrite_string(line, &self.fmt, self.max_width) {
741 self.is_prev_line_multi_line = s.contains('\n');
742 self.result.push_str(s);
745 self.is_prev_line_multi_line = false;
746 self.result.push_str(line);
751 self.is_prev_line_multi_line = false;
752 self.result.push_str(line);
756 self.fmt.shape = if self.is_prev_line_multi_line {
758 let offset = 1 + last_line_width(&self.result) - self.line_start.len();
760 width: self.max_width.saturating_sub(offset),
761 indent: self.fmt_indent,
762 offset: self.fmt.shape.offset + offset,
765 Shape::legacy(self.max_width, self.fmt_indent)
768 if line.is_empty() && self.result.ends_with(' ') && !is_last {
769 // Remove space if this is an empty comment or a doc comment.
772 self.result.push_str(line);
773 self.fmt.shape = Shape::legacy(self.max_width, self.fmt_indent);
774 self.is_prev_line_multi_line = false;
781 fn rewrite_comment_inner(
784 style: CommentStyle<'_>,
787 is_doc_comment: bool,
788 ) -> Option<String> {
789 let mut rewriter = CommentRewrite::new(orig, block_style, shape, config);
791 let line_breaks = count_newlines(orig.trim_end());
795 .map(|(i, mut line)| {
796 line = trim_end_unless_two_whitespaces(line.trim_start(), is_doc_comment);
798 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
799 line = line[..(line.len() - 2)].trim_end();
804 .map(|s| left_trim_comment_line(s, &style))
805 .map(|(line, has_leading_whitespace)| {
806 if orig.starts_with("/*") && line_breaks == 0 {
809 has_leading_whitespace || config.normalize_comments(),
812 (line, has_leading_whitespace || config.normalize_comments())
816 for (i, (line, has_leading_whitespace)) in lines.enumerate() {
817 if rewriter.handle_line(orig, i, line, has_leading_whitespace) {
822 Some(rewriter.finish())
825 const RUSTFMT_CUSTOM_COMMENT_PREFIX: &str = "//#### ";
827 fn hide_sharp_behind_comment(s: &str) -> Cow<'_, str> {
828 let s_trimmed = s.trim();
829 if s_trimmed.starts_with("# ") || s_trimmed == "#" {
830 Cow::from(format!("{}{}", RUSTFMT_CUSTOM_COMMENT_PREFIX, s))
836 fn trim_custom_comment_prefix(s: &str) -> String {
839 let left_trimmed = line.trim_start();
840 if left_trimmed.starts_with(RUSTFMT_CUSTOM_COMMENT_PREFIX) {
841 left_trimmed.trim_start_matches(RUSTFMT_CUSTOM_COMMENT_PREFIX)
850 /// Returns `true` if the given string MAY include URLs or alike.
851 fn has_url(s: &str) -> bool {
852 // This function may return false positive, but should get its job done in most cases.
853 s.contains("https://") || s.contains("http://") || s.contains("ftp://") || s.contains("file://")
856 /// Given the span, rewrite the missing comment inside it if available.
857 /// Note that the given span must only include comments (or leading/trailing whitespaces).
858 pub(crate) fn rewrite_missing_comment(
861 context: &RewriteContext<'_>,
862 ) -> Option<String> {
863 let missing_snippet = context.snippet(span);
864 let trimmed_snippet = missing_snippet.trim();
865 // check the span starts with a comment
866 let pos = trimmed_snippet.find('/');
867 if !trimmed_snippet.is_empty() && pos.is_some() {
868 rewrite_comment(trimmed_snippet, false, shape, context.config)
874 /// Recover the missing comments in the specified span, if available.
875 /// The layout of the comments will be preserved as long as it does not break the code
876 /// and its total width does not exceed the max width.
877 pub(crate) fn recover_missing_comment_in_span(
880 context: &RewriteContext<'_>,
882 ) -> Option<String> {
883 let missing_comment = rewrite_missing_comment(span, shape, context)?;
884 if missing_comment.is_empty() {
887 let missing_snippet = context.snippet(span);
888 let pos = missing_snippet.find('/')?;
890 let total_width = missing_comment.len() + used_width + 1;
891 let force_new_line_before_comment =
892 missing_snippet[..pos].contains('\n') || total_width > context.config.max_width();
893 let sep = if force_new_line_before_comment {
894 shape.indent.to_string_with_newline(context.config)
898 Some(format!("{}{}", sep, missing_comment))
902 /// Trim trailing whitespaces unless they consist of two or more whitespaces.
903 fn trim_end_unless_two_whitespaces(s: &str, is_doc_comment: bool) -> &str {
904 if is_doc_comment && s.ends_with(" ") {
911 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
912 fn light_rewrite_comment(
916 is_doc_comment: bool,
918 let lines: Vec<&str> = orig
921 // This is basically just l.trim(), but in the case that a line starts
922 // with `*` we want to leave one space before it, so it aligns with the
924 let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
925 let left_trimmed = if let Some(fnw) = first_non_whitespace {
926 if l.as_bytes()[fnw] == b'*' && fnw > 0 {
934 // Preserve markdown's double-space line break syntax in doc comment.
935 trim_end_unless_two_whitespaces(left_trimmed, is_doc_comment)
938 lines.join(&format!("\n{}", offset.to_string(config)))
941 /// Trims comment characters and possibly a single space from the left of a string.
942 /// Does not trim all whitespace. If a single space is trimmed from the left of the string,
943 /// this function returns true.
944 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle<'_>) -> (&'a str, bool) {
945 if line.starts_with("//! ")
946 || line.starts_with("/// ")
947 || line.starts_with("/*! ")
948 || line.starts_with("/** ")
951 } else if let CommentStyle::Custom(opener) = *style {
952 if line.starts_with(opener) {
953 (&line[opener.len()..], true)
955 (&line[opener.trim_end().len()..], false)
957 } else if line.starts_with("/* ")
958 || line.starts_with("// ")
959 || line.starts_with("//!")
960 || line.starts_with("///")
961 || line.starts_with("** ")
962 || line.starts_with("/*!")
963 || (line.starts_with("/**") && !line.starts_with("/**/"))
965 (&line[3..], line.chars().nth(2).unwrap() == ' ')
966 } else if line.starts_with("/*")
967 || line.starts_with("* ")
968 || line.starts_with("//")
969 || line.starts_with("**")
971 (&line[2..], line.chars().nth(1).unwrap() == ' ')
972 } else if line.starts_with('*') {
975 (line, line.starts_with(' '))
979 pub(crate) trait FindUncommented {
980 fn find_uncommented(&self, pat: &str) -> Option<usize>;
983 impl FindUncommented for str {
984 fn find_uncommented(&self, pat: &str) -> Option<usize> {
985 let mut needle_iter = pat.chars();
986 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
987 match needle_iter.next() {
989 return Some(i - pat.len());
991 Some(c) => match kind {
992 FullCodeCharKind::Normal | FullCodeCharKind::InString if b == c => {}
994 needle_iter = pat.chars();
1000 // Handle case where the pattern is a suffix of the search string
1001 match needle_iter.next() {
1003 None => Some(self.len() - pat.len()),
1008 // Returns the first byte position after the first comment. The given string
1009 // is expected to be prefixed by a comment, including delimiters.
1010 // Good: `/* /* inner */ outer */ code();`
1011 // Bad: `code(); // hello\n world!`
1012 pub(crate) fn find_comment_end(s: &str) -> Option<usize> {
1013 let mut iter = CharClasses::new(s.char_indices());
1014 for (kind, (i, _c)) in &mut iter {
1015 if kind == FullCodeCharKind::Normal || kind == FullCodeCharKind::InString {
1020 // Handle case where the comment ends at the end of `s`.
1021 if iter.status == CharClassesStatus::Normal {
1028 /// Returns `true` if text contains any comment.
1029 pub(crate) fn contains_comment(text: &str) -> bool {
1030 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
1033 pub(crate) struct CharClasses<T>
1039 status: CharClassesStatus,
1042 pub(crate) trait RichChar {
1043 fn get_char(&self) -> char;
1046 impl RichChar for char {
1047 fn get_char(&self) -> char {
1052 impl RichChar for (usize, char) {
1053 fn get_char(&self) -> char {
1058 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
1059 enum CharClassesStatus {
1061 /// Character is within a string
1064 /// Character is within a raw string
1066 RawStringPrefix(u32),
1067 RawStringSuffix(u32),
1070 /// Character inside a block comment, with the integer indicating the nesting deepness of the
1073 /// Character inside a block-commented string, with the integer indicating the nesting deepness
1075 StringInBlockComment(u32),
1076 /// Status when the '/' has been consumed, but not yet the '*', deepness is
1077 /// the new deepness (after the comment opening).
1078 BlockCommentOpening(u32),
1079 /// Status when the '*' has been consumed, but not yet the '/', deepness is
1080 /// the new deepness (after the comment closing).
1081 BlockCommentClosing(u32),
1082 /// Character is within a line comment
1086 /// Distinguish between functional part of code and comments
1087 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
1088 pub(crate) enum CodeCharKind {
1093 /// Distinguish between functional part of code and comments,
1094 /// describing opening and closing of comments for ease when chunking
1095 /// code from tagged characters
1096 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
1097 pub(crate) enum FullCodeCharKind {
1099 /// The first character of a comment, there is only one for a comment (always '/')
1101 /// Any character inside a comment including the second character of comment
1102 /// marks ("//", "/*")
1104 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
1106 /// Start of a mutlitine string inside a comment
1107 StartStringCommented,
1108 /// End of a mutlitine string inside a comment
1110 /// Inside a commented string
1112 /// Start of a mutlitine string
1114 /// End of a mutlitine string
1116 /// Inside a string.
1120 impl FullCodeCharKind {
1121 pub(crate) fn is_comment(self) -> bool {
1123 FullCodeCharKind::StartComment
1124 | FullCodeCharKind::InComment
1125 | FullCodeCharKind::EndComment
1126 | FullCodeCharKind::StartStringCommented
1127 | FullCodeCharKind::InStringCommented
1128 | FullCodeCharKind::EndStringCommented => true,
1133 /// Returns true if the character is inside a comment
1134 pub(crate) fn inside_comment(self) -> bool {
1136 FullCodeCharKind::InComment
1137 | FullCodeCharKind::StartStringCommented
1138 | FullCodeCharKind::InStringCommented
1139 | FullCodeCharKind::EndStringCommented => true,
1144 pub(crate) fn is_string(self) -> bool {
1145 self == FullCodeCharKind::InString || self == FullCodeCharKind::StartString
1148 /// Returns true if the character is within a commented string
1149 pub(crate) fn is_commented_string(self) -> bool {
1150 self == FullCodeCharKind::InStringCommented
1151 || self == FullCodeCharKind::StartStringCommented
1154 fn to_codecharkind(self) -> CodeCharKind {
1155 if self.is_comment() {
1156 CodeCharKind::Comment
1158 CodeCharKind::Normal
1163 impl<T> CharClasses<T>
1168 pub(crate) fn new(base: T) -> CharClasses<T> {
1170 base: multipeek(base),
1171 status: CharClassesStatus::Normal,
1176 fn is_raw_string_suffix<T>(iter: &mut MultiPeek<T>, count: u32) -> bool
1183 Some(c) if c.get_char() == '#' => continue,
1190 impl<T> Iterator for CharClasses<T>
1195 type Item = (FullCodeCharKind, T::Item);
1197 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
1198 let item = self.base.next()?;
1199 let chr = item.get_char();
1200 let mut char_kind = FullCodeCharKind::Normal;
1201 self.status = match self.status {
1202 CharClassesStatus::LitRawString(sharps) => {
1203 char_kind = FullCodeCharKind::InString;
1207 char_kind = FullCodeCharKind::Normal;
1208 CharClassesStatus::Normal
1209 } else if is_raw_string_suffix(&mut self.base, sharps) {
1210 CharClassesStatus::RawStringSuffix(sharps)
1212 CharClassesStatus::LitRawString(sharps)
1215 _ => CharClassesStatus::LitRawString(sharps),
1218 CharClassesStatus::RawStringPrefix(sharps) => {
1219 char_kind = FullCodeCharKind::InString;
1221 '#' => CharClassesStatus::RawStringPrefix(sharps + 1),
1222 '"' => CharClassesStatus::LitRawString(sharps),
1223 _ => CharClassesStatus::Normal, // Unreachable.
1226 CharClassesStatus::RawStringSuffix(sharps) => {
1230 CharClassesStatus::Normal
1232 char_kind = FullCodeCharKind::InString;
1233 CharClassesStatus::RawStringSuffix(sharps - 1)
1236 _ => CharClassesStatus::Normal, // Unreachable
1239 CharClassesStatus::LitString => {
1240 char_kind = FullCodeCharKind::InString;
1242 '"' => CharClassesStatus::Normal,
1243 '\\' => CharClassesStatus::LitStringEscape,
1244 _ => CharClassesStatus::LitString,
1247 CharClassesStatus::LitStringEscape => {
1248 char_kind = FullCodeCharKind::InString;
1249 CharClassesStatus::LitString
1251 CharClassesStatus::LitChar => match chr {
1252 '\\' => CharClassesStatus::LitCharEscape,
1253 '\'' => CharClassesStatus::Normal,
1254 _ => CharClassesStatus::LitChar,
1256 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
1257 CharClassesStatus::Normal => match chr {
1258 'r' => match self.base.peek().map(RichChar::get_char) {
1259 Some('#') | Some('"') => {
1260 char_kind = FullCodeCharKind::InString;
1261 CharClassesStatus::RawStringPrefix(0)
1263 _ => CharClassesStatus::Normal,
1266 char_kind = FullCodeCharKind::InString;
1267 CharClassesStatus::LitString
1270 // HACK: Work around mut borrow.
1271 match self.base.peek() {
1272 Some(next) if next.get_char() == '\\' => {
1273 self.status = CharClassesStatus::LitChar;
1274 return Some((char_kind, item));
1279 match self.base.peek() {
1280 Some(next) if next.get_char() == '\'' => CharClassesStatus::LitChar,
1281 _ => CharClassesStatus::Normal,
1284 '/' => match self.base.peek() {
1285 Some(next) if next.get_char() == '*' => {
1286 self.status = CharClassesStatus::BlockCommentOpening(1);
1287 return Some((FullCodeCharKind::StartComment, item));
1289 Some(next) if next.get_char() == '/' => {
1290 self.status = CharClassesStatus::LineComment;
1291 return Some((FullCodeCharKind::StartComment, item));
1293 _ => CharClassesStatus::Normal,
1295 _ => CharClassesStatus::Normal,
1297 CharClassesStatus::StringInBlockComment(deepness) => {
1298 char_kind = FullCodeCharKind::InStringCommented;
1300 CharClassesStatus::BlockComment(deepness)
1302 CharClassesStatus::StringInBlockComment(deepness)
1305 CharClassesStatus::BlockComment(deepness) => {
1306 assert_ne!(deepness, 0);
1307 char_kind = FullCodeCharKind::InComment;
1308 match self.base.peek() {
1309 Some(next) if next.get_char() == '/' && chr == '*' => {
1310 CharClassesStatus::BlockCommentClosing(deepness - 1)
1312 Some(next) if next.get_char() == '*' && chr == '/' => {
1313 CharClassesStatus::BlockCommentOpening(deepness + 1)
1315 _ if chr == '"' => CharClassesStatus::StringInBlockComment(deepness),
1319 CharClassesStatus::BlockCommentOpening(deepness) => {
1320 assert_eq!(chr, '*');
1321 self.status = CharClassesStatus::BlockComment(deepness);
1322 return Some((FullCodeCharKind::InComment, item));
1324 CharClassesStatus::BlockCommentClosing(deepness) => {
1325 assert_eq!(chr, '/');
1327 self.status = CharClassesStatus::Normal;
1328 return Some((FullCodeCharKind::EndComment, item));
1330 self.status = CharClassesStatus::BlockComment(deepness);
1331 return Some((FullCodeCharKind::InComment, item));
1334 CharClassesStatus::LineComment => match chr {
1336 self.status = CharClassesStatus::Normal;
1337 return Some((FullCodeCharKind::EndComment, item));
1340 self.status = CharClassesStatus::LineComment;
1341 return Some((FullCodeCharKind::InComment, item));
1345 Some((char_kind, item))
1349 /// An iterator over the lines of a string, paired with the char kind at the
1350 /// end of the line.
1351 pub(crate) struct LineClasses<'a> {
1352 base: iter::Peekable<CharClasses<std::str::Chars<'a>>>,
1353 kind: FullCodeCharKind,
1356 impl<'a> LineClasses<'a> {
1357 pub(crate) fn new(s: &'a str) -> Self {
1359 base: CharClasses::new(s.chars()).peekable(),
1360 kind: FullCodeCharKind::Normal,
1365 impl<'a> Iterator for LineClasses<'a> {
1366 type Item = (FullCodeCharKind, String);
1368 fn next(&mut self) -> Option<Self::Item> {
1371 let mut line = String::new();
1373 let start_kind = match self.base.peek() {
1374 Some((kind, _)) => *kind,
1375 None => unreachable!(),
1378 while let Some((kind, c)) = self.base.next() {
1379 // needed to set the kind of the ending character on the last line
1382 self.kind = match (start_kind, kind) {
1383 (FullCodeCharKind::Normal, FullCodeCharKind::InString) => {
1384 FullCodeCharKind::StartString
1386 (FullCodeCharKind::InString, FullCodeCharKind::Normal) => {
1387 FullCodeCharKind::EndString
1389 (FullCodeCharKind::InComment, FullCodeCharKind::InStringCommented) => {
1390 FullCodeCharKind::StartStringCommented
1392 (FullCodeCharKind::InStringCommented, FullCodeCharKind::InComment) => {
1393 FullCodeCharKind::EndStringCommented
1402 // Workaround for CRLF newline.
1403 if line.ends_with('\r') {
1407 Some((self.kind, line))
1411 /// Iterator over functional and commented parts of a string. Any part of a string is either
1412 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
1413 /// comments is functional code. Line comments contain their ending newlines.
1414 struct UngroupedCommentCodeSlices<'a> {
1416 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
1419 impl<'a> UngroupedCommentCodeSlices<'a> {
1420 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
1421 UngroupedCommentCodeSlices {
1423 iter: CharClasses::new(code.char_indices()).peekable(),
1428 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
1429 type Item = (CodeCharKind, usize, &'a str);
1431 fn next(&mut self) -> Option<Self::Item> {
1432 let (kind, (start_idx, _)) = self.iter.next()?;
1434 FullCodeCharKind::Normal | FullCodeCharKind::InString => {
1435 // Consume all the Normal code
1436 while let Some(&(char_kind, _)) = self.iter.peek() {
1437 if char_kind.is_comment() {
1440 let _ = self.iter.next();
1443 FullCodeCharKind::StartComment => {
1444 // Consume the whole comment
1446 match self.iter.next() {
1447 Some((kind, ..)) if kind.inside_comment() => continue,
1454 let slice = match self.iter.peek() {
1455 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
1456 None => &self.slice[start_idx..],
1459 if kind.is_comment() {
1460 CodeCharKind::Comment
1462 CodeCharKind::Normal
1470 /// Iterator over an alternating sequence of functional and commented parts of
1471 /// a string. The first item is always a, possibly zero length, subslice of
1472 /// functional text. Line style comments contain their ending newlines.
1473 pub(crate) struct CommentCodeSlices<'a> {
1475 last_slice_kind: CodeCharKind,
1476 last_slice_end: usize,
1479 impl<'a> CommentCodeSlices<'a> {
1480 pub(crate) fn new(slice: &'a str) -> CommentCodeSlices<'a> {
1483 last_slice_kind: CodeCharKind::Comment,
1489 impl<'a> Iterator for CommentCodeSlices<'a> {
1490 type Item = (CodeCharKind, usize, &'a str);
1492 fn next(&mut self) -> Option<Self::Item> {
1493 if self.last_slice_end == self.slice.len() {
1497 let mut sub_slice_end = self.last_slice_end;
1498 let mut first_whitespace = None;
1499 let subslice = &self.slice[self.last_slice_end..];
1500 let mut iter = CharClasses::new(subslice.char_indices());
1502 for (kind, (i, c)) in &mut iter {
1503 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal
1504 && &subslice[..2] == "//"
1505 && [' ', '\t'].contains(&c);
1507 if is_comment_connector && first_whitespace.is_none() {
1508 first_whitespace = Some(i);
1511 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
1512 let last_index = match first_whitespace {
1516 sub_slice_end = self.last_slice_end + last_index;
1520 if !is_comment_connector {
1521 first_whitespace = None;
1525 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
1526 // This was the last subslice.
1527 sub_slice_end = match first_whitespace {
1528 Some(i) => self.last_slice_end + i,
1529 None => self.slice.len(),
1533 let kind = match self.last_slice_kind {
1534 CodeCharKind::Comment => CodeCharKind::Normal,
1535 CodeCharKind::Normal => CodeCharKind::Comment,
1539 self.last_slice_end,
1540 &self.slice[self.last_slice_end..sub_slice_end],
1542 self.last_slice_end = sub_slice_end;
1543 self.last_slice_kind = kind;
1549 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
1550 /// (if it fits in the width/offset, else return `None`), else return `new`
1551 pub(crate) fn recover_comment_removed(
1554 context: &RewriteContext<'_>,
1555 ) -> Option<String> {
1556 let snippet = context.snippet(span);
1557 if snippet != new && changed_comment_content(snippet, &new) {
1558 // We missed some comments. Warn and keep the original text.
1559 if context.config.error_on_unformatted() {
1560 context.report.append(
1561 context.parse_sess.span_to_filename(span),
1562 vec![FormattingError::from_span(
1564 &context.parse_sess,
1565 ErrorKind::LostComment,
1569 Some(snippet.to_owned())
1575 pub(crate) fn filter_normal_code(code: &str) -> String {
1576 let mut buffer = String::with_capacity(code.len());
1577 LineClasses::new(code).for_each(|(kind, line)| match kind {
1578 FullCodeCharKind::Normal
1579 | FullCodeCharKind::StartString
1580 | FullCodeCharKind::InString
1581 | FullCodeCharKind::EndString => {
1582 buffer.push_str(&line);
1587 if !code.ends_with('\n') && buffer.ends_with('\n') {
1593 /// Returns `true` if the two strings of code have the same payload of comments.
1594 /// The payload of comments is everything in the string except:
1595 /// - actual code (not comments),
1596 /// - comment start/end marks,
1598 /// - '*' at the beginning of lines in block comments.
1599 fn changed_comment_content(orig: &str, new: &str) -> bool {
1600 // Cannot write this as a fn since we cannot return types containing closures.
1601 let code_comment_content = |code| {
1602 let slices = UngroupedCommentCodeSlices::new(code);
1604 .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
1605 .flat_map(|(_, _, s)| CommentReducer::new(s))
1607 let res = code_comment_content(orig).ne(code_comment_content(new));
1609 "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
1613 code_comment_content(orig).collect::<String>(),
1614 code_comment_content(new).collect::<String>()
1619 /// Iterator over the 'payload' characters of a comment.
1620 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
1621 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
1623 struct CommentReducer<'a> {
1625 at_start_line: bool,
1626 iter: std::str::Chars<'a>,
1629 impl<'a> CommentReducer<'a> {
1630 fn new(comment: &'a str) -> CommentReducer<'a> {
1631 let is_block = comment.starts_with("/*");
1632 let comment = remove_comment_header(comment);
1635 // There are no supplementary '*' on the first line.
1636 at_start_line: false,
1637 iter: comment.chars(),
1642 impl<'a> Iterator for CommentReducer<'a> {
1645 fn next(&mut self) -> Option<Self::Item> {
1647 let mut c = self.iter.next()?;
1648 if self.is_block && self.at_start_line {
1649 while c.is_whitespace() {
1650 c = self.iter.next()?;
1652 // Ignore leading '*'.
1654 c = self.iter.next()?;
1656 } else if c == '\n' {
1657 self.at_start_line = true;
1659 if !c.is_whitespace() {
1666 fn remove_comment_header(comment: &str) -> &str {
1667 if comment.starts_with("///") || comment.starts_with("//!") {
1669 } else if comment.starts_with("//") {
1671 } else if (comment.starts_with("/**") && !comment.starts_with("/**/"))
1672 || comment.starts_with("/*!")
1674 &comment[3..comment.len() - 2]
1677 comment.starts_with("/*"),
1678 format!("string '{}' is not a comment", comment)
1680 &comment[2..comment.len() - 2]
1687 use crate::shape::{Indent, Shape};
1691 let mut iter = CharClasses::new("//\n\n".chars());
1693 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
1694 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
1695 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
1696 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
1697 assert_eq!(None, iter.next());
1701 fn comment_code_slices() {
1702 let input = "code(); /* test */ 1 + 1";
1703 let mut iter = CommentCodeSlices::new(input);
1705 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
1707 (CodeCharKind::Comment, 8, "/* test */"),
1708 iter.next().unwrap()
1710 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
1711 assert_eq!(None, iter.next());
1715 fn comment_code_slices_two() {
1716 let input = "// comment\n test();";
1717 let mut iter = CommentCodeSlices::new(input);
1719 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
1721 (CodeCharKind::Comment, 0, "// comment\n"),
1722 iter.next().unwrap()
1725 (CodeCharKind::Normal, 11, " test();"),
1726 iter.next().unwrap()
1728 assert_eq!(None, iter.next());
1732 fn comment_code_slices_three() {
1733 let input = "1 // comment\n // comment2\n\n";
1734 let mut iter = CommentCodeSlices::new(input);
1736 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
1738 (CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
1739 iter.next().unwrap()
1741 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
1742 assert_eq!(None, iter.next());
1747 fn format_doc_comments() {
1748 let mut wrap_normalize_config: crate::config::Config = Default::default();
1749 wrap_normalize_config.set().wrap_comments(true);
1750 wrap_normalize_config.set().normalize_comments(true);
1752 let mut wrap_config: crate::config::Config = Default::default();
1753 wrap_config.set().wrap_comments(true);
1755 let comment = rewrite_comment(" //test",
1757 Shape::legacy(100, Indent::new(0, 100)),
1758 &wrap_normalize_config).unwrap();
1759 assert_eq!("/* test */", comment);
1761 let comment = rewrite_comment("// comment on a",
1763 Shape::legacy(10, Indent::empty()),
1764 &wrap_normalize_config).unwrap();
1765 assert_eq!("// comment\n// on a", comment);
1767 let comment = rewrite_comment("// A multi line comment\n // between args.",
1769 Shape::legacy(60, Indent::new(0, 12)),
1770 &wrap_normalize_config).unwrap();
1771 assert_eq!("// A multi line comment\n // between args.", comment);
1773 let input = "// comment";
1776 let comment = rewrite_comment(input,
1778 Shape::legacy(9, Indent::new(0, 69)),
1779 &wrap_normalize_config).unwrap();
1780 assert_eq!(expected, comment);
1782 let comment = rewrite_comment("/* trimmed */",
1784 Shape::legacy(100, Indent::new(0, 100)),
1785 &wrap_normalize_config).unwrap();
1786 assert_eq!("/* trimmed */", comment);
1788 // Check that different comment style are properly recognised.
1789 let comment = rewrite_comment(r#"/// test1
1795 Shape::legacy(100, Indent::new(0, 0)),
1796 &wrap_normalize_config).unwrap();
1797 assert_eq!("/// test1\n/// test2\n// test3", comment);
1799 // Check that the blank line marks the end of a commented paragraph.
1800 let comment = rewrite_comment(r#"// test1
1804 Shape::legacy(100, Indent::new(0, 0)),
1805 &wrap_normalize_config).unwrap();
1806 assert_eq!("// test1\n\n// test2", comment);
1808 // Check that the blank line marks the end of a custom-commented paragraph.
1809 let comment = rewrite_comment(r#"//@ test1
1813 Shape::legacy(100, Indent::new(0, 0)),
1814 &wrap_normalize_config).unwrap();
1815 assert_eq!("//@ test1\n\n//@ test2", comment);
1817 // Check that bare lines are just indented but otherwise left unchanged.
1818 let comment = rewrite_comment(r#"// test1
1825 Shape::legacy(100, Indent::new(0, 0)),
1826 &wrap_config).unwrap();
1827 assert_eq!("// test1\n/*\n a bare line!\n\n another bare line!\n*/", comment);
1830 // This is probably intended to be a non-test fn, but it is not used.
1831 // We should keep this around unless it helps us test stuff to remove it.
1832 fn uncommented(text: &str) -> String {
1833 CharClasses::new(text.chars())
1834 .filter_map(|(s, c)| match s {
1835 FullCodeCharKind::Normal | FullCodeCharKind::InString => Some(c),
1842 fn test_uncommented() {
1843 assert_eq!(&uncommented("abc/*...*/"), "abc");
1845 &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
1848 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
1852 fn test_contains_comment() {
1853 assert_eq!(contains_comment("abc"), false);
1854 assert_eq!(contains_comment("abc // qsdf"), true);
1855 assert_eq!(contains_comment("abc /* kqsdf"), true);
1856 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
1860 fn test_find_uncommented() {
1861 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
1862 assert_eq!(expected, haystack.find_uncommented(needle));
1865 check("/*/ */test", "test", Some(6));
1866 check("//test\ntest", "test", Some(7));
1867 check("/* comment only */", "whatever", None);
1869 "/* comment */ some text /* more commentary */ result",
1873 check("sup // sup", "p", Some(2));
1874 check("sup", "x", None);
1875 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
1876 check("/*sup yo? \n sup*/ sup", "p", Some(20));
1877 check("hel/*lohello*/lo", "hello", None);
1878 check("acb", "ab", None);
1879 check(",/*A*/ ", ",", Some(0));
1880 check("abc", "abc", Some(0));
1881 check("/* abc */", "abc", None);
1882 check("/**/abc/* */", "abc", Some(4));
1883 check("\"/* abc */\"", "abc", Some(4));
1884 check("\"/* abc", "abc", Some(4));
1888 fn test_filter_normal_code() {
1891 println!("hello, world");
1894 assert_eq!(s, filter_normal_code(s));
1895 let s_with_comment = r#"
1898 println!("hello, world");
1901 assert_eq!(s, filter_normal_code(s_with_comment));