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, iter};
15 use syntax::codemap::Span;
19 use rewrite::RewriteContext;
20 use string::{StringFormat, rewrite_string};
23 fn is_custom_comment(comment: &str) -> bool {
24 if !comment.starts_with("//") {
27 if let Some(c) = comment.chars().nth(2) {
28 !c.is_alphanumeric() && !c.is_whitespace()
35 #[derive(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 + 1])
54 impl<'a> CommentStyle<'a> {
55 pub fn opener(&self) -> &'a str {
57 CommentStyle::DoubleSlash => "// ",
58 CommentStyle::TripleSlash => "/// ",
59 CommentStyle::Doc => "//! ",
60 CommentStyle::SingleBullet => "/* ",
61 CommentStyle::DoubleBullet => "/** ",
62 CommentStyle::Exclamation => "/*! ",
63 CommentStyle::Custom(opener) => opener,
67 pub fn closer(&self) -> &'a str {
69 CommentStyle::DoubleSlash |
70 CommentStyle::TripleSlash |
71 CommentStyle::Custom(..) |
72 CommentStyle::Doc => "",
73 CommentStyle::DoubleBullet => " **/",
74 CommentStyle::SingleBullet | CommentStyle::Exclamation => " */",
78 pub fn line_start(&self) -> &'a str {
80 CommentStyle::DoubleSlash => "// ",
81 CommentStyle::TripleSlash => "/// ",
82 CommentStyle::Doc => "//! ",
83 CommentStyle::SingleBullet | CommentStyle::Exclamation => " * ",
84 CommentStyle::DoubleBullet => " ** ",
85 CommentStyle::Custom(opener) => opener,
89 pub fn to_str_tuplet(&self) -> (&'a str, &'a str, &'a str) {
90 (self.opener(), self.closer(), self.line_start())
93 pub fn line_with_same_comment_style(&self, line: &str, normalize_comments: bool) -> bool {
95 CommentStyle::DoubleSlash | CommentStyle::TripleSlash | CommentStyle::Doc => {
96 line.trim_left().starts_with(self.line_start().trim_left()) ||
97 comment_style(line, normalize_comments) == *self
99 CommentStyle::DoubleBullet | CommentStyle::SingleBullet | CommentStyle::Exclamation => {
100 line.trim_left().starts_with(self.closer().trim_left()) ||
101 line.trim_left().starts_with(self.line_start().trim_left()) ||
102 comment_style(line, normalize_comments) == *self
104 CommentStyle::Custom(opener) => line.trim_left().starts_with(opener.trim_right()),
109 fn comment_style(orig: &str, normalize_comments: bool) -> CommentStyle {
110 if !normalize_comments {
111 if orig.starts_with("/**") && !orig.starts_with("/**/") {
112 CommentStyle::DoubleBullet
113 } else if orig.starts_with("/*!") {
114 CommentStyle::Exclamation
115 } else if orig.starts_with("/*") {
116 CommentStyle::SingleBullet
117 } else if orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/') {
118 CommentStyle::TripleSlash
119 } else if orig.starts_with("//!") {
121 } else if is_custom_comment(orig) {
122 CommentStyle::Custom(custom_opener(orig))
124 CommentStyle::DoubleSlash
126 } else if (orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/')) ||
127 (orig.starts_with("/**") && !orig.starts_with("/**/"))
129 CommentStyle::TripleSlash
130 } else if orig.starts_with("//!") || orig.starts_with("/*!") {
132 } else if is_custom_comment(orig) {
133 CommentStyle::Custom(custom_opener(orig))
135 CommentStyle::DoubleSlash
139 pub fn rewrite_comment(
144 ) -> Option<String> {
145 // If there are lines without a starting sigil, we won't format them correctly
146 // so in that case we won't even re-align (if !config.normalize_comments()) and
147 // we should stop now.
148 let num_bare_lines = orig.lines()
149 .map(|line| line.trim())
151 !(l.starts_with('*') || l.starts_with("//") || l.starts_with("/*"))
154 if num_bare_lines > 0 && !config.normalize_comments() {
155 return Some(orig.to_owned());
157 if !config.normalize_comments() && !config.wrap_comments() {
158 return light_rewrite_comment(orig, shape.indent, config);
161 identify_comment(orig, block_style, shape, config)
169 ) -> Option<String> {
170 let style = comment_style(orig, false);
171 let first_group = orig.lines()
172 .take_while(|l| style.line_with_same_comment_style(l, false))
175 let rest = orig.lines()
176 .skip(first_group.lines().count())
180 let first_group_str = try_opt!(rewrite_comment_inner(
188 Some(first_group_str)
190 identify_comment(&rest, block_style, shape, config).map(|rest_str| {
194 shape.indent.to_string(config),
201 fn rewrite_comment_inner(
207 ) -> Option<String> {
208 let (opener, closer, line_start) = if block_style {
209 CommentStyle::SingleBullet.to_str_tuplet()
211 comment_style(orig, config.normalize_comments()).to_str_tuplet()
214 let max_chars = shape
216 .checked_sub(closer.len() + opener.len())
218 let indent_str = shape.indent.to_string(config);
219 let fmt = StringFormat {
222 line_start: line_start,
224 shape: Shape::legacy(max_chars, shape.indent + (opener.len() - line_start.len())),
229 let line_breaks = orig.trim_right().chars().filter(|&c| c == '\n').count();
230 let lines = orig.lines()
232 .map(|(i, mut line)| {
235 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
236 line = &line[..(line.len() - 2)].trim_right();
241 .map(|s| left_trim_comment_line(s, &style))
242 .map(|line| if orig.starts_with("/*") && line_breaks == 0 {
248 let mut result = opener.to_owned();
250 if result == opener {
256 result.push_str(&indent_str);
257 result.push_str(line_start);
260 if config.wrap_comments() && line.len() > max_chars {
261 let rewrite = rewrite_string(line, &fmt).unwrap_or(line.to_owned());
262 result.push_str(&rewrite);
264 if line.is_empty() && result.ends_with(' ') {
265 // Remove space if this is an empty comment or a doc comment.
268 result.push_str(line);
272 result.push_str(closer);
273 if result == opener && result.ends_with(' ') {
281 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
282 fn light_rewrite_comment(orig: &str, offset: Indent, config: &Config) -> Option<String> {
283 let lines: Vec<&str> = orig.lines()
285 // This is basically just l.trim(), but in the case that a line starts
286 // with `*` we want to leave one space before it, so it aligns with the
288 let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
289 if let Some(fnw) = first_non_whitespace {
290 if l.as_bytes()[fnw] == '*' as u8 && fnw > 0 {
300 Some(lines.join(&format!("\n{}", offset.to_string(config))))
303 /// Trims comment characters and possibly a single space from the left of a string.
304 /// Does not trim all whitespace.
305 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle) -> &'a str {
306 if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") ||
307 line.starts_with("/** ")
310 } else if let &CommentStyle::Custom(opener) = style {
311 if line.starts_with(opener) {
312 &line[opener.len()..]
314 &line[opener.trim_right().len()..]
316 } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!") ||
317 line.starts_with("///") ||
318 line.starts_with("** ") || line.starts_with("/*!") ||
319 (line.starts_with("/**") && !line.starts_with("/**/"))
322 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") ||
323 line.starts_with("**")
326 } else if line.starts_with('*') {
333 pub trait FindUncommented {
334 fn find_uncommented(&self, pat: &str) -> Option<usize>;
337 impl FindUncommented for str {
338 fn find_uncommented(&self, pat: &str) -> Option<usize> {
339 let mut needle_iter = pat.chars();
340 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
341 match needle_iter.next() {
343 return Some(i - pat.len());
347 FullCodeCharKind::Normal if b == c => {}
349 needle_iter = pat.chars();
356 // Handle case where the pattern is a suffix of the search string
357 match needle_iter.next() {
359 None => Some(self.len() - pat.len()),
364 // Returns the first byte position after the first comment. The given string
365 // is expected to be prefixed by a comment, including delimiters.
366 // Good: "/* /* inner */ outer */ code();"
367 // Bad: "code(); // hello\n world!"
368 pub fn find_comment_end(s: &str) -> Option<usize> {
369 let mut iter = CharClasses::new(s.char_indices());
370 for (kind, (i, _c)) in &mut iter {
371 if kind == FullCodeCharKind::Normal {
376 // Handle case where the comment ends at the end of s.
377 if iter.status == CharClassesStatus::Normal {
384 /// Returns true if text contains any comment.
385 pub fn contains_comment(text: &str) -> bool {
386 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
389 struct CharClasses<T>
394 base: iter::Peekable<T>,
395 status: CharClassesStatus,
399 fn get_char(&self) -> char;
402 impl RichChar for char {
403 fn get_char(&self) -> char {
408 impl RichChar for (usize, char) {
409 fn get_char(&self) -> char {
414 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
415 enum CharClassesStatus {
421 // The u32 is the nesting deepness of the comment
423 // Status when the '/' has been consumed, but not yet the '*', deepness is
424 // the new deepness (after the comment opening).
425 BlockCommentOpening(u32),
426 // Status when the '*' has been consumed, but not yet the '/', deepness is
427 // the new deepness (after the comment closing).
428 BlockCommentClosing(u32),
432 /// Distinguish between functional part of code and comments
433 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
434 pub enum CodeCharKind {
439 /// Distinguish between functional part of code and comments,
440 /// describing opening and closing of comments for ease when chunking
441 /// code from tagged characters
442 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
443 enum FullCodeCharKind {
445 /// The first character of a comment, there is only one for a comment (always '/')
447 /// Any character inside a comment including the second character of comment
448 /// marks ("//", "/*")
450 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
454 impl FullCodeCharKind {
455 fn is_comment(&self) -> bool {
457 FullCodeCharKind::Normal => false,
458 FullCodeCharKind::StartComment |
459 FullCodeCharKind::InComment |
460 FullCodeCharKind::EndComment => true,
464 fn to_codecharkind(&self) -> CodeCharKind {
465 if self.is_comment() {
466 CodeCharKind::Comment
473 impl<T> CharClasses<T>
478 fn new(base: T) -> CharClasses<T> {
480 base: base.peekable(),
481 status: CharClassesStatus::Normal,
486 impl<T> Iterator for CharClasses<T>
491 type Item = (FullCodeCharKind, T::Item);
493 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
494 let item = try_opt!(self.base.next());
495 let chr = item.get_char();
496 self.status = match self.status {
497 CharClassesStatus::LitString => {
499 '"' => CharClassesStatus::Normal,
500 '\\' => CharClassesStatus::LitStringEscape,
501 _ => CharClassesStatus::LitString,
504 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
505 CharClassesStatus::LitChar => {
507 '\\' => CharClassesStatus::LitCharEscape,
508 '\'' => CharClassesStatus::Normal,
509 _ => CharClassesStatus::LitChar,
512 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
513 CharClassesStatus::Normal => {
515 '"' => CharClassesStatus::LitString,
516 '\'' => CharClassesStatus::LitChar,
518 match self.base.peek() {
519 Some(next) if next.get_char() == '*' => {
520 self.status = CharClassesStatus::BlockCommentOpening(1);
521 return Some((FullCodeCharKind::StartComment, item));
523 Some(next) if next.get_char() == '/' => {
524 self.status = CharClassesStatus::LineComment;
525 return Some((FullCodeCharKind::StartComment, item));
527 _ => CharClassesStatus::Normal,
530 _ => CharClassesStatus::Normal,
533 CharClassesStatus::BlockComment(deepness) => {
534 assert!(deepness != 0);
535 self.status = match self.base.peek() {
536 Some(next) if next.get_char() == '/' && chr == '*' => {
537 CharClassesStatus::BlockCommentClosing(deepness - 1)
539 Some(next) if next.get_char() == '*' && chr == '/' => {
540 CharClassesStatus::BlockCommentOpening(deepness + 1)
542 _ => CharClassesStatus::BlockComment(deepness),
544 return Some((FullCodeCharKind::InComment, item));
546 CharClassesStatus::BlockCommentOpening(deepness) => {
547 assert_eq!(chr, '*');
548 self.status = CharClassesStatus::BlockComment(deepness);
549 return Some((FullCodeCharKind::InComment, item));
551 CharClassesStatus::BlockCommentClosing(deepness) => {
552 assert_eq!(chr, '/');
554 self.status = CharClassesStatus::Normal;
555 return Some((FullCodeCharKind::EndComment, item));
557 self.status = CharClassesStatus::BlockComment(deepness);
558 return Some((FullCodeCharKind::InComment, item));
561 CharClassesStatus::LineComment => {
564 self.status = CharClassesStatus::Normal;
565 return Some((FullCodeCharKind::EndComment, item));
568 self.status = CharClassesStatus::LineComment;
569 return Some((FullCodeCharKind::InComment, item));
574 Some((FullCodeCharKind::Normal, item))
578 /// Iterator over functional and commented parts of a string. Any part of a string is either
579 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
580 /// comments is functional code. Line comments contain their ending newlines.
581 struct UngroupedCommentCodeSlices<'a> {
583 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
586 impl<'a> UngroupedCommentCodeSlices<'a> {
587 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
588 UngroupedCommentCodeSlices {
590 iter: CharClasses::new(code.char_indices()).peekable(),
595 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
596 type Item = (CodeCharKind, usize, &'a str);
598 fn next(&mut self) -> Option<Self::Item> {
599 let (kind, (start_idx, _)) = try_opt!(self.iter.next());
601 FullCodeCharKind::Normal => {
602 // Consume all the Normal code
603 while let Some(&(FullCodeCharKind::Normal, (_, _))) = self.iter.peek() {
604 let _ = self.iter.next();
607 FullCodeCharKind::StartComment => {
608 // Consume the whole comment
609 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
613 let slice = match self.iter.peek() {
614 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
615 None => &self.slice[start_idx..],
618 if kind.is_comment() {
619 CodeCharKind::Comment
632 /// Iterator over an alternating sequence of functional and commented parts of
633 /// a string. The first item is always a, possibly zero length, subslice of
634 /// functional text. Line style comments contain their ending newlines.
635 pub struct CommentCodeSlices<'a> {
637 last_slice_kind: CodeCharKind,
638 last_slice_end: usize,
641 impl<'a> CommentCodeSlices<'a> {
642 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
645 last_slice_kind: CodeCharKind::Comment,
651 impl<'a> Iterator for CommentCodeSlices<'a> {
652 type Item = (CodeCharKind, usize, &'a str);
654 fn next(&mut self) -> Option<Self::Item> {
655 if self.last_slice_end == self.slice.len() {
659 let mut sub_slice_end = self.last_slice_end;
660 let mut first_whitespace = None;
661 let subslice = &self.slice[self.last_slice_end..];
662 let mut iter = CharClasses::new(subslice.char_indices());
664 for (kind, (i, c)) in &mut iter {
665 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
666 &subslice[..2] == "//" &&
667 [' ', '\t'].contains(&c);
669 if is_comment_connector && first_whitespace.is_none() {
670 first_whitespace = Some(i);
673 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
674 let last_index = match first_whitespace {
678 sub_slice_end = self.last_slice_end + last_index;
682 if !is_comment_connector {
683 first_whitespace = None;
687 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
688 // This was the last subslice.
689 sub_slice_end = match first_whitespace {
690 Some(i) => self.last_slice_end + i,
691 None => self.slice.len(),
695 let kind = match self.last_slice_kind {
696 CodeCharKind::Comment => CodeCharKind::Normal,
697 CodeCharKind::Normal => CodeCharKind::Comment,
702 &self.slice[self.last_slice_end..sub_slice_end],
704 self.last_slice_end = sub_slice_end;
705 self.last_slice_kind = kind;
711 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
712 /// (if it fits in the width/offset, else return None), else return `new`
713 pub fn recover_comment_removed(
716 context: &RewriteContext,
718 ) -> Option<String> {
719 let snippet = context.snippet(span);
720 if changed_comment_content(&snippet, &new) {
721 // We missed some comments
722 // Keep previous formatting if it satisfies the constrains
723 wrap_str(snippet, context.config.max_width(), shape)
729 /// Return true if the two strings of code have the same payload of comments.
730 /// The payload of comments is everything in the string except:
731 /// - actual code (not comments)
732 /// - comment start/end marks
734 /// - '*' at the beginning of lines in block comments
735 fn changed_comment_content(orig: &str, new: &str) -> bool {
736 // Cannot write this as a fn since we cannot return types containing closures
737 let code_comment_content = |code| {
738 let slices = UngroupedCommentCodeSlices::new(code);
740 .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
741 .flat_map(|(_, _, s)| CommentReducer::new(s))
743 let res = code_comment_content(orig).ne(code_comment_content(new));
745 "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
749 code_comment_content(orig).collect::<String>(),
750 code_comment_content(new).collect::<String>()
756 /// Iterator over the 'payload' characters of a comment.
757 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
758 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
760 struct CommentReducer<'a> {
763 iter: std::str::Chars<'a>,
766 impl<'a> CommentReducer<'a> {
767 fn new(comment: &'a str) -> CommentReducer<'a> {
768 let is_block = comment.starts_with("/*");
769 let comment = remove_comment_header(comment);
772 at_start_line: false, // There are no supplementary '*' on the first line
773 iter: comment.chars(),
778 impl<'a> Iterator for CommentReducer<'a> {
780 fn next(&mut self) -> Option<Self::Item> {
782 let mut c = try_opt!(self.iter.next());
783 if self.is_block && self.at_start_line {
784 while c.is_whitespace() {
785 c = try_opt!(self.iter.next());
787 // Ignore leading '*'
789 c = try_opt!(self.iter.next());
793 self.at_start_line = true;
796 if !c.is_whitespace() {
804 fn remove_comment_header(comment: &str) -> &str {
805 if comment.starts_with("///") || comment.starts_with("//!") {
807 } else if comment.starts_with("//") {
809 } else if (comment.starts_with("/**") && !comment.starts_with("/**/")) ||
810 comment.starts_with("/*!")
812 &comment[3..comment.len() - 2]
815 comment.starts_with("/*"),
816 format!("string '{}' is not a comment", comment)
818 &comment[2..comment.len() - 2]
824 use super::{CharClasses, CodeCharKind, FullCodeCharKind, contains_comment, rewrite_comment,
825 FindUncommented, CommentCodeSlices};
830 let mut iter = CharClasses::new("//\n\n".chars());
832 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
833 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
834 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
835 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
836 assert_eq!(None, iter.next());
840 fn comment_code_slices() {
841 let input = "code(); /* test */ 1 + 1";
842 let mut iter = CommentCodeSlices::new(input);
844 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
846 (CodeCharKind::Comment, 8, "/* test */"),
849 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
850 assert_eq!(None, iter.next());
854 fn comment_code_slices_two() {
855 let input = "// comment\n test();";
856 let mut iter = CommentCodeSlices::new(input);
858 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
860 (CodeCharKind::Comment, 0, "// comment\n"),
864 (CodeCharKind::Normal, 11, " test();"),
867 assert_eq!(None, iter.next());
871 fn comment_code_slices_three() {
872 let input = "1 // comment\n // comment2\n\n";
873 let mut iter = CommentCodeSlices::new(input);
875 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
877 (CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
880 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
881 assert_eq!(None, iter.next());
885 #[cfg_attr(rustfmt, rustfmt_skip)]
886 fn format_comments() {
887 let mut config: ::config::Config = Default::default();
888 config.set().wrap_comments(true);
889 config.set().normalize_comments(true);
891 let comment = rewrite_comment(" //test",
893 Shape::legacy(100, Indent::new(0, 100)),
895 assert_eq!("/* test */", comment);
897 let comment = rewrite_comment("// comment on a",
899 Shape::legacy(10, Indent::empty()),
901 assert_eq!("// comment\n// on a", comment);
903 let comment = rewrite_comment("// A multi line comment\n // between args.",
905 Shape::legacy(60, Indent::new(0, 12)),
907 assert_eq!("// A multi line comment\n // between args.", comment);
909 let input = "// comment";
912 let comment = rewrite_comment(input,
914 Shape::legacy(9, Indent::new(0, 69)),
916 assert_eq!(expected, comment);
918 let comment = rewrite_comment("/* trimmed */",
920 Shape::legacy(100, Indent::new(0, 100)),
922 assert_eq!("/* trimmed */", comment);
925 // This is probably intended to be a non-test fn, but it is not used. I'm
926 // keeping it around unless it helps us test stuff.
927 fn uncommented(text: &str) -> String {
928 CharClasses::new(text.chars())
929 .filter_map(|(s, c)| match s {
930 FullCodeCharKind::Normal => Some(c),
937 fn test_uncommented() {
938 assert_eq!(&uncommented("abc/*...*/"), "abc");
940 &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
943 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
947 fn test_contains_comment() {
948 assert_eq!(contains_comment("abc"), false);
949 assert_eq!(contains_comment("abc // qsdf"), true);
950 assert_eq!(contains_comment("abc /* kqsdf"), true);
951 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
955 fn test_find_uncommented() {
956 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
957 assert_eq!(expected, haystack.find_uncommented(needle));
960 check("/*/ */test", "test", Some(6));
961 check("//test\ntest", "test", Some(7));
962 check("/* comment only */", "whatever", None);
964 "/* comment */ some text /* more commentary */ result",
968 check("sup // sup", "p", Some(2));
969 check("sup", "x", None);
970 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
971 check("/*sup yo? \n sup*/ sup", "p", Some(20));
972 check("hel/*lohello*/lo", "hello", None);
973 check("acb", "ab", None);
974 check(",/*A*/ ", ",", Some(0));
975 check("abc", "abc", Some(0));
976 check("/* abc */", "abc", None);
977 check("/**/abc/* */", "abc", Some(4));
978 check("\"/* abc */\"", "abc", Some(4));
979 check("\"/* abc", "abc", Some(4));