1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Formatting and tools for comments.
13 use std::{self, borrow::Cow, iter};
15 use itertools::{multipeek, MultiPeek};
16 use syntax::source_map::Span;
19 use rewrite::RewriteContext;
20 use shape::{Indent, Shape};
21 use string::{rewrite_string, StringFormat};
22 use utils::{count_newlines, first_line_width, last_line_width, trim_left_preserve_layout};
23 use {ErrorKind, FormattingError};
25 fn is_custom_comment(comment: &str) -> bool {
26 if !comment.starts_with("//") {
28 } else if let Some(c) = comment.chars().nth(2) {
29 !c.is_alphanumeric() && !c.is_whitespace()
35 #[derive(Copy, Clone, PartialEq, Eq)]
36 pub enum CommentStyle<'a> {
46 fn custom_opener(s: &str) -> &str {
47 s.lines().next().map_or("", |first_line| {
50 .map_or(first_line, |space_index| &first_line[0..=space_index])
54 impl<'a> CommentStyle<'a> {
55 /// Returns true if the commenting style covers a line only.
56 pub fn is_line_comment(&self) -> bool {
58 CommentStyle::DoubleSlash
59 | CommentStyle::TripleSlash
61 | CommentStyle::Custom(_) => true,
66 /// Returns true if the commenting style can span over multiple lines.
67 pub fn is_block_comment(&self) -> bool {
69 CommentStyle::SingleBullet | CommentStyle::DoubleBullet | CommentStyle::Exclamation => {
76 /// Returns true if the commenting style is for documentation.
77 pub fn is_doc_comment(&self) -> bool {
79 CommentStyle::TripleSlash | CommentStyle::Doc => true,
84 pub fn opener(&self) -> &'a str {
86 CommentStyle::DoubleSlash => "// ",
87 CommentStyle::TripleSlash => "/// ",
88 CommentStyle::Doc => "//! ",
89 CommentStyle::SingleBullet => "/* ",
90 CommentStyle::DoubleBullet => "/** ",
91 CommentStyle::Exclamation => "/*! ",
92 CommentStyle::Custom(opener) => opener,
96 pub fn closer(&self) -> &'a str {
98 CommentStyle::DoubleSlash
99 | CommentStyle::TripleSlash
100 | CommentStyle::Custom(..)
101 | CommentStyle::Doc => "",
102 CommentStyle::DoubleBullet => " **/",
103 CommentStyle::SingleBullet | CommentStyle::Exclamation => " */",
107 pub fn line_start(&self) -> &'a str {
109 CommentStyle::DoubleSlash => "// ",
110 CommentStyle::TripleSlash => "/// ",
111 CommentStyle::Doc => "//! ",
112 CommentStyle::SingleBullet | CommentStyle::Exclamation => " * ",
113 CommentStyle::DoubleBullet => " ** ",
114 CommentStyle::Custom(opener) => opener,
118 pub fn to_str_tuplet(&self) -> (&'a str, &'a str, &'a str) {
119 (self.opener(), self.closer(), self.line_start())
123 fn comment_style(orig: &str, normalize_comments: bool) -> CommentStyle {
124 if !normalize_comments {
125 if orig.starts_with("/**") && !orig.starts_with("/**/") {
126 CommentStyle::DoubleBullet
127 } else if orig.starts_with("/*!") {
128 CommentStyle::Exclamation
129 } else if orig.starts_with("/*") {
130 CommentStyle::SingleBullet
131 } else if orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/') {
132 CommentStyle::TripleSlash
133 } else if orig.starts_with("//!") {
135 } else if is_custom_comment(orig) {
136 CommentStyle::Custom(custom_opener(orig))
138 CommentStyle::DoubleSlash
140 } else if (orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/'))
141 || (orig.starts_with("/**") && !orig.starts_with("/**/"))
143 CommentStyle::TripleSlash
144 } else if orig.starts_with("//!") || orig.starts_with("/*!") {
146 } else if is_custom_comment(orig) {
147 CommentStyle::Custom(custom_opener(orig))
149 CommentStyle::DoubleSlash
153 /// Combine `prev_str` and `next_str` into a single `String`. `span` may contain
154 /// comments between two strings. If there are such comments, then that will be
155 /// recovered. If `allow_extend` is true and there is no comment between the two
156 /// strings, then they will be put on a single line as long as doing so does not
157 /// exceed max width.
158 pub fn combine_strs_with_missing_comments(
159 context: &RewriteContext,
165 ) -> Option<String> {
167 "combine_strs_with_missing_comments `{}` `{}` {:?} {:?}",
175 String::with_capacity(prev_str.len() + next_str.len() + shape.indent.width() + 128);
176 result.push_str(prev_str);
177 let mut allow_one_line = !prev_str.contains('\n') && !next_str.contains('\n');
178 let first_sep = if prev_str.is_empty() || next_str.is_empty() {
183 let mut one_line_width =
184 last_line_width(prev_str) + first_line_width(next_str) + first_sep.len();
186 let config = context.config;
187 let indent = shape.indent;
188 let missing_comment = rewrite_missing_comment(span, shape, context)?;
190 if missing_comment.is_empty() {
191 if allow_extend && prev_str.len() + first_sep.len() + next_str.len() <= shape.width {
192 result.push_str(first_sep);
193 } else if !prev_str.is_empty() {
194 result.push_str(&indent.to_string_with_newline(config))
196 result.push_str(next_str);
200 // We have a missing comment between the first expression and the second expression.
202 // Peek the the original source code and find out whether there is a newline between the first
203 // expression and the second expression or the missing comment. We will preserve the original
204 // layout whenever possible.
205 let original_snippet = context.snippet(span);
206 let prefer_same_line = if let Some(pos) = original_snippet.find('/') {
207 !original_snippet[..pos].contains('\n')
209 !original_snippet.contains('\n')
212 one_line_width -= first_sep.len();
213 let first_sep = if prev_str.is_empty() || missing_comment.is_empty() {
216 let one_line_width = last_line_width(prev_str) + first_line_width(&missing_comment) + 1;
217 if prefer_same_line && one_line_width <= shape.width {
220 indent.to_string_with_newline(config)
223 result.push_str(&first_sep);
224 result.push_str(&missing_comment);
226 let second_sep = if missing_comment.is_empty() || next_str.is_empty() {
228 } else if missing_comment.starts_with("//") {
229 indent.to_string_with_newline(config)
231 one_line_width += missing_comment.len() + first_sep.len() + 1;
232 allow_one_line &= !missing_comment.starts_with("//") && !missing_comment.contains('\n');
233 if prefer_same_line && allow_one_line && one_line_width <= shape.width {
236 indent.to_string_with_newline(config)
239 result.push_str(&second_sep);
240 result.push_str(next_str);
245 pub fn rewrite_doc_comment(orig: &str, shape: Shape, config: &Config) -> Option<String> {
246 identify_comment(orig, false, shape, config, true)
249 pub fn rewrite_comment(
254 ) -> Option<String> {
255 identify_comment(orig, block_style, shape, config, false)
263 is_doc_comment: bool,
264 ) -> Option<String> {
265 let style = comment_style(orig, false);
267 // Computes the len of line taking into account a newline if the line is part of a paragraph.
268 fn compute_len(orig: &str, line: &str) -> usize {
269 if orig.len() > line.len() {
270 if orig.as_bytes()[line.len()] == b'\r' {
280 // Get the first group of line comments having the same commenting style.
282 // Returns a tuple with:
283 // - a boolean indicating if there is a blank line
284 // - a number indicating the size of the first group of comments
285 fn consume_same_line_comments(
290 let mut first_group_ending = 0;
293 for line in orig.lines() {
294 let trimmed_line = line.trim_start();
295 if trimmed_line.is_empty() {
298 } else if trimmed_line.starts_with(line_start)
299 || comment_style(trimmed_line, false) == style
301 first_group_ending += compute_len(&orig[first_group_ending..], line);
306 (hbl, first_group_ending)
309 let (has_bare_lines, first_group_ending) = match style {
310 CommentStyle::DoubleSlash | CommentStyle::TripleSlash | CommentStyle::Doc => {
311 let line_start = style.line_start().trim_start();
312 consume_same_line_comments(style, orig, line_start)
314 CommentStyle::Custom(opener) => {
315 let trimmed_opener = opener.trim_end();
316 consume_same_line_comments(style, orig, trimmed_opener)
318 // for a block comment, search for the closing symbol
319 CommentStyle::DoubleBullet | CommentStyle::SingleBullet | CommentStyle::Exclamation => {
320 let closer = style.closer().trim_start();
321 let mut closing_symbol_offset = 0;
323 let mut first = true;
324 for line in orig.lines() {
325 closing_symbol_offset += compute_len(&orig[closing_symbol_offset..], line);
326 let mut trimmed_line = line.trim_start();
327 if !trimmed_line.starts_with('*')
328 && !trimmed_line.starts_with("//")
329 && !trimmed_line.starts_with("/*")
334 // Remove opener from consideration when searching for closer
336 let opener = style.opener().trim_end();
337 trimmed_line = &trimmed_line[opener.len()..];
340 if trimmed_line.ends_with(closer) {
344 (hbl, closing_symbol_offset)
348 let (first_group, rest) = orig.split_at(first_group_ending);
349 let rewritten_first_group =
350 if !config.normalize_comments() && has_bare_lines && style.is_block_comment() {
351 trim_left_preserve_layout(first_group, shape.indent, config)?
352 } else if !config.normalize_comments()
353 && !config.wrap_comments()
354 && !config.format_doc_comments()
356 light_rewrite_comment(first_group, shape.indent, config, is_doc_comment)
358 rewrite_comment_inner(
364 is_doc_comment || style.is_doc_comment(),
368 Some(rewritten_first_group)
380 rewritten_first_group,
381 // insert back the blank line
382 if has_bare_lines && style.is_line_comment() {
387 shape.indent.to_string(config),
394 /// Attributes for code blocks in rustdoc.
395 /// See https://doc.rust-lang.org/rustdoc/print.html#attributes
396 enum CodeBlockAttribute {
405 impl CodeBlockAttribute {
406 fn new(attribute: &str) -> CodeBlockAttribute {
408 "rust" | "" => CodeBlockAttribute::Rust,
409 "ignore" => CodeBlockAttribute::Ignore,
410 "text" => CodeBlockAttribute::Text,
411 "should_panic" => CodeBlockAttribute::ShouldPanic,
412 "no_run" => CodeBlockAttribute::NoRun,
413 "compile_fail" => CodeBlockAttribute::CompileFail,
414 _ => CodeBlockAttribute::Text,
419 /// Block that is formatted as an item.
421 /// An item starts with either a star `*` or a dash `-`. Different level of indentation are
422 /// handled by shrinking the shape accordingly.
423 struct ItemizedBlock {
424 /// the number of whitespaces up to the item sigil
426 /// the string that marks the start of an item
428 /// sequence of whitespaces to prefix new lines that are part of the item
433 /// Returns true if the line is formatted as an item
434 fn is_itemized_line(line: &str) -> bool {
435 let trimmed = line.trim_start();
436 trimmed.starts_with("* ") || trimmed.starts_with("- ")
439 /// Creates a new ItemizedBlock described with the given line.
440 /// The `is_itemized_line` needs to be called first.
441 fn new(line: &str) -> ItemizedBlock {
442 let space_to_sigil = line.chars().take_while(|c| c.is_whitespace()).count();
443 let indent = space_to_sigil + 2;
446 opener: line[..indent].to_string(),
447 line_start: " ".repeat(indent),
451 /// Returns a `StringFormat` used for formatting the content of an item
452 fn create_string_format<'a>(&'a self, fmt: &'a StringFormat) -> StringFormat<'a> {
458 shape: Shape::legacy(fmt.shape.width.saturating_sub(self.indent), Indent::empty()),
464 /// Returns true if the line is part of the current itemized block
465 fn in_block(&self, line: &str) -> bool {
466 !ItemizedBlock::is_itemized_line(line)
467 && self.indent <= line.chars().take_while(|c| c.is_whitespace()).count()
471 struct CommentRewrite<'a> {
473 code_block_buffer: String,
474 is_prev_line_multi_line: bool,
475 code_block_attr: Option<CodeBlockAttribute>,
476 item_block_buffer: String,
477 item_block: Option<ItemizedBlock>,
478 comment_line_separator: String,
482 fmt: StringFormat<'a>,
489 impl<'a> CommentRewrite<'a> {
495 ) -> CommentRewrite<'a> {
496 let (opener, closer, line_start) = if block_style {
497 CommentStyle::SingleBullet.to_str_tuplet()
499 comment_style(orig, config.normalize_comments()).to_str_tuplet()
502 let max_chars = shape
504 .checked_sub(closer.len() + opener.len())
506 let indent_str = shape.indent.to_string_with_newline(config).to_string();
507 let fmt_indent = shape.indent + (opener.len() - line_start.len());
509 let mut cr = CommentRewrite {
510 result: String::with_capacity(orig.len() * 2),
511 code_block_buffer: String::with_capacity(128),
512 is_prev_line_multi_line: false,
513 code_block_attr: None,
514 item_block_buffer: String::with_capacity(128),
516 comment_line_separator: format!("{}{}", indent_str, line_start),
526 shape: Shape::legacy(max_chars, fmt_indent),
531 opener: opener.to_owned(),
532 closer: closer.to_owned(),
533 line_start: line_start.to_owned(),
535 cr.result.push_str(opener);
539 fn join_block(s: &str, sep: &str) -> String {
540 let mut result = String::with_capacity(s.len() + 128);
541 let mut iter = s.lines().peekable();
542 while let Some(line) = iter.next() {
543 result.push_str(line);
544 result.push_str(match iter.peek() {
545 Some(next_line) if next_line.is_empty() => sep.trim_end(),
553 fn finish(mut self) -> String {
554 if !self.code_block_buffer.is_empty() {
555 // There is a code block that is not properly enclosed by backticks.
556 // We will leave them untouched.
557 self.result.push_str(&self.comment_line_separator);
558 self.result.push_str(&Self::join_block(
559 &trim_custom_comment_prefix(&self.code_block_buffer),
560 &self.comment_line_separator,
564 if !self.item_block_buffer.is_empty() {
565 // the last few lines are part of an itemized block
566 self.fmt.shape = Shape::legacy(self.max_chars, self.fmt_indent);
568 ::std::mem::swap(&mut ib, &mut self.item_block);
569 let ib = ib.unwrap();
570 let item_fmt = ib.create_string_format(&self.fmt);
571 self.result.push_str(&self.comment_line_separator);
572 self.result.push_str(&ib.opener);
573 match rewrite_string(
574 &self.item_block_buffer.replace("\n", " "),
576 self.max_chars.saturating_sub(ib.indent),
578 Some(s) => self.result.push_str(&Self::join_block(
580 &format!("{}{}", &self.comment_line_separator, ib.line_start),
582 None => self.result.push_str(&Self::join_block(
583 &self.item_block_buffer,
584 &self.comment_line_separator,
589 self.result.push_str(&self.closer);
590 if self.result.ends_with(&self.opener) && self.opener.ends_with(' ') {
603 has_leading_whitespace: bool,
605 let is_last = i == count_newlines(orig);
607 if let Some(ref ib) = self.item_block {
608 if ib.in_block(&line) {
609 self.item_block_buffer.push_str(line.trim_start());
610 self.item_block_buffer.push('\n');
613 self.is_prev_line_multi_line = false;
614 self.fmt.shape = Shape::legacy(self.max_chars, self.fmt_indent);
615 let item_fmt = ib.create_string_format(&self.fmt);
616 self.result.push_str(&self.comment_line_separator);
617 self.result.push_str(&ib.opener);
618 match rewrite_string(
619 &self.item_block_buffer.replace("\n", " "),
621 self.max_chars.saturating_sub(ib.indent),
623 Some(s) => self.result.push_str(&Self::join_block(
625 &format!("{}{}", &self.comment_line_separator, ib.line_start),
627 None => self.result.push_str(&Self::join_block(
628 &self.item_block_buffer,
629 &self.comment_line_separator,
632 self.item_block_buffer.clear();
633 } else if self.code_block_attr.is_some() {
634 if line.starts_with("```") {
635 let code_block = match self.code_block_attr.as_ref().unwrap() {
636 CodeBlockAttribute::Ignore | CodeBlockAttribute::Text => {
637 trim_custom_comment_prefix(&self.code_block_buffer)
639 _ if self.code_block_buffer.is_empty() => String::new(),
641 let mut config = self.fmt.config.clone();
642 config.set().wrap_comments(false);
643 match ::format_code_block(&self.code_block_buffer, &config) {
644 Some(ref s) => trim_custom_comment_prefix(&s.snippet),
645 None => trim_custom_comment_prefix(&self.code_block_buffer),
649 if !code_block.is_empty() {
650 self.result.push_str(&self.comment_line_separator);
652 .push_str(&Self::join_block(&code_block, &self.comment_line_separator));
654 self.code_block_buffer.clear();
655 self.result.push_str(&self.comment_line_separator);
656 self.result.push_str(line);
657 self.code_block_attr = None;
659 self.code_block_buffer
660 .push_str(&hide_sharp_behind_comment(line));
661 self.code_block_buffer.push('\n');
666 self.code_block_attr = None;
667 self.item_block = None;
668 if line.starts_with("```") {
669 self.code_block_attr = Some(CodeBlockAttribute::new(&line[3..]))
670 } else if self.fmt.config.wrap_comments() && ItemizedBlock::is_itemized_line(&line) {
671 let ib = ItemizedBlock::new(&line);
672 self.item_block_buffer.push_str(&line[ib.indent..]);
673 self.item_block_buffer.push('\n');
674 self.item_block = Some(ib);
678 if self.result == self.opener {
679 let force_leading_whitespace = &self.opener == "/* " && count_newlines(orig) == 0;
680 if !has_leading_whitespace && !force_leading_whitespace && self.result.ends_with(' ') {
686 } else if self.is_prev_line_multi_line && !line.is_empty() {
687 self.result.push(' ')
688 } else if is_last && line.is_empty() {
689 // trailing blank lines are unwanted
690 if !self.closer.is_empty() {
691 self.result.push_str(&self.indent_str);
695 self.result.push_str(&self.comment_line_separator);
696 if !has_leading_whitespace && self.result.ends_with(' ') {
701 if self.fmt.config.wrap_comments() && line.len() > self.fmt.shape.width && !has_url(line) {
702 match rewrite_string(line, &self.fmt, self.max_chars) {
704 self.is_prev_line_multi_line = s.contains('\n');
705 self.result.push_str(s);
707 None if self.is_prev_line_multi_line => {
708 // We failed to put the current `line` next to the previous `line`.
709 // Remove the trailing space, then start rewrite on the next line.
711 self.result.push_str(&self.comment_line_separator);
712 self.fmt.shape = Shape::legacy(self.max_chars, self.fmt_indent);
713 match rewrite_string(line, &self.fmt, self.max_chars) {
715 self.is_prev_line_multi_line = s.contains('\n');
716 self.result.push_str(s);
719 self.is_prev_line_multi_line = false;
720 self.result.push_str(line);
725 self.is_prev_line_multi_line = false;
726 self.result.push_str(line);
730 self.fmt.shape = if self.is_prev_line_multi_line {
732 let offset = 1 + last_line_width(&self.result) - self.line_start.len();
734 width: self.max_chars.saturating_sub(offset),
735 indent: self.fmt_indent,
736 offset: self.fmt.shape.offset + offset,
739 Shape::legacy(self.max_chars, self.fmt_indent)
742 if line.is_empty() && self.result.ends_with(' ') && !is_last {
743 // Remove space if this is an empty comment or a doc comment.
746 self.result.push_str(line);
747 self.fmt.shape = Shape::legacy(self.max_chars, self.fmt_indent);
748 self.is_prev_line_multi_line = false;
755 fn rewrite_comment_inner(
761 is_doc_comment: bool,
762 ) -> Option<String> {
763 let mut rewriter = CommentRewrite::new(orig, block_style, shape, config);
765 let line_breaks = count_newlines(orig.trim_end());
769 .map(|(i, mut line)| {
770 line = trim_end_unless_two_whitespaces(line.trim_start(), is_doc_comment);
772 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
773 line = line[..(line.len() - 2)].trim_end();
778 .map(|s| left_trim_comment_line(s, &style))
779 .map(|(line, has_leading_whitespace)| {
780 if orig.starts_with("/*") && line_breaks == 0 {
783 has_leading_whitespace || config.normalize_comments(),
786 (line, has_leading_whitespace || config.normalize_comments())
790 for (i, (line, has_leading_whitespace)) in lines.enumerate() {
791 if rewriter.handle_line(orig, i, line, has_leading_whitespace) {
796 Some(rewriter.finish())
799 const RUSTFMT_CUSTOM_COMMENT_PREFIX: &str = "//#### ";
801 fn hide_sharp_behind_comment(s: &str) -> Cow<str> {
802 if s.trim_start().starts_with("# ") {
803 Cow::from(format!("{}{}", RUSTFMT_CUSTOM_COMMENT_PREFIX, s))
809 fn trim_custom_comment_prefix(s: &str) -> String {
812 let left_trimmed = line.trim_start();
813 if left_trimmed.starts_with(RUSTFMT_CUSTOM_COMMENT_PREFIX) {
814 left_trimmed.trim_start_matches(RUSTFMT_CUSTOM_COMMENT_PREFIX)
823 /// Returns true if the given string MAY include URLs or alike.
824 fn has_url(s: &str) -> bool {
825 // This function may return false positive, but should get its job done in most cases.
826 s.contains("https://") || s.contains("http://") || s.contains("ftp://") || s.contains("file://")
829 /// Given the span, rewrite the missing comment inside it if available.
830 /// Note that the given span must only include comments (or leading/trailing whitespaces).
831 pub fn rewrite_missing_comment(
834 context: &RewriteContext,
835 ) -> Option<String> {
836 let missing_snippet = context.snippet(span);
837 let trimmed_snippet = missing_snippet.trim();
838 if !trimmed_snippet.is_empty() {
839 rewrite_comment(trimmed_snippet, false, shape, context.config)
845 /// Recover the missing comments in the specified span, if available.
846 /// The layout of the comments will be preserved as long as it does not break the code
847 /// and its total width does not exceed the max width.
848 pub fn recover_missing_comment_in_span(
851 context: &RewriteContext,
853 ) -> Option<String> {
854 let missing_comment = rewrite_missing_comment(span, shape, context)?;
855 if missing_comment.is_empty() {
858 let missing_snippet = context.snippet(span);
859 let pos = missing_snippet.find('/').unwrap_or(0);
861 let total_width = missing_comment.len() + used_width + 1;
862 let force_new_line_before_comment =
863 missing_snippet[..pos].contains('\n') || total_width > context.config.max_width();
864 let sep = if force_new_line_before_comment {
865 shape.indent.to_string_with_newline(context.config)
869 Some(format!("{}{}", sep, missing_comment))
873 /// Trim trailing whitespaces unless they consist of two or more whitespaces.
874 fn trim_end_unless_two_whitespaces(s: &str, is_doc_comment: bool) -> &str {
875 if is_doc_comment && s.ends_with(" ") {
882 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
883 fn light_rewrite_comment(
887 is_doc_comment: bool,
889 let lines: Vec<&str> = orig
892 // This is basically just l.trim(), but in the case that a line starts
893 // with `*` we want to leave one space before it, so it aligns with the
895 let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
896 let left_trimmed = if let Some(fnw) = first_non_whitespace {
897 if l.as_bytes()[fnw] == b'*' && fnw > 0 {
905 // Preserve markdown's double-space line break syntax in doc comment.
906 trim_end_unless_two_whitespaces(left_trimmed, is_doc_comment)
909 lines.join(&format!("\n{}", offset.to_string(config)))
912 /// Trims comment characters and possibly a single space from the left of a string.
913 /// Does not trim all whitespace. If a single space is trimmed from the left of the string,
914 /// this function returns true.
915 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle) -> (&'a str, bool) {
916 if line.starts_with("//! ")
917 || line.starts_with("/// ")
918 || line.starts_with("/*! ")
919 || line.starts_with("/** ")
922 } else if let CommentStyle::Custom(opener) = *style {
923 if line.starts_with(opener) {
924 (&line[opener.len()..], true)
926 (&line[opener.trim_end().len()..], false)
928 } else if line.starts_with("/* ")
929 || line.starts_with("// ")
930 || line.starts_with("//!")
931 || line.starts_with("///")
932 || line.starts_with("** ")
933 || line.starts_with("/*!")
934 || (line.starts_with("/**") && !line.starts_with("/**/"))
936 (&line[3..], line.chars().nth(2).unwrap() == ' ')
937 } else if line.starts_with("/*")
938 || line.starts_with("* ")
939 || line.starts_with("//")
940 || line.starts_with("**")
942 (&line[2..], line.chars().nth(1).unwrap() == ' ')
943 } else if line.starts_with('*') {
946 (line, line.starts_with(' '))
950 pub trait FindUncommented {
951 fn find_uncommented(&self, pat: &str) -> Option<usize>;
954 impl FindUncommented for str {
955 fn find_uncommented(&self, pat: &str) -> Option<usize> {
956 let mut needle_iter = pat.chars();
957 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
958 match needle_iter.next() {
960 return Some(i - pat.len());
962 Some(c) => match kind {
963 FullCodeCharKind::Normal | FullCodeCharKind::InString if b == c => {}
965 needle_iter = pat.chars();
971 // Handle case where the pattern is a suffix of the search string
972 match needle_iter.next() {
974 None => Some(self.len() - pat.len()),
979 // Returns the first byte position after the first comment. The given string
980 // is expected to be prefixed by a comment, including delimiters.
981 // Good: "/* /* inner */ outer */ code();"
982 // Bad: "code(); // hello\n world!"
983 pub fn find_comment_end(s: &str) -> Option<usize> {
984 let mut iter = CharClasses::new(s.char_indices());
985 for (kind, (i, _c)) in &mut iter {
986 if kind == FullCodeCharKind::Normal || kind == FullCodeCharKind::InString {
991 // Handle case where the comment ends at the end of s.
992 if iter.status == CharClassesStatus::Normal {
999 /// Returns true if text contains any comment.
1000 pub fn contains_comment(text: &str) -> bool {
1001 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
1004 pub struct CharClasses<T>
1010 status: CharClassesStatus,
1013 pub trait RichChar {
1014 fn get_char(&self) -> char;
1017 impl RichChar for char {
1018 fn get_char(&self) -> char {
1023 impl RichChar for (usize, char) {
1024 fn get_char(&self) -> char {
1029 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
1030 enum CharClassesStatus {
1035 RawStringPrefix(u32),
1036 RawStringSuffix(u32),
1039 // The u32 is the nesting deepness of the comment
1041 // Status when the '/' has been consumed, but not yet the '*', deepness is
1042 // the new deepness (after the comment opening).
1043 BlockCommentOpening(u32),
1044 // Status when the '*' has been consumed, but not yet the '/', deepness is
1045 // the new deepness (after the comment closing).
1046 BlockCommentClosing(u32),
1050 /// Distinguish between functional part of code and comments
1051 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
1052 pub enum CodeCharKind {
1057 /// Distinguish between functional part of code and comments,
1058 /// describing opening and closing of comments for ease when chunking
1059 /// code from tagged characters
1060 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
1061 pub enum FullCodeCharKind {
1063 /// The first character of a comment, there is only one for a comment (always '/')
1065 /// Any character inside a comment including the second character of comment
1066 /// marks ("//", "/*")
1068 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
1070 /// Start of a mutlitine string
1072 /// End of a mutlitine string
1074 /// Inside a string.
1078 impl FullCodeCharKind {
1079 pub fn is_comment(self) -> bool {
1081 FullCodeCharKind::StartComment
1082 | FullCodeCharKind::InComment
1083 | FullCodeCharKind::EndComment => true,
1088 pub fn is_string(self) -> bool {
1089 self == FullCodeCharKind::InString || self == FullCodeCharKind::StartString
1092 fn to_codecharkind(self) -> CodeCharKind {
1093 if self.is_comment() {
1094 CodeCharKind::Comment
1096 CodeCharKind::Normal
1101 impl<T> CharClasses<T>
1106 pub fn new(base: T) -> CharClasses<T> {
1108 base: multipeek(base),
1109 status: CharClassesStatus::Normal,
1114 fn is_raw_string_suffix<T>(iter: &mut MultiPeek<T>, count: u32) -> bool
1121 Some(c) if c.get_char() == '#' => continue,
1128 impl<T> Iterator for CharClasses<T>
1133 type Item = (FullCodeCharKind, T::Item);
1135 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
1136 let item = self.base.next()?;
1137 let chr = item.get_char();
1138 let mut char_kind = FullCodeCharKind::Normal;
1139 self.status = match self.status {
1140 CharClassesStatus::LitRawString(sharps) => {
1141 char_kind = FullCodeCharKind::InString;
1145 char_kind = FullCodeCharKind::Normal;
1146 CharClassesStatus::Normal
1147 } else if is_raw_string_suffix(&mut self.base, sharps) {
1148 CharClassesStatus::RawStringSuffix(sharps)
1150 CharClassesStatus::LitRawString(sharps)
1153 _ => CharClassesStatus::LitRawString(sharps),
1156 CharClassesStatus::RawStringPrefix(sharps) => {
1157 char_kind = FullCodeCharKind::InString;
1159 '#' => CharClassesStatus::RawStringPrefix(sharps + 1),
1160 '"' => CharClassesStatus::LitRawString(sharps),
1161 _ => CharClassesStatus::Normal, // Unreachable.
1164 CharClassesStatus::RawStringSuffix(sharps) => {
1168 CharClassesStatus::Normal
1170 char_kind = FullCodeCharKind::InString;
1171 CharClassesStatus::RawStringSuffix(sharps - 1)
1174 _ => CharClassesStatus::Normal, // Unreachable
1177 CharClassesStatus::LitString => {
1178 char_kind = FullCodeCharKind::InString;
1180 '"' => CharClassesStatus::Normal,
1181 '\\' => CharClassesStatus::LitStringEscape,
1182 _ => CharClassesStatus::LitString,
1185 CharClassesStatus::LitStringEscape => {
1186 char_kind = FullCodeCharKind::InString;
1187 CharClassesStatus::LitString
1189 CharClassesStatus::LitChar => match chr {
1190 '\\' => CharClassesStatus::LitCharEscape,
1191 '\'' => CharClassesStatus::Normal,
1192 _ => CharClassesStatus::LitChar,
1194 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
1195 CharClassesStatus::Normal => match chr {
1196 'r' => match self.base.peek().map(|c| c.get_char()) {
1197 Some('#') | Some('"') => {
1198 char_kind = FullCodeCharKind::InString;
1199 CharClassesStatus::RawStringPrefix(0)
1201 _ => CharClassesStatus::Normal,
1204 char_kind = FullCodeCharKind::InString;
1205 CharClassesStatus::LitString
1208 // HACK: Work around mut borrow.
1209 match self.base.peek() {
1210 Some(next) if next.get_char() == '\\' => {
1211 self.status = CharClassesStatus::LitChar;
1212 return Some((char_kind, item));
1217 match self.base.peek() {
1218 Some(next) if next.get_char() == '\'' => CharClassesStatus::LitChar,
1219 _ => CharClassesStatus::Normal,
1222 '/' => match self.base.peek() {
1223 Some(next) if next.get_char() == '*' => {
1224 self.status = CharClassesStatus::BlockCommentOpening(1);
1225 return Some((FullCodeCharKind::StartComment, item));
1227 Some(next) if next.get_char() == '/' => {
1228 self.status = CharClassesStatus::LineComment;
1229 return Some((FullCodeCharKind::StartComment, item));
1231 _ => CharClassesStatus::Normal,
1233 _ => CharClassesStatus::Normal,
1235 CharClassesStatus::BlockComment(deepness) => {
1236 assert_ne!(deepness, 0);
1237 self.status = match self.base.peek() {
1238 Some(next) if next.get_char() == '/' && chr == '*' => {
1239 CharClassesStatus::BlockCommentClosing(deepness - 1)
1241 Some(next) if next.get_char() == '*' && chr == '/' => {
1242 CharClassesStatus::BlockCommentOpening(deepness + 1)
1244 _ => CharClassesStatus::BlockComment(deepness),
1246 return Some((FullCodeCharKind::InComment, item));
1248 CharClassesStatus::BlockCommentOpening(deepness) => {
1249 assert_eq!(chr, '*');
1250 self.status = CharClassesStatus::BlockComment(deepness);
1251 return Some((FullCodeCharKind::InComment, item));
1253 CharClassesStatus::BlockCommentClosing(deepness) => {
1254 assert_eq!(chr, '/');
1256 self.status = CharClassesStatus::Normal;
1257 return Some((FullCodeCharKind::EndComment, item));
1259 self.status = CharClassesStatus::BlockComment(deepness);
1260 return Some((FullCodeCharKind::InComment, item));
1263 CharClassesStatus::LineComment => match chr {
1265 self.status = CharClassesStatus::Normal;
1266 return Some((FullCodeCharKind::EndComment, item));
1269 self.status = CharClassesStatus::LineComment;
1270 return Some((FullCodeCharKind::InComment, item));
1274 Some((char_kind, item))
1278 /// An iterator over the lines of a string, paired with the char kind at the
1279 /// end of the line.
1280 pub struct LineClasses<'a> {
1281 base: iter::Peekable<CharClasses<std::str::Chars<'a>>>,
1282 kind: FullCodeCharKind,
1285 impl<'a> LineClasses<'a> {
1286 pub fn new(s: &'a str) -> Self {
1288 base: CharClasses::new(s.chars()).peekable(),
1289 kind: FullCodeCharKind::Normal,
1294 impl<'a> Iterator for LineClasses<'a> {
1295 type Item = (FullCodeCharKind, String);
1297 fn next(&mut self) -> Option<Self::Item> {
1300 let mut line = String::new();
1302 let start_class = match self.base.peek() {
1303 Some((kind, _)) => *kind,
1304 None => unreachable!(),
1307 while let Some((kind, c)) = self.base.next() {
1309 self.kind = match (start_class, kind) {
1310 (FullCodeCharKind::Normal, FullCodeCharKind::InString) => {
1311 FullCodeCharKind::StartString
1313 (FullCodeCharKind::InString, FullCodeCharKind::Normal) => {
1314 FullCodeCharKind::EndString
1324 // Workaround for CRLF newline.
1325 if line.ends_with('\r') {
1329 Some((self.kind, line))
1333 /// Iterator over functional and commented parts of a string. Any part of a string is either
1334 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
1335 /// comments is functional code. Line comments contain their ending newlines.
1336 struct UngroupedCommentCodeSlices<'a> {
1338 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
1341 impl<'a> UngroupedCommentCodeSlices<'a> {
1342 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
1343 UngroupedCommentCodeSlices {
1345 iter: CharClasses::new(code.char_indices()).peekable(),
1350 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
1351 type Item = (CodeCharKind, usize, &'a str);
1353 fn next(&mut self) -> Option<Self::Item> {
1354 let (kind, (start_idx, _)) = self.iter.next()?;
1356 FullCodeCharKind::Normal | FullCodeCharKind::InString => {
1357 // Consume all the Normal code
1358 while let Some(&(char_kind, _)) = self.iter.peek() {
1359 if char_kind.is_comment() {
1362 let _ = self.iter.next();
1365 FullCodeCharKind::StartComment => {
1366 // Consume the whole comment
1367 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
1371 let slice = match self.iter.peek() {
1372 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
1373 None => &self.slice[start_idx..],
1376 if kind.is_comment() {
1377 CodeCharKind::Comment
1379 CodeCharKind::Normal
1387 /// Iterator over an alternating sequence of functional and commented parts of
1388 /// a string. The first item is always a, possibly zero length, subslice of
1389 /// functional text. Line style comments contain their ending newlines.
1390 pub struct CommentCodeSlices<'a> {
1392 last_slice_kind: CodeCharKind,
1393 last_slice_end: usize,
1396 impl<'a> CommentCodeSlices<'a> {
1397 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
1400 last_slice_kind: CodeCharKind::Comment,
1406 impl<'a> Iterator for CommentCodeSlices<'a> {
1407 type Item = (CodeCharKind, usize, &'a str);
1409 fn next(&mut self) -> Option<Self::Item> {
1410 if self.last_slice_end == self.slice.len() {
1414 let mut sub_slice_end = self.last_slice_end;
1415 let mut first_whitespace = None;
1416 let subslice = &self.slice[self.last_slice_end..];
1417 let mut iter = CharClasses::new(subslice.char_indices());
1419 for (kind, (i, c)) in &mut iter {
1420 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal
1421 && &subslice[..2] == "//"
1422 && [' ', '\t'].contains(&c);
1424 if is_comment_connector && first_whitespace.is_none() {
1425 first_whitespace = Some(i);
1428 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
1429 let last_index = match first_whitespace {
1433 sub_slice_end = self.last_slice_end + last_index;
1437 if !is_comment_connector {
1438 first_whitespace = None;
1442 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
1443 // This was the last subslice.
1444 sub_slice_end = match first_whitespace {
1445 Some(i) => self.last_slice_end + i,
1446 None => self.slice.len(),
1450 let kind = match self.last_slice_kind {
1451 CodeCharKind::Comment => CodeCharKind::Normal,
1452 CodeCharKind::Normal => CodeCharKind::Comment,
1456 self.last_slice_end,
1457 &self.slice[self.last_slice_end..sub_slice_end],
1459 self.last_slice_end = sub_slice_end;
1460 self.last_slice_kind = kind;
1466 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
1467 /// (if it fits in the width/offset, else return None), else return `new`
1468 pub fn recover_comment_removed(
1471 context: &RewriteContext,
1472 ) -> Option<String> {
1473 let snippet = context.snippet(span);
1474 if snippet != new && changed_comment_content(snippet, &new) {
1475 // We missed some comments. Warn and keep the original text.
1476 if context.config.error_on_unformatted() {
1477 context.report.append(
1478 context.source_map.span_to_filename(span).into(),
1479 vec![FormattingError::from_span(
1481 &context.source_map,
1482 ErrorKind::LostComment,
1486 Some(snippet.to_owned())
1492 pub fn filter_normal_code(code: &str) -> String {
1493 let mut buffer = String::with_capacity(code.len());
1494 LineClasses::new(code).for_each(|(kind, line)| match kind {
1495 FullCodeCharKind::Normal
1496 | FullCodeCharKind::StartString
1497 | FullCodeCharKind::InString
1498 | FullCodeCharKind::EndString => {
1499 buffer.push_str(&line);
1504 if !code.ends_with('\n') && buffer.ends_with('\n') {
1510 /// Return true if the two strings of code have the same payload of comments.
1511 /// The payload of comments is everything in the string except:
1512 /// - actual code (not comments)
1513 /// - comment start/end marks
1515 /// - '*' at the beginning of lines in block comments
1516 fn changed_comment_content(orig: &str, new: &str) -> bool {
1517 // Cannot write this as a fn since we cannot return types containing closures
1518 let code_comment_content = |code| {
1519 let slices = UngroupedCommentCodeSlices::new(code);
1521 .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
1522 .flat_map(|(_, _, s)| CommentReducer::new(s))
1524 let res = code_comment_content(orig).ne(code_comment_content(new));
1526 "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
1530 code_comment_content(orig).collect::<String>(),
1531 code_comment_content(new).collect::<String>()
1536 /// Iterator over the 'payload' characters of a comment.
1537 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
1538 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
1540 struct CommentReducer<'a> {
1542 at_start_line: bool,
1543 iter: std::str::Chars<'a>,
1546 impl<'a> CommentReducer<'a> {
1547 fn new(comment: &'a str) -> CommentReducer<'a> {
1548 let is_block = comment.starts_with("/*");
1549 let comment = remove_comment_header(comment);
1552 at_start_line: false, // There are no supplementary '*' on the first line
1553 iter: comment.chars(),
1558 impl<'a> Iterator for CommentReducer<'a> {
1561 fn next(&mut self) -> Option<Self::Item> {
1563 let mut c = self.iter.next()?;
1564 if self.is_block && self.at_start_line {
1565 while c.is_whitespace() {
1566 c = self.iter.next()?;
1568 // Ignore leading '*'
1570 c = self.iter.next()?;
1572 } else if c == '\n' {
1573 self.at_start_line = true;
1575 if !c.is_whitespace() {
1582 fn remove_comment_header(comment: &str) -> &str {
1583 if comment.starts_with("///") || comment.starts_with("//!") {
1585 } else if comment.starts_with("//") {
1587 } else if (comment.starts_with("/**") && !comment.starts_with("/**/"))
1588 || comment.starts_with("/*!")
1590 &comment[3..comment.len() - 2]
1593 comment.starts_with("/*"),
1594 format!("string '{}' is not a comment", comment)
1596 &comment[2..comment.len() - 2]
1603 use shape::{Indent, Shape};
1607 let mut iter = CharClasses::new("//\n\n".chars());
1609 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
1610 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
1611 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
1612 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
1613 assert_eq!(None, iter.next());
1617 fn comment_code_slices() {
1618 let input = "code(); /* test */ 1 + 1";
1619 let mut iter = CommentCodeSlices::new(input);
1621 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
1623 (CodeCharKind::Comment, 8, "/* test */"),
1624 iter.next().unwrap()
1626 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
1627 assert_eq!(None, iter.next());
1631 fn comment_code_slices_two() {
1632 let input = "// comment\n test();";
1633 let mut iter = CommentCodeSlices::new(input);
1635 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
1637 (CodeCharKind::Comment, 0, "// comment\n"),
1638 iter.next().unwrap()
1641 (CodeCharKind::Normal, 11, " test();"),
1642 iter.next().unwrap()
1644 assert_eq!(None, iter.next());
1648 fn comment_code_slices_three() {
1649 let input = "1 // comment\n // comment2\n\n";
1650 let mut iter = CommentCodeSlices::new(input);
1652 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
1654 (CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
1655 iter.next().unwrap()
1657 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
1658 assert_eq!(None, iter.next());
1663 fn format_doc_comments() {
1664 let mut wrap_normalize_config: ::config::Config = Default::default();
1665 wrap_normalize_config.set().wrap_comments(true);
1666 wrap_normalize_config.set().normalize_comments(true);
1668 let mut wrap_config: ::config::Config = Default::default();
1669 wrap_config.set().wrap_comments(true);
1671 let comment = rewrite_comment(" //test",
1673 Shape::legacy(100, Indent::new(0, 100)),
1674 &wrap_normalize_config).unwrap();
1675 assert_eq!("/* test */", comment);
1677 let comment = rewrite_comment("// comment on a",
1679 Shape::legacy(10, Indent::empty()),
1680 &wrap_normalize_config).unwrap();
1681 assert_eq!("// comment\n// on a", comment);
1683 let comment = rewrite_comment("// A multi line comment\n // between args.",
1685 Shape::legacy(60, Indent::new(0, 12)),
1686 &wrap_normalize_config).unwrap();
1687 assert_eq!("// A multi line comment\n // between args.", comment);
1689 let input = "// comment";
1692 let comment = rewrite_comment(input,
1694 Shape::legacy(9, Indent::new(0, 69)),
1695 &wrap_normalize_config).unwrap();
1696 assert_eq!(expected, comment);
1698 let comment = rewrite_comment("/* trimmed */",
1700 Shape::legacy(100, Indent::new(0, 100)),
1701 &wrap_normalize_config).unwrap();
1702 assert_eq!("/* trimmed */", comment);
1704 // check that different comment style are properly recognised
1705 let comment = rewrite_comment(r#"/// test1
1711 Shape::legacy(100, Indent::new(0, 0)),
1712 &wrap_normalize_config).unwrap();
1713 assert_eq!("/// test1\n/// test2\n// test3", comment);
1715 // check that the blank line marks the end of a commented paragraph
1716 let comment = rewrite_comment(r#"// test1
1720 Shape::legacy(100, Indent::new(0, 0)),
1721 &wrap_normalize_config).unwrap();
1722 assert_eq!("// test1\n\n// test2", comment);
1724 // check that the blank line marks the end of a custom-commented paragraph
1725 let comment = rewrite_comment(r#"//@ test1
1729 Shape::legacy(100, Indent::new(0, 0)),
1730 &wrap_normalize_config).unwrap();
1731 assert_eq!("//@ test1\n\n//@ test2", comment);
1733 // check that bare lines are just indented but left unchanged otherwise
1734 let comment = rewrite_comment(r#"// test1
1741 Shape::legacy(100, Indent::new(0, 0)),
1742 &wrap_config).unwrap();
1743 assert_eq!("// test1\n/*\n a bare line!\n\n another bare line!\n*/", comment);
1746 // This is probably intended to be a non-test fn, but it is not used. I'm
1747 // keeping it around unless it helps us test stuff.
1748 fn uncommented(text: &str) -> String {
1749 CharClasses::new(text.chars())
1750 .filter_map(|(s, c)| match s {
1751 FullCodeCharKind::Normal | FullCodeCharKind::InString => Some(c),
1758 fn test_uncommented() {
1759 assert_eq!(&uncommented("abc/*...*/"), "abc");
1761 &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
1764 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
1768 fn test_contains_comment() {
1769 assert_eq!(contains_comment("abc"), false);
1770 assert_eq!(contains_comment("abc // qsdf"), true);
1771 assert_eq!(contains_comment("abc /* kqsdf"), true);
1772 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
1776 fn test_find_uncommented() {
1777 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
1778 assert_eq!(expected, haystack.find_uncommented(needle));
1781 check("/*/ */test", "test", Some(6));
1782 check("//test\ntest", "test", Some(7));
1783 check("/* comment only */", "whatever", None);
1785 "/* comment */ some text /* more commentary */ result",
1789 check("sup // sup", "p", Some(2));
1790 check("sup", "x", None);
1791 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
1792 check("/*sup yo? \n sup*/ sup", "p", Some(20));
1793 check("hel/*lohello*/lo", "hello", None);
1794 check("acb", "ab", None);
1795 check(",/*A*/ ", ",", Some(0));
1796 check("abc", "abc", Some(0));
1797 check("/* abc */", "abc", None);
1798 check("/**/abc/* */", "abc", Some(4));
1799 check("\"/* abc */\"", "abc", Some(4));
1800 check("\"/* abc", "abc", Some(4));
1804 fn test_filter_normal_code() {
1807 println!("hello, world");
1810 assert_eq!(s, filter_normal_code(s));
1811 let s_with_comment = r#"
1814 println!("hello, world");
1817 assert_eq!(s, filter_normal_code(s_with_comment));