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 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 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 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 fn is_doc_comment(&self) -> bool {
71 CommentStyle::TripleSlash | CommentStyle::Doc => true,
76 pub 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 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 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 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 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 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 fn rewrite_doc_comment(orig: &str, shape: Shape, config: &Config) -> Option<String> {
243 identify_comment(orig, false, shape, config, true)
246 pub 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_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 match crate::format_code_block(&self.code_block_buffer, &config) {
660 Some(ref s) => trim_custom_comment_prefix(&s.snippet),
661 None => trim_custom_comment_prefix(&self.code_block_buffer),
665 if !code_block.is_empty() {
666 self.result.push_str(&self.comment_line_separator);
668 .push_str(&Self::join_block(&code_block, &self.comment_line_separator));
670 self.code_block_buffer.clear();
671 self.result.push_str(&self.comment_line_separator);
672 self.result.push_str(line);
673 self.code_block_attr = None;
675 self.code_block_buffer
676 .push_str(&hide_sharp_behind_comment(line));
677 self.code_block_buffer.push('\n');
682 self.code_block_attr = None;
683 self.item_block = None;
684 if line.starts_with("```") {
685 self.code_block_attr = Some(CodeBlockAttribute::new(&line[3..]))
686 } else if self.fmt.config.wrap_comments() && ItemizedBlock::is_itemized_line(&line) {
687 let ib = ItemizedBlock::new(&line);
688 self.item_block = Some(ib);
692 if self.result == self.opener {
693 let force_leading_whitespace = &self.opener == "/* " && count_newlines(orig) == 0;
694 if !has_leading_whitespace && !force_leading_whitespace && self.result.ends_with(' ') {
700 } else if self.is_prev_line_multi_line && !line.is_empty() {
701 self.result.push(' ')
702 } else if is_last && line.is_empty() {
703 // trailing blank lines are unwanted
704 if !self.closer.is_empty() {
705 self.result.push_str(&self.indent_str);
709 self.result.push_str(&self.comment_line_separator);
710 if !has_leading_whitespace && self.result.ends_with(' ') {
715 if self.fmt.config.wrap_comments()
716 && unicode_str_width(line) > self.fmt.shape.width
719 match rewrite_string(line, &self.fmt, self.max_width) {
721 self.is_prev_line_multi_line = s.contains('\n');
722 self.result.push_str(s);
724 None if self.is_prev_line_multi_line => {
725 // We failed to put the current `line` next to the previous `line`.
726 // Remove the trailing space, then start rewrite on the next line.
728 self.result.push_str(&self.comment_line_separator);
729 self.fmt.shape = Shape::legacy(self.max_width, self.fmt_indent);
730 match rewrite_string(line, &self.fmt, self.max_width) {
732 self.is_prev_line_multi_line = s.contains('\n');
733 self.result.push_str(s);
736 self.is_prev_line_multi_line = false;
737 self.result.push_str(line);
742 self.is_prev_line_multi_line = false;
743 self.result.push_str(line);
747 self.fmt.shape = if self.is_prev_line_multi_line {
749 let offset = 1 + last_line_width(&self.result) - self.line_start.len();
751 width: self.max_width.saturating_sub(offset),
752 indent: self.fmt_indent,
753 offset: self.fmt.shape.offset + offset,
756 Shape::legacy(self.max_width, self.fmt_indent)
759 if line.is_empty() && self.result.ends_with(' ') && !is_last {
760 // Remove space if this is an empty comment or a doc comment.
763 self.result.push_str(line);
764 self.fmt.shape = Shape::legacy(self.max_width, self.fmt_indent);
765 self.is_prev_line_multi_line = false;
772 fn rewrite_comment_inner(
775 style: CommentStyle<'_>,
778 is_doc_comment: bool,
779 ) -> Option<String> {
780 let mut rewriter = CommentRewrite::new(orig, block_style, shape, config);
782 let line_breaks = count_newlines(orig.trim_end());
786 .map(|(i, mut line)| {
787 line = trim_end_unless_two_whitespaces(line.trim_start(), is_doc_comment);
789 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
790 line = line[..(line.len() - 2)].trim_end();
795 .map(|s| left_trim_comment_line(s, &style))
796 .map(|(line, has_leading_whitespace)| {
797 if orig.starts_with("/*") && line_breaks == 0 {
800 has_leading_whitespace || config.normalize_comments(),
803 (line, has_leading_whitespace || config.normalize_comments())
807 for (i, (line, has_leading_whitespace)) in lines.enumerate() {
808 if rewriter.handle_line(orig, i, line, has_leading_whitespace) {
813 Some(rewriter.finish())
816 const RUSTFMT_CUSTOM_COMMENT_PREFIX: &str = "//#### ";
818 fn hide_sharp_behind_comment(s: &str) -> Cow<'_, str> {
819 if s.trim_start().starts_with("# ") {
820 Cow::from(format!("{}{}", RUSTFMT_CUSTOM_COMMENT_PREFIX, s))
826 fn trim_custom_comment_prefix(s: &str) -> String {
829 let left_trimmed = line.trim_start();
830 if left_trimmed.starts_with(RUSTFMT_CUSTOM_COMMENT_PREFIX) {
831 left_trimmed.trim_start_matches(RUSTFMT_CUSTOM_COMMENT_PREFIX)
840 /// Returns `true` if the given string MAY include URLs or alike.
841 fn has_url(s: &str) -> bool {
842 // This function may return false positive, but should get its job done in most cases.
843 s.contains("https://") || s.contains("http://") || s.contains("ftp://") || s.contains("file://")
846 /// Given the span, rewrite the missing comment inside it if available.
847 /// Note that the given span must only include comments (or leading/trailing whitespaces).
848 pub fn rewrite_missing_comment(
851 context: &RewriteContext<'_>,
852 ) -> Option<String> {
853 let missing_snippet = context.snippet(span);
854 let trimmed_snippet = missing_snippet.trim();
855 if !trimmed_snippet.is_empty() {
856 rewrite_comment(trimmed_snippet, false, shape, context.config)
862 /// Recover the missing comments in the specified span, if available.
863 /// The layout of the comments will be preserved as long as it does not break the code
864 /// and its total width does not exceed the max width.
865 pub fn recover_missing_comment_in_span(
868 context: &RewriteContext<'_>,
870 ) -> Option<String> {
871 let missing_comment = rewrite_missing_comment(span, shape, context)?;
872 if missing_comment.is_empty() {
875 let missing_snippet = context.snippet(span);
876 let pos = missing_snippet.find('/').unwrap_or(0);
878 let total_width = missing_comment.len() + used_width + 1;
879 let force_new_line_before_comment =
880 missing_snippet[..pos].contains('\n') || total_width > context.config.max_width();
881 let sep = if force_new_line_before_comment {
882 shape.indent.to_string_with_newline(context.config)
886 Some(format!("{}{}", sep, missing_comment))
890 /// Trim trailing whitespaces unless they consist of two or more whitespaces.
891 fn trim_end_unless_two_whitespaces(s: &str, is_doc_comment: bool) -> &str {
892 if is_doc_comment && s.ends_with(" ") {
899 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
900 fn light_rewrite_comment(
904 is_doc_comment: bool,
906 let lines: Vec<&str> = orig
909 // This is basically just l.trim(), but in the case that a line starts
910 // with `*` we want to leave one space before it, so it aligns with the
912 let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
913 let left_trimmed = if let Some(fnw) = first_non_whitespace {
914 if l.as_bytes()[fnw] == b'*' && fnw > 0 {
922 // Preserve markdown's double-space line break syntax in doc comment.
923 trim_end_unless_two_whitespaces(left_trimmed, is_doc_comment)
926 lines.join(&format!("\n{}", offset.to_string(config)))
929 /// Trims comment characters and possibly a single space from the left of a string.
930 /// Does not trim all whitespace. If a single space is trimmed from the left of the string,
931 /// this function returns true.
932 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle<'_>) -> (&'a str, bool) {
933 if line.starts_with("//! ")
934 || line.starts_with("/// ")
935 || line.starts_with("/*! ")
936 || line.starts_with("/** ")
939 } else if let CommentStyle::Custom(opener) = *style {
940 if line.starts_with(opener) {
941 (&line[opener.len()..], true)
943 (&line[opener.trim_end().len()..], false)
945 } else if line.starts_with("/* ")
946 || line.starts_with("// ")
947 || line.starts_with("//!")
948 || line.starts_with("///")
949 || line.starts_with("** ")
950 || line.starts_with("/*!")
951 || (line.starts_with("/**") && !line.starts_with("/**/"))
953 (&line[3..], line.chars().nth(2).unwrap() == ' ')
954 } else if line.starts_with("/*")
955 || line.starts_with("* ")
956 || line.starts_with("//")
957 || line.starts_with("**")
959 (&line[2..], line.chars().nth(1).unwrap() == ' ')
960 } else if line.starts_with('*') {
963 (line, line.starts_with(' '))
967 pub trait FindUncommented {
968 fn find_uncommented(&self, pat: &str) -> Option<usize>;
971 impl FindUncommented for str {
972 fn find_uncommented(&self, pat: &str) -> Option<usize> {
973 let mut needle_iter = pat.chars();
974 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
975 match needle_iter.next() {
977 return Some(i - pat.len());
979 Some(c) => match kind {
980 FullCodeCharKind::Normal | FullCodeCharKind::InString if b == c => {}
982 needle_iter = pat.chars();
988 // Handle case where the pattern is a suffix of the search string
989 match needle_iter.next() {
991 None => Some(self.len() - pat.len()),
996 // Returns the first byte position after the first comment. The given string
997 // is expected to be prefixed by a comment, including delimiters.
998 // Good: `/* /* inner */ outer */ code();`
999 // Bad: `code(); // hello\n world!`
1000 pub fn find_comment_end(s: &str) -> Option<usize> {
1001 let mut iter = CharClasses::new(s.char_indices());
1002 for (kind, (i, _c)) in &mut iter {
1003 if kind == FullCodeCharKind::Normal || kind == FullCodeCharKind::InString {
1008 // Handle case where the comment ends at the end of `s`.
1009 if iter.status == CharClassesStatus::Normal {
1016 /// Returns `true` if text contains any comment.
1017 pub fn contains_comment(text: &str) -> bool {
1018 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
1021 pub struct CharClasses<T>
1027 status: CharClassesStatus,
1030 pub trait RichChar {
1031 fn get_char(&self) -> char;
1034 impl RichChar for char {
1035 fn get_char(&self) -> char {
1040 impl RichChar for (usize, char) {
1041 fn get_char(&self) -> char {
1046 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
1047 enum CharClassesStatus {
1049 /// Character is within a string
1052 /// Character is within a raw string
1054 RawStringPrefix(u32),
1055 RawStringSuffix(u32),
1058 /// Character inside a block comment, with the integer indicating the nesting deepness of the
1061 /// Character inside a block-commented string, with the integer indicating the nesting deepness
1063 StringInBlockComment(u32),
1064 /// Status when the '/' has been consumed, but not yet the '*', deepness is
1065 /// the new deepness (after the comment opening).
1066 BlockCommentOpening(u32),
1067 /// Status when the '*' has been consumed, but not yet the '/', deepness is
1068 /// the new deepness (after the comment closing).
1069 BlockCommentClosing(u32),
1070 /// Character is within a line comment
1074 /// Distinguish between functional part of code and comments
1075 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
1076 pub enum CodeCharKind {
1081 /// Distinguish between functional part of code and comments,
1082 /// describing opening and closing of comments for ease when chunking
1083 /// code from tagged characters
1084 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
1085 pub enum FullCodeCharKind {
1087 /// The first character of a comment, there is only one for a comment (always '/')
1089 /// Any character inside a comment including the second character of comment
1090 /// marks ("//", "/*")
1092 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
1094 /// Start of a mutlitine string inside a comment
1095 StartStringCommented,
1096 /// End of a mutlitine string inside a comment
1098 /// Inside a commented string
1100 /// Start of a mutlitine string
1102 /// End of a mutlitine string
1104 /// Inside a string.
1108 impl FullCodeCharKind {
1109 pub fn is_comment(self) -> bool {
1111 FullCodeCharKind::StartComment
1112 | FullCodeCharKind::InComment
1113 | FullCodeCharKind::EndComment
1114 | FullCodeCharKind::StartStringCommented
1115 | FullCodeCharKind::InStringCommented
1116 | FullCodeCharKind::EndStringCommented => true,
1121 /// Returns true if the character is inside a comment
1122 pub fn inside_comment(self) -> bool {
1124 FullCodeCharKind::InComment
1125 | FullCodeCharKind::StartStringCommented
1126 | FullCodeCharKind::InStringCommented
1127 | FullCodeCharKind::EndStringCommented => true,
1132 pub fn is_string(self) -> bool {
1133 self == FullCodeCharKind::InString || self == FullCodeCharKind::StartString
1136 /// Returns true if the character is within a commented string
1137 pub fn is_commented_string(self) -> bool {
1138 self == FullCodeCharKind::InStringCommented
1139 || self == FullCodeCharKind::StartStringCommented
1142 fn to_codecharkind(self) -> CodeCharKind {
1143 if self.is_comment() {
1144 CodeCharKind::Comment
1146 CodeCharKind::Normal
1151 impl<T> CharClasses<T>
1156 pub fn new(base: T) -> CharClasses<T> {
1158 base: multipeek(base),
1159 status: CharClassesStatus::Normal,
1164 fn is_raw_string_suffix<T>(iter: &mut MultiPeek<T>, count: u32) -> bool
1171 Some(c) if c.get_char() == '#' => continue,
1178 impl<T> Iterator for CharClasses<T>
1183 type Item = (FullCodeCharKind, T::Item);
1185 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
1186 let item = self.base.next()?;
1187 let chr = item.get_char();
1188 let mut char_kind = FullCodeCharKind::Normal;
1189 self.status = match self.status {
1190 CharClassesStatus::LitRawString(sharps) => {
1191 char_kind = FullCodeCharKind::InString;
1195 char_kind = FullCodeCharKind::Normal;
1196 CharClassesStatus::Normal
1197 } else if is_raw_string_suffix(&mut self.base, sharps) {
1198 CharClassesStatus::RawStringSuffix(sharps)
1200 CharClassesStatus::LitRawString(sharps)
1203 _ => CharClassesStatus::LitRawString(sharps),
1206 CharClassesStatus::RawStringPrefix(sharps) => {
1207 char_kind = FullCodeCharKind::InString;
1209 '#' => CharClassesStatus::RawStringPrefix(sharps + 1),
1210 '"' => CharClassesStatus::LitRawString(sharps),
1211 _ => CharClassesStatus::Normal, // Unreachable.
1214 CharClassesStatus::RawStringSuffix(sharps) => {
1218 CharClassesStatus::Normal
1220 char_kind = FullCodeCharKind::InString;
1221 CharClassesStatus::RawStringSuffix(sharps - 1)
1224 _ => CharClassesStatus::Normal, // Unreachable
1227 CharClassesStatus::LitString => {
1228 char_kind = FullCodeCharKind::InString;
1230 '"' => CharClassesStatus::Normal,
1231 '\\' => CharClassesStatus::LitStringEscape,
1232 _ => CharClassesStatus::LitString,
1235 CharClassesStatus::LitStringEscape => {
1236 char_kind = FullCodeCharKind::InString;
1237 CharClassesStatus::LitString
1239 CharClassesStatus::LitChar => match chr {
1240 '\\' => CharClassesStatus::LitCharEscape,
1241 '\'' => CharClassesStatus::Normal,
1242 _ => CharClassesStatus::LitChar,
1244 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
1245 CharClassesStatus::Normal => match chr {
1246 'r' => match self.base.peek().map(|c| c.get_char()) {
1247 Some('#') | Some('"') => {
1248 char_kind = FullCodeCharKind::InString;
1249 CharClassesStatus::RawStringPrefix(0)
1251 _ => CharClassesStatus::Normal,
1254 char_kind = FullCodeCharKind::InString;
1255 CharClassesStatus::LitString
1258 // HACK: Work around mut borrow.
1259 match self.base.peek() {
1260 Some(next) if next.get_char() == '\\' => {
1261 self.status = CharClassesStatus::LitChar;
1262 return Some((char_kind, item));
1267 match self.base.peek() {
1268 Some(next) if next.get_char() == '\'' => CharClassesStatus::LitChar,
1269 _ => CharClassesStatus::Normal,
1272 '/' => match self.base.peek() {
1273 Some(next) if next.get_char() == '*' => {
1274 self.status = CharClassesStatus::BlockCommentOpening(1);
1275 return Some((FullCodeCharKind::StartComment, item));
1277 Some(next) if next.get_char() == '/' => {
1278 self.status = CharClassesStatus::LineComment;
1279 return Some((FullCodeCharKind::StartComment, item));
1281 _ => CharClassesStatus::Normal,
1283 _ => CharClassesStatus::Normal,
1285 CharClassesStatus::StringInBlockComment(deepness) => {
1286 char_kind = FullCodeCharKind::InStringCommented;
1288 CharClassesStatus::BlockComment(deepness)
1290 CharClassesStatus::StringInBlockComment(deepness)
1293 CharClassesStatus::BlockComment(deepness) => {
1294 assert_ne!(deepness, 0);
1295 char_kind = FullCodeCharKind::InComment;
1296 match self.base.peek() {
1297 Some(next) if next.get_char() == '/' && chr == '*' => {
1298 CharClassesStatus::BlockCommentClosing(deepness - 1)
1300 Some(next) if next.get_char() == '*' && chr == '/' => {
1301 CharClassesStatus::BlockCommentOpening(deepness + 1)
1303 _ if chr == '"' => CharClassesStatus::StringInBlockComment(deepness),
1307 CharClassesStatus::BlockCommentOpening(deepness) => {
1308 assert_eq!(chr, '*');
1309 self.status = CharClassesStatus::BlockComment(deepness);
1310 return Some((FullCodeCharKind::InComment, item));
1312 CharClassesStatus::BlockCommentClosing(deepness) => {
1313 assert_eq!(chr, '/');
1315 self.status = CharClassesStatus::Normal;
1316 return Some((FullCodeCharKind::EndComment, item));
1318 self.status = CharClassesStatus::BlockComment(deepness);
1319 return Some((FullCodeCharKind::InComment, item));
1322 CharClassesStatus::LineComment => match chr {
1324 self.status = CharClassesStatus::Normal;
1325 return Some((FullCodeCharKind::EndComment, item));
1328 self.status = CharClassesStatus::LineComment;
1329 return Some((FullCodeCharKind::InComment, item));
1333 Some((char_kind, item))
1337 /// An iterator over the lines of a string, paired with the char kind at the
1338 /// end of the line.
1339 pub struct LineClasses<'a> {
1340 base: iter::Peekable<CharClasses<std::str::Chars<'a>>>,
1341 kind: FullCodeCharKind,
1344 impl<'a> LineClasses<'a> {
1345 pub fn new(s: &'a str) -> Self {
1347 base: CharClasses::new(s.chars()).peekable(),
1348 kind: FullCodeCharKind::Normal,
1353 impl<'a> Iterator for LineClasses<'a> {
1354 type Item = (FullCodeCharKind, String);
1356 fn next(&mut self) -> Option<Self::Item> {
1359 let mut line = String::new();
1361 let start_kind = match self.base.peek() {
1362 Some((kind, _)) => *kind,
1363 None => unreachable!(),
1366 while let Some((kind, c)) = self.base.next() {
1367 // needed to set the kind of the ending character on the last line
1370 self.kind = match (start_kind, kind) {
1371 (FullCodeCharKind::Normal, FullCodeCharKind::InString) => {
1372 FullCodeCharKind::StartString
1374 (FullCodeCharKind::InString, FullCodeCharKind::Normal) => {
1375 FullCodeCharKind::EndString
1377 (FullCodeCharKind::InComment, FullCodeCharKind::InStringCommented) => {
1378 FullCodeCharKind::StartStringCommented
1380 (FullCodeCharKind::InStringCommented, FullCodeCharKind::InComment) => {
1381 FullCodeCharKind::EndStringCommented
1390 // Workaround for CRLF newline.
1391 if line.ends_with('\r') {
1395 Some((self.kind, line))
1399 /// Iterator over functional and commented parts of a string. Any part of a string is either
1400 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
1401 /// comments is functional code. Line comments contain their ending newlines.
1402 struct UngroupedCommentCodeSlices<'a> {
1404 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
1407 impl<'a> UngroupedCommentCodeSlices<'a> {
1408 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
1409 UngroupedCommentCodeSlices {
1411 iter: CharClasses::new(code.char_indices()).peekable(),
1416 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
1417 type Item = (CodeCharKind, usize, &'a str);
1419 fn next(&mut self) -> Option<Self::Item> {
1420 let (kind, (start_idx, _)) = self.iter.next()?;
1422 FullCodeCharKind::Normal | FullCodeCharKind::InString => {
1423 // Consume all the Normal code
1424 while let Some(&(char_kind, _)) = self.iter.peek() {
1425 if char_kind.is_comment() {
1428 let _ = self.iter.next();
1431 FullCodeCharKind::StartComment => {
1432 // Consume the whole comment
1434 match self.iter.next() {
1435 Some((kind, ..)) if kind.inside_comment() => continue,
1442 let slice = match self.iter.peek() {
1443 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
1444 None => &self.slice[start_idx..],
1447 if kind.is_comment() {
1448 CodeCharKind::Comment
1450 CodeCharKind::Normal
1458 /// Iterator over an alternating sequence of functional and commented parts of
1459 /// a string. The first item is always a, possibly zero length, subslice of
1460 /// functional text. Line style comments contain their ending newlines.
1461 pub struct CommentCodeSlices<'a> {
1463 last_slice_kind: CodeCharKind,
1464 last_slice_end: usize,
1467 impl<'a> CommentCodeSlices<'a> {
1468 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
1471 last_slice_kind: CodeCharKind::Comment,
1477 impl<'a> Iterator for CommentCodeSlices<'a> {
1478 type Item = (CodeCharKind, usize, &'a str);
1480 fn next(&mut self) -> Option<Self::Item> {
1481 if self.last_slice_end == self.slice.len() {
1485 let mut sub_slice_end = self.last_slice_end;
1486 let mut first_whitespace = None;
1487 let subslice = &self.slice[self.last_slice_end..];
1488 let mut iter = CharClasses::new(subslice.char_indices());
1490 for (kind, (i, c)) in &mut iter {
1491 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal
1492 && &subslice[..2] == "//"
1493 && [' ', '\t'].contains(&c);
1495 if is_comment_connector && first_whitespace.is_none() {
1496 first_whitespace = Some(i);
1499 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
1500 let last_index = match first_whitespace {
1504 sub_slice_end = self.last_slice_end + last_index;
1508 if !is_comment_connector {
1509 first_whitespace = None;
1513 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
1514 // This was the last subslice.
1515 sub_slice_end = match first_whitespace {
1516 Some(i) => self.last_slice_end + i,
1517 None => self.slice.len(),
1521 let kind = match self.last_slice_kind {
1522 CodeCharKind::Comment => CodeCharKind::Normal,
1523 CodeCharKind::Normal => CodeCharKind::Comment,
1527 self.last_slice_end,
1528 &self.slice[self.last_slice_end..sub_slice_end],
1530 self.last_slice_end = sub_slice_end;
1531 self.last_slice_kind = kind;
1537 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
1538 /// (if it fits in the width/offset, else return `None`), else return `new`
1539 pub fn recover_comment_removed(
1542 context: &RewriteContext<'_>,
1543 ) -> Option<String> {
1544 let snippet = context.snippet(span);
1545 if snippet != new && changed_comment_content(snippet, &new) {
1546 // We missed some comments. Warn and keep the original text.
1547 if context.config.error_on_unformatted() {
1548 context.report.append(
1549 context.source_map.span_to_filename(span).into(),
1550 vec![FormattingError::from_span(
1552 &context.source_map,
1553 ErrorKind::LostComment,
1557 Some(snippet.to_owned())
1563 pub fn filter_normal_code(code: &str) -> String {
1564 let mut buffer = String::with_capacity(code.len());
1565 LineClasses::new(code).for_each(|(kind, line)| match kind {
1566 FullCodeCharKind::Normal
1567 | FullCodeCharKind::StartString
1568 | FullCodeCharKind::InString
1569 | FullCodeCharKind::EndString => {
1570 buffer.push_str(&line);
1575 if !code.ends_with('\n') && buffer.ends_with('\n') {
1581 /// Returns `true` if the two strings of code have the same payload of comments.
1582 /// The payload of comments is everything in the string except:
1583 /// - actual code (not comments),
1584 /// - comment start/end marks,
1586 /// - '*' at the beginning of lines in block comments.
1587 fn changed_comment_content(orig: &str, new: &str) -> bool {
1588 // Cannot write this as a fn since we cannot return types containing closures.
1589 let code_comment_content = |code| {
1590 let slices = UngroupedCommentCodeSlices::new(code);
1592 .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
1593 .flat_map(|(_, _, s)| CommentReducer::new(s))
1595 let res = code_comment_content(orig).ne(code_comment_content(new));
1597 "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
1601 code_comment_content(orig).collect::<String>(),
1602 code_comment_content(new).collect::<String>()
1607 /// Iterator over the 'payload' characters of a comment.
1608 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
1609 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
1611 struct CommentReducer<'a> {
1613 at_start_line: bool,
1614 iter: std::str::Chars<'a>,
1617 impl<'a> CommentReducer<'a> {
1618 fn new(comment: &'a str) -> CommentReducer<'a> {
1619 let is_block = comment.starts_with("/*");
1620 let comment = remove_comment_header(comment);
1623 // There are no supplementary '*' on the first line.
1624 at_start_line: false,
1625 iter: comment.chars(),
1630 impl<'a> Iterator for CommentReducer<'a> {
1633 fn next(&mut self) -> Option<Self::Item> {
1635 let mut c = self.iter.next()?;
1636 if self.is_block && self.at_start_line {
1637 while c.is_whitespace() {
1638 c = self.iter.next()?;
1640 // Ignore leading '*'.
1642 c = self.iter.next()?;
1644 } else if c == '\n' {
1645 self.at_start_line = true;
1647 if !c.is_whitespace() {
1654 fn remove_comment_header(comment: &str) -> &str {
1655 if comment.starts_with("///") || comment.starts_with("//!") {
1657 } else if comment.starts_with("//") {
1659 } else if (comment.starts_with("/**") && !comment.starts_with("/**/"))
1660 || comment.starts_with("/*!")
1662 &comment[3..comment.len() - 2]
1665 comment.starts_with("/*"),
1666 format!("string '{}' is not a comment", comment)
1668 &comment[2..comment.len() - 2]
1675 use crate::shape::{Indent, Shape};
1679 let mut iter = CharClasses::new("//\n\n".chars());
1681 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
1682 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
1683 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
1684 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
1685 assert_eq!(None, iter.next());
1689 fn comment_code_slices() {
1690 let input = "code(); /* test */ 1 + 1";
1691 let mut iter = CommentCodeSlices::new(input);
1693 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
1695 (CodeCharKind::Comment, 8, "/* test */"),
1696 iter.next().unwrap()
1698 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
1699 assert_eq!(None, iter.next());
1703 fn comment_code_slices_two() {
1704 let input = "// comment\n test();";
1705 let mut iter = CommentCodeSlices::new(input);
1707 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
1709 (CodeCharKind::Comment, 0, "// comment\n"),
1710 iter.next().unwrap()
1713 (CodeCharKind::Normal, 11, " test();"),
1714 iter.next().unwrap()
1716 assert_eq!(None, iter.next());
1720 fn comment_code_slices_three() {
1721 let input = "1 // comment\n // comment2\n\n";
1722 let mut iter = CommentCodeSlices::new(input);
1724 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
1726 (CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
1727 iter.next().unwrap()
1729 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
1730 assert_eq!(None, iter.next());
1735 fn format_doc_comments() {
1736 let mut wrap_normalize_config: crate::config::Config = Default::default();
1737 wrap_normalize_config.set().wrap_comments(true);
1738 wrap_normalize_config.set().normalize_comments(true);
1740 let mut wrap_config: crate::config::Config = Default::default();
1741 wrap_config.set().wrap_comments(true);
1743 let comment = rewrite_comment(" //test",
1745 Shape::legacy(100, Indent::new(0, 100)),
1746 &wrap_normalize_config).unwrap();
1747 assert_eq!("/* test */", comment);
1749 let comment = rewrite_comment("// comment on a",
1751 Shape::legacy(10, Indent::empty()),
1752 &wrap_normalize_config).unwrap();
1753 assert_eq!("// comment\n// on a", comment);
1755 let comment = rewrite_comment("// A multi line comment\n // between args.",
1757 Shape::legacy(60, Indent::new(0, 12)),
1758 &wrap_normalize_config).unwrap();
1759 assert_eq!("// A multi line comment\n // between args.", comment);
1761 let input = "// comment";
1764 let comment = rewrite_comment(input,
1766 Shape::legacy(9, Indent::new(0, 69)),
1767 &wrap_normalize_config).unwrap();
1768 assert_eq!(expected, comment);
1770 let comment = rewrite_comment("/* trimmed */",
1772 Shape::legacy(100, Indent::new(0, 100)),
1773 &wrap_normalize_config).unwrap();
1774 assert_eq!("/* trimmed */", comment);
1776 // Check that different comment style are properly recognised.
1777 let comment = rewrite_comment(r#"/// test1
1783 Shape::legacy(100, Indent::new(0, 0)),
1784 &wrap_normalize_config).unwrap();
1785 assert_eq!("/// test1\n/// test2\n// test3", comment);
1787 // Check that the blank line marks the end of a commented paragraph.
1788 let comment = rewrite_comment(r#"// test1
1792 Shape::legacy(100, Indent::new(0, 0)),
1793 &wrap_normalize_config).unwrap();
1794 assert_eq!("// test1\n\n// test2", comment);
1796 // Check that the blank line marks the end of a custom-commented paragraph.
1797 let comment = rewrite_comment(r#"//@ test1
1801 Shape::legacy(100, Indent::new(0, 0)),
1802 &wrap_normalize_config).unwrap();
1803 assert_eq!("//@ test1\n\n//@ test2", comment);
1805 // Check that bare lines are just indented but otherwise left unchanged.
1806 let comment = rewrite_comment(r#"// test1
1813 Shape::legacy(100, Indent::new(0, 0)),
1814 &wrap_config).unwrap();
1815 assert_eq!("// test1\n/*\n a bare line!\n\n another bare line!\n*/", comment);
1818 // This is probably intended to be a non-test fn, but it is not used.
1819 // We should keep this around unless it helps us test stuff to remove it.
1820 fn uncommented(text: &str) -> String {
1821 CharClasses::new(text.chars())
1822 .filter_map(|(s, c)| match s {
1823 FullCodeCharKind::Normal | FullCodeCharKind::InString => Some(c),
1830 fn test_uncommented() {
1831 assert_eq!(&uncommented("abc/*...*/"), "abc");
1833 &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
1836 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
1840 fn test_contains_comment() {
1841 assert_eq!(contains_comment("abc"), false);
1842 assert_eq!(contains_comment("abc // qsdf"), true);
1843 assert_eq!(contains_comment("abc /* kqsdf"), true);
1844 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
1848 fn test_find_uncommented() {
1849 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
1850 assert_eq!(expected, haystack.find_uncommented(needle));
1853 check("/*/ */test", "test", Some(6));
1854 check("//test\ntest", "test", Some(7));
1855 check("/* comment only */", "whatever", None);
1857 "/* comment */ some text /* more commentary */ result",
1861 check("sup // sup", "p", Some(2));
1862 check("sup", "x", None);
1863 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
1864 check("/*sup yo? \n sup*/ sup", "p", Some(20));
1865 check("hel/*lohello*/lo", "hello", None);
1866 check("acb", "ab", None);
1867 check(",/*A*/ ", ",", Some(0));
1868 check("abc", "abc", Some(0));
1869 check("/* abc */", "abc", None);
1870 check("/**/abc/* */", "abc", Some(4));
1871 check("\"/* abc */\"", "abc", Some(4));
1872 check("\"/* abc", "abc", Some(4));
1876 fn test_filter_normal_code() {
1879 println!("hello, world");
1882 assert_eq!(s, filter_normal_code(s));
1883 let s_with_comment = r#"
1886 println!("hello, world");
1889 assert_eq!(s, filter_normal_code(s_with_comment));