1 // Formatting and tools for comments.
3 use std::{self, borrow::Cow, iter};
5 use itertools::{multipeek, MultiPeek};
6 use syntax::source_map::Span;
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 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 if s.trim_start().starts_with("# ") {
827 Cow::from(format!("{}{}", RUSTFMT_CUSTOM_COMMENT_PREFIX, s))
833 fn trim_custom_comment_prefix(s: &str) -> String {
836 let left_trimmed = line.trim_start();
837 if left_trimmed.starts_with(RUSTFMT_CUSTOM_COMMENT_PREFIX) {
838 left_trimmed.trim_start_matches(RUSTFMT_CUSTOM_COMMENT_PREFIX)
847 /// Returns `true` if the given string MAY include URLs or alike.
848 fn has_url(s: &str) -> bool {
849 // This function may return false positive, but should get its job done in most cases.
850 s.contains("https://") || s.contains("http://") || s.contains("ftp://") || s.contains("file://")
853 /// Given the span, rewrite the missing comment inside it if available.
854 /// Note that the given span must only include comments (or leading/trailing whitespaces).
855 pub(crate) fn rewrite_missing_comment(
858 context: &RewriteContext<'_>,
859 ) -> Option<String> {
860 let missing_snippet = context.snippet(span);
861 let trimmed_snippet = missing_snippet.trim();
862 if !trimmed_snippet.is_empty() {
863 rewrite_comment(trimmed_snippet, false, shape, context.config)
869 /// Recover the missing comments in the specified span, if available.
870 /// The layout of the comments will be preserved as long as it does not break the code
871 /// and its total width does not exceed the max width.
872 pub(crate) fn recover_missing_comment_in_span(
875 context: &RewriteContext<'_>,
877 ) -> Option<String> {
878 let missing_comment = rewrite_missing_comment(span, shape, context)?;
879 if missing_comment.is_empty() {
882 let missing_snippet = context.snippet(span);
883 let pos = missing_snippet.find('/').unwrap_or(0);
885 let total_width = missing_comment.len() + used_width + 1;
886 let force_new_line_before_comment =
887 missing_snippet[..pos].contains('\n') || total_width > context.config.max_width();
888 let sep = if force_new_line_before_comment {
889 shape.indent.to_string_with_newline(context.config)
893 Some(format!("{}{}", sep, missing_comment))
897 /// Trim trailing whitespaces unless they consist of two or more whitespaces.
898 fn trim_end_unless_two_whitespaces(s: &str, is_doc_comment: bool) -> &str {
899 if is_doc_comment && s.ends_with(" ") {
906 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
907 fn light_rewrite_comment(
911 is_doc_comment: bool,
913 let lines: Vec<&str> = orig
916 // This is basically just l.trim(), but in the case that a line starts
917 // with `*` we want to leave one space before it, so it aligns with the
919 let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
920 let left_trimmed = if let Some(fnw) = first_non_whitespace {
921 if l.as_bytes()[fnw] == b'*' && fnw > 0 {
929 // Preserve markdown's double-space line break syntax in doc comment.
930 trim_end_unless_two_whitespaces(left_trimmed, is_doc_comment)
933 lines.join(&format!("\n{}", offset.to_string(config)))
936 /// Trims comment characters and possibly a single space from the left of a string.
937 /// Does not trim all whitespace. If a single space is trimmed from the left of the string,
938 /// this function returns true.
939 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle<'_>) -> (&'a str, bool) {
940 if line.starts_with("//! ")
941 || line.starts_with("/// ")
942 || line.starts_with("/*! ")
943 || line.starts_with("/** ")
946 } else if let CommentStyle::Custom(opener) = *style {
947 if line.starts_with(opener) {
948 (&line[opener.len()..], true)
950 (&line[opener.trim_end().len()..], false)
952 } else if line.starts_with("/* ")
953 || line.starts_with("// ")
954 || line.starts_with("//!")
955 || line.starts_with("///")
956 || line.starts_with("** ")
957 || line.starts_with("/*!")
958 || (line.starts_with("/**") && !line.starts_with("/**/"))
960 (&line[3..], line.chars().nth(2).unwrap() == ' ')
961 } else if line.starts_with("/*")
962 || line.starts_with("* ")
963 || line.starts_with("//")
964 || line.starts_with("**")
966 (&line[2..], line.chars().nth(1).unwrap() == ' ')
967 } else if line.starts_with('*') {
970 (line, line.starts_with(' '))
974 pub(crate) trait FindUncommented {
975 fn find_uncommented(&self, pat: &str) -> Option<usize>;
978 impl FindUncommented for str {
979 fn find_uncommented(&self, pat: &str) -> Option<usize> {
980 let mut needle_iter = pat.chars();
981 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
982 match needle_iter.next() {
984 return Some(i - pat.len());
986 Some(c) => match kind {
987 FullCodeCharKind::Normal | FullCodeCharKind::InString if b == c => {}
989 needle_iter = pat.chars();
995 // Handle case where the pattern is a suffix of the search string
996 match needle_iter.next() {
998 None => Some(self.len() - pat.len()),
1003 // Returns the first byte position after the first comment. The given string
1004 // is expected to be prefixed by a comment, including delimiters.
1005 // Good: `/* /* inner */ outer */ code();`
1006 // Bad: `code(); // hello\n world!`
1007 pub(crate) fn find_comment_end(s: &str) -> Option<usize> {
1008 let mut iter = CharClasses::new(s.char_indices());
1009 for (kind, (i, _c)) in &mut iter {
1010 if kind == FullCodeCharKind::Normal || kind == FullCodeCharKind::InString {
1015 // Handle case where the comment ends at the end of `s`.
1016 if iter.status == CharClassesStatus::Normal {
1023 /// Returns `true` if text contains any comment.
1024 pub(crate) fn contains_comment(text: &str) -> bool {
1025 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
1028 pub(crate) struct CharClasses<T>
1034 status: CharClassesStatus,
1037 pub(crate) trait RichChar {
1038 fn get_char(&self) -> char;
1041 impl RichChar for char {
1042 fn get_char(&self) -> char {
1047 impl RichChar for (usize, char) {
1048 fn get_char(&self) -> char {
1053 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
1054 enum CharClassesStatus {
1056 /// Character is within a string
1059 /// Character is within a raw string
1061 RawStringPrefix(u32),
1062 RawStringSuffix(u32),
1065 /// Character inside a block comment, with the integer indicating the nesting deepness of the
1068 /// Character inside a block-commented string, with the integer indicating the nesting deepness
1070 StringInBlockComment(u32),
1071 /// Status when the '/' has been consumed, but not yet the '*', deepness is
1072 /// the new deepness (after the comment opening).
1073 BlockCommentOpening(u32),
1074 /// Status when the '*' has been consumed, but not yet the '/', deepness is
1075 /// the new deepness (after the comment closing).
1076 BlockCommentClosing(u32),
1077 /// Character is within a line comment
1081 /// Distinguish between functional part of code and comments
1082 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
1083 pub(crate) enum CodeCharKind {
1088 /// Distinguish between functional part of code and comments,
1089 /// describing opening and closing of comments for ease when chunking
1090 /// code from tagged characters
1091 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
1092 pub(crate) enum FullCodeCharKind {
1094 /// The first character of a comment, there is only one for a comment (always '/')
1096 /// Any character inside a comment including the second character of comment
1097 /// marks ("//", "/*")
1099 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
1101 /// Start of a mutlitine string inside a comment
1102 StartStringCommented,
1103 /// End of a mutlitine string inside a comment
1105 /// Inside a commented string
1107 /// Start of a mutlitine string
1109 /// End of a mutlitine string
1111 /// Inside a string.
1115 impl FullCodeCharKind {
1116 pub(crate) fn is_comment(self) -> bool {
1118 FullCodeCharKind::StartComment
1119 | FullCodeCharKind::InComment
1120 | FullCodeCharKind::EndComment
1121 | FullCodeCharKind::StartStringCommented
1122 | FullCodeCharKind::InStringCommented
1123 | FullCodeCharKind::EndStringCommented => true,
1128 /// Returns true if the character is inside a comment
1129 pub(crate) fn inside_comment(self) -> bool {
1131 FullCodeCharKind::InComment
1132 | FullCodeCharKind::StartStringCommented
1133 | FullCodeCharKind::InStringCommented
1134 | FullCodeCharKind::EndStringCommented => true,
1139 pub(crate) fn is_string(self) -> bool {
1140 self == FullCodeCharKind::InString || self == FullCodeCharKind::StartString
1143 /// Returns true if the character is within a commented string
1144 pub(crate) fn is_commented_string(self) -> bool {
1145 self == FullCodeCharKind::InStringCommented
1146 || self == FullCodeCharKind::StartStringCommented
1149 fn to_codecharkind(self) -> CodeCharKind {
1150 if self.is_comment() {
1151 CodeCharKind::Comment
1153 CodeCharKind::Normal
1158 impl<T> CharClasses<T>
1163 pub(crate) fn new(base: T) -> CharClasses<T> {
1165 base: multipeek(base),
1166 status: CharClassesStatus::Normal,
1171 fn is_raw_string_suffix<T>(iter: &mut MultiPeek<T>, count: u32) -> bool
1178 Some(c) if c.get_char() == '#' => continue,
1185 impl<T> Iterator for CharClasses<T>
1190 type Item = (FullCodeCharKind, T::Item);
1192 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
1193 let item = self.base.next()?;
1194 let chr = item.get_char();
1195 let mut char_kind = FullCodeCharKind::Normal;
1196 self.status = match self.status {
1197 CharClassesStatus::LitRawString(sharps) => {
1198 char_kind = FullCodeCharKind::InString;
1202 char_kind = FullCodeCharKind::Normal;
1203 CharClassesStatus::Normal
1204 } else if is_raw_string_suffix(&mut self.base, sharps) {
1205 CharClassesStatus::RawStringSuffix(sharps)
1207 CharClassesStatus::LitRawString(sharps)
1210 _ => CharClassesStatus::LitRawString(sharps),
1213 CharClassesStatus::RawStringPrefix(sharps) => {
1214 char_kind = FullCodeCharKind::InString;
1216 '#' => CharClassesStatus::RawStringPrefix(sharps + 1),
1217 '"' => CharClassesStatus::LitRawString(sharps),
1218 _ => CharClassesStatus::Normal, // Unreachable.
1221 CharClassesStatus::RawStringSuffix(sharps) => {
1225 CharClassesStatus::Normal
1227 char_kind = FullCodeCharKind::InString;
1228 CharClassesStatus::RawStringSuffix(sharps - 1)
1231 _ => CharClassesStatus::Normal, // Unreachable
1234 CharClassesStatus::LitString => {
1235 char_kind = FullCodeCharKind::InString;
1237 '"' => CharClassesStatus::Normal,
1238 '\\' => CharClassesStatus::LitStringEscape,
1239 _ => CharClassesStatus::LitString,
1242 CharClassesStatus::LitStringEscape => {
1243 char_kind = FullCodeCharKind::InString;
1244 CharClassesStatus::LitString
1246 CharClassesStatus::LitChar => match chr {
1247 '\\' => CharClassesStatus::LitCharEscape,
1248 '\'' => CharClassesStatus::Normal,
1249 _ => CharClassesStatus::LitChar,
1251 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
1252 CharClassesStatus::Normal => match chr {
1253 'r' => match self.base.peek().map(RichChar::get_char) {
1254 Some('#') | Some('"') => {
1255 char_kind = FullCodeCharKind::InString;
1256 CharClassesStatus::RawStringPrefix(0)
1258 _ => CharClassesStatus::Normal,
1261 char_kind = FullCodeCharKind::InString;
1262 CharClassesStatus::LitString
1265 // HACK: Work around mut borrow.
1266 match self.base.peek() {
1267 Some(next) if next.get_char() == '\\' => {
1268 self.status = CharClassesStatus::LitChar;
1269 return Some((char_kind, item));
1274 match self.base.peek() {
1275 Some(next) if next.get_char() == '\'' => CharClassesStatus::LitChar,
1276 _ => CharClassesStatus::Normal,
1279 '/' => match self.base.peek() {
1280 Some(next) if next.get_char() == '*' => {
1281 self.status = CharClassesStatus::BlockCommentOpening(1);
1282 return Some((FullCodeCharKind::StartComment, item));
1284 Some(next) if next.get_char() == '/' => {
1285 self.status = CharClassesStatus::LineComment;
1286 return Some((FullCodeCharKind::StartComment, item));
1288 _ => CharClassesStatus::Normal,
1290 _ => CharClassesStatus::Normal,
1292 CharClassesStatus::StringInBlockComment(deepness) => {
1293 char_kind = FullCodeCharKind::InStringCommented;
1295 CharClassesStatus::BlockComment(deepness)
1297 CharClassesStatus::StringInBlockComment(deepness)
1300 CharClassesStatus::BlockComment(deepness) => {
1301 assert_ne!(deepness, 0);
1302 char_kind = FullCodeCharKind::InComment;
1303 match self.base.peek() {
1304 Some(next) if next.get_char() == '/' && chr == '*' => {
1305 CharClassesStatus::BlockCommentClosing(deepness - 1)
1307 Some(next) if next.get_char() == '*' && chr == '/' => {
1308 CharClassesStatus::BlockCommentOpening(deepness + 1)
1310 _ if chr == '"' => CharClassesStatus::StringInBlockComment(deepness),
1314 CharClassesStatus::BlockCommentOpening(deepness) => {
1315 assert_eq!(chr, '*');
1316 self.status = CharClassesStatus::BlockComment(deepness);
1317 return Some((FullCodeCharKind::InComment, item));
1319 CharClassesStatus::BlockCommentClosing(deepness) => {
1320 assert_eq!(chr, '/');
1322 self.status = CharClassesStatus::Normal;
1323 return Some((FullCodeCharKind::EndComment, item));
1325 self.status = CharClassesStatus::BlockComment(deepness);
1326 return Some((FullCodeCharKind::InComment, item));
1329 CharClassesStatus::LineComment => match chr {
1331 self.status = CharClassesStatus::Normal;
1332 return Some((FullCodeCharKind::EndComment, item));
1335 self.status = CharClassesStatus::LineComment;
1336 return Some((FullCodeCharKind::InComment, item));
1340 Some((char_kind, item))
1344 /// An iterator over the lines of a string, paired with the char kind at the
1345 /// end of the line.
1346 pub(crate) struct LineClasses<'a> {
1347 base: iter::Peekable<CharClasses<std::str::Chars<'a>>>,
1348 kind: FullCodeCharKind,
1351 impl<'a> LineClasses<'a> {
1352 pub(crate) fn new(s: &'a str) -> Self {
1354 base: CharClasses::new(s.chars()).peekable(),
1355 kind: FullCodeCharKind::Normal,
1360 impl<'a> Iterator for LineClasses<'a> {
1361 type Item = (FullCodeCharKind, String);
1363 fn next(&mut self) -> Option<Self::Item> {
1366 let mut line = String::new();
1368 let start_kind = match self.base.peek() {
1369 Some((kind, _)) => *kind,
1370 None => unreachable!(),
1373 while let Some((kind, c)) = self.base.next() {
1374 // needed to set the kind of the ending character on the last line
1377 self.kind = match (start_kind, kind) {
1378 (FullCodeCharKind::Normal, FullCodeCharKind::InString) => {
1379 FullCodeCharKind::StartString
1381 (FullCodeCharKind::InString, FullCodeCharKind::Normal) => {
1382 FullCodeCharKind::EndString
1384 (FullCodeCharKind::InComment, FullCodeCharKind::InStringCommented) => {
1385 FullCodeCharKind::StartStringCommented
1387 (FullCodeCharKind::InStringCommented, FullCodeCharKind::InComment) => {
1388 FullCodeCharKind::EndStringCommented
1397 // Workaround for CRLF newline.
1398 if line.ends_with('\r') {
1402 Some((self.kind, line))
1406 /// Iterator over functional and commented parts of a string. Any part of a string is either
1407 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
1408 /// comments is functional code. Line comments contain their ending newlines.
1409 struct UngroupedCommentCodeSlices<'a> {
1411 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
1414 impl<'a> UngroupedCommentCodeSlices<'a> {
1415 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
1416 UngroupedCommentCodeSlices {
1418 iter: CharClasses::new(code.char_indices()).peekable(),
1423 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
1424 type Item = (CodeCharKind, usize, &'a str);
1426 fn next(&mut self) -> Option<Self::Item> {
1427 let (kind, (start_idx, _)) = self.iter.next()?;
1429 FullCodeCharKind::Normal | FullCodeCharKind::InString => {
1430 // Consume all the Normal code
1431 while let Some(&(char_kind, _)) = self.iter.peek() {
1432 if char_kind.is_comment() {
1435 let _ = self.iter.next();
1438 FullCodeCharKind::StartComment => {
1439 // Consume the whole comment
1441 match self.iter.next() {
1442 Some((kind, ..)) if kind.inside_comment() => continue,
1449 let slice = match self.iter.peek() {
1450 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
1451 None => &self.slice[start_idx..],
1454 if kind.is_comment() {
1455 CodeCharKind::Comment
1457 CodeCharKind::Normal
1465 /// Iterator over an alternating sequence of functional and commented parts of
1466 /// a string. The first item is always a, possibly zero length, subslice of
1467 /// functional text. Line style comments contain their ending newlines.
1468 pub(crate) struct CommentCodeSlices<'a> {
1470 last_slice_kind: CodeCharKind,
1471 last_slice_end: usize,
1474 impl<'a> CommentCodeSlices<'a> {
1475 pub(crate) fn new(slice: &'a str) -> CommentCodeSlices<'a> {
1478 last_slice_kind: CodeCharKind::Comment,
1484 impl<'a> Iterator for CommentCodeSlices<'a> {
1485 type Item = (CodeCharKind, usize, &'a str);
1487 fn next(&mut self) -> Option<Self::Item> {
1488 if self.last_slice_end == self.slice.len() {
1492 let mut sub_slice_end = self.last_slice_end;
1493 let mut first_whitespace = None;
1494 let subslice = &self.slice[self.last_slice_end..];
1495 let mut iter = CharClasses::new(subslice.char_indices());
1497 for (kind, (i, c)) in &mut iter {
1498 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal
1499 && &subslice[..2] == "//"
1500 && [' ', '\t'].contains(&c);
1502 if is_comment_connector && first_whitespace.is_none() {
1503 first_whitespace = Some(i);
1506 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
1507 let last_index = match first_whitespace {
1511 sub_slice_end = self.last_slice_end + last_index;
1515 if !is_comment_connector {
1516 first_whitespace = None;
1520 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
1521 // This was the last subslice.
1522 sub_slice_end = match first_whitespace {
1523 Some(i) => self.last_slice_end + i,
1524 None => self.slice.len(),
1528 let kind = match self.last_slice_kind {
1529 CodeCharKind::Comment => CodeCharKind::Normal,
1530 CodeCharKind::Normal => CodeCharKind::Comment,
1534 self.last_slice_end,
1535 &self.slice[self.last_slice_end..sub_slice_end],
1537 self.last_slice_end = sub_slice_end;
1538 self.last_slice_kind = kind;
1544 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
1545 /// (if it fits in the width/offset, else return `None`), else return `new`
1546 pub(crate) fn recover_comment_removed(
1549 context: &RewriteContext<'_>,
1550 ) -> Option<String> {
1551 let snippet = context.snippet(span);
1552 if snippet != new && changed_comment_content(snippet, &new) {
1553 // We missed some comments. Warn and keep the original text.
1554 if context.config.error_on_unformatted() {
1555 context.report.append(
1556 context.source_map.span_to_filename(span).into(),
1557 vec![FormattingError::from_span(
1559 &context.source_map,
1560 ErrorKind::LostComment,
1564 Some(snippet.to_owned())
1570 pub(crate) fn filter_normal_code(code: &str) -> String {
1571 let mut buffer = String::with_capacity(code.len());
1572 LineClasses::new(code).for_each(|(kind, line)| match kind {
1573 FullCodeCharKind::Normal
1574 | FullCodeCharKind::StartString
1575 | FullCodeCharKind::InString
1576 | FullCodeCharKind::EndString => {
1577 buffer.push_str(&line);
1582 if !code.ends_with('\n') && buffer.ends_with('\n') {
1588 /// Returns `true` if the two strings of code have the same payload of comments.
1589 /// The payload of comments is everything in the string except:
1590 /// - actual code (not comments),
1591 /// - comment start/end marks,
1593 /// - '*' at the beginning of lines in block comments.
1594 fn changed_comment_content(orig: &str, new: &str) -> bool {
1595 // Cannot write this as a fn since we cannot return types containing closures.
1596 let code_comment_content = |code| {
1597 let slices = UngroupedCommentCodeSlices::new(code);
1599 .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
1600 .flat_map(|(_, _, s)| CommentReducer::new(s))
1602 let res = code_comment_content(orig).ne(code_comment_content(new));
1604 "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
1608 code_comment_content(orig).collect::<String>(),
1609 code_comment_content(new).collect::<String>()
1614 /// Iterator over the 'payload' characters of a comment.
1615 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
1616 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
1618 struct CommentReducer<'a> {
1620 at_start_line: bool,
1621 iter: std::str::Chars<'a>,
1624 impl<'a> CommentReducer<'a> {
1625 fn new(comment: &'a str) -> CommentReducer<'a> {
1626 let is_block = comment.starts_with("/*");
1627 let comment = remove_comment_header(comment);
1630 // There are no supplementary '*' on the first line.
1631 at_start_line: false,
1632 iter: comment.chars(),
1637 impl<'a> Iterator for CommentReducer<'a> {
1640 fn next(&mut self) -> Option<Self::Item> {
1642 let mut c = self.iter.next()?;
1643 if self.is_block && self.at_start_line {
1644 while c.is_whitespace() {
1645 c = self.iter.next()?;
1647 // Ignore leading '*'.
1649 c = self.iter.next()?;
1651 } else if c == '\n' {
1652 self.at_start_line = true;
1654 if !c.is_whitespace() {
1661 fn remove_comment_header(comment: &str) -> &str {
1662 if comment.starts_with("///") || comment.starts_with("//!") {
1664 } else if comment.starts_with("//") {
1666 } else if (comment.starts_with("/**") && !comment.starts_with("/**/"))
1667 || comment.starts_with("/*!")
1669 &comment[3..comment.len() - 2]
1672 comment.starts_with("/*"),
1673 format!("string '{}' is not a comment", comment)
1675 &comment[2..comment.len() - 2]
1682 use crate::shape::{Indent, Shape};
1686 let mut iter = CharClasses::new("//\n\n".chars());
1688 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
1689 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
1690 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
1691 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
1692 assert_eq!(None, iter.next());
1696 fn comment_code_slices() {
1697 let input = "code(); /* test */ 1 + 1";
1698 let mut iter = CommentCodeSlices::new(input);
1700 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
1702 (CodeCharKind::Comment, 8, "/* test */"),
1703 iter.next().unwrap()
1705 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
1706 assert_eq!(None, iter.next());
1710 fn comment_code_slices_two() {
1711 let input = "// comment\n test();";
1712 let mut iter = CommentCodeSlices::new(input);
1714 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
1716 (CodeCharKind::Comment, 0, "// comment\n"),
1717 iter.next().unwrap()
1720 (CodeCharKind::Normal, 11, " test();"),
1721 iter.next().unwrap()
1723 assert_eq!(None, iter.next());
1727 fn comment_code_slices_three() {
1728 let input = "1 // comment\n // comment2\n\n";
1729 let mut iter = CommentCodeSlices::new(input);
1731 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
1733 (CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
1734 iter.next().unwrap()
1736 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
1737 assert_eq!(None, iter.next());
1742 fn format_doc_comments() {
1743 let mut wrap_normalize_config: crate::config::Config = Default::default();
1744 wrap_normalize_config.set().wrap_comments(true);
1745 wrap_normalize_config.set().normalize_comments(true);
1747 let mut wrap_config: crate::config::Config = Default::default();
1748 wrap_config.set().wrap_comments(true);
1750 let comment = rewrite_comment(" //test",
1752 Shape::legacy(100, Indent::new(0, 100)),
1753 &wrap_normalize_config).unwrap();
1754 assert_eq!("/* test */", comment);
1756 let comment = rewrite_comment("// comment on a",
1758 Shape::legacy(10, Indent::empty()),
1759 &wrap_normalize_config).unwrap();
1760 assert_eq!("// comment\n// on a", comment);
1762 let comment = rewrite_comment("// A multi line comment\n // between args.",
1764 Shape::legacy(60, Indent::new(0, 12)),
1765 &wrap_normalize_config).unwrap();
1766 assert_eq!("// A multi line comment\n // between args.", comment);
1768 let input = "// comment";
1771 let comment = rewrite_comment(input,
1773 Shape::legacy(9, Indent::new(0, 69)),
1774 &wrap_normalize_config).unwrap();
1775 assert_eq!(expected, comment);
1777 let comment = rewrite_comment("/* trimmed */",
1779 Shape::legacy(100, Indent::new(0, 100)),
1780 &wrap_normalize_config).unwrap();
1781 assert_eq!("/* trimmed */", comment);
1783 // Check that different comment style are properly recognised.
1784 let comment = rewrite_comment(r#"/// test1
1790 Shape::legacy(100, Indent::new(0, 0)),
1791 &wrap_normalize_config).unwrap();
1792 assert_eq!("/// test1\n/// test2\n// test3", comment);
1794 // Check that the blank line marks the end of a commented paragraph.
1795 let comment = rewrite_comment(r#"// test1
1799 Shape::legacy(100, Indent::new(0, 0)),
1800 &wrap_normalize_config).unwrap();
1801 assert_eq!("// test1\n\n// test2", comment);
1803 // Check that the blank line marks the end of a custom-commented paragraph.
1804 let comment = rewrite_comment(r#"//@ test1
1808 Shape::legacy(100, Indent::new(0, 0)),
1809 &wrap_normalize_config).unwrap();
1810 assert_eq!("//@ test1\n\n//@ test2", comment);
1812 // Check that bare lines are just indented but otherwise left unchanged.
1813 let comment = rewrite_comment(r#"// test1
1820 Shape::legacy(100, Indent::new(0, 0)),
1821 &wrap_config).unwrap();
1822 assert_eq!("// test1\n/*\n a bare line!\n\n another bare line!\n*/", comment);
1825 // This is probably intended to be a non-test fn, but it is not used.
1826 // We should keep this around unless it helps us test stuff to remove it.
1827 fn uncommented(text: &str) -> String {
1828 CharClasses::new(text.chars())
1829 .filter_map(|(s, c)| match s {
1830 FullCodeCharKind::Normal | FullCodeCharKind::InString => Some(c),
1837 fn test_uncommented() {
1838 assert_eq!(&uncommented("abc/*...*/"), "abc");
1840 &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
1843 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
1847 fn test_contains_comment() {
1848 assert_eq!(contains_comment("abc"), false);
1849 assert_eq!(contains_comment("abc // qsdf"), true);
1850 assert_eq!(contains_comment("abc /* kqsdf"), true);
1851 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
1855 fn test_find_uncommented() {
1856 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
1857 assert_eq!(expected, haystack.find_uncommented(needle));
1860 check("/*/ */test", "test", Some(6));
1861 check("//test\ntest", "test", Some(7));
1862 check("/* comment only */", "whatever", None);
1864 "/* comment */ some text /* more commentary */ result",
1868 check("sup // sup", "p", Some(2));
1869 check("sup", "x", None);
1870 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
1871 check("/*sup yo? \n sup*/ sup", "p", Some(20));
1872 check("hel/*lohello*/lo", "hello", None);
1873 check("acb", "ab", None);
1874 check(",/*A*/ ", ",", Some(0));
1875 check("abc", "abc", Some(0));
1876 check("/* abc */", "abc", None);
1877 check("/**/abc/* */", "abc", Some(4));
1878 check("\"/* abc */\"", "abc", Some(4));
1879 check("\"/* abc", "abc", Some(4));
1883 fn test_filter_normal_code() {
1886 println!("hello, world");
1889 assert_eq!(s, filter_normal_code(s));
1890 let s_with_comment = r#"
1893 println!("hello, world");
1896 assert_eq!(s, filter_normal_code(s_with_comment));