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| {
48 first_line.find(' ').map_or(
50 |space_index| &first_line[0..space_index + 1],
55 impl<'a> CommentStyle<'a> {
56 pub fn opener(&self) -> &'a str {
58 CommentStyle::DoubleSlash => "// ",
59 CommentStyle::TripleSlash => "/// ",
60 CommentStyle::Doc => "//! ",
61 CommentStyle::SingleBullet => "/* ",
62 CommentStyle::DoubleBullet => "/** ",
63 CommentStyle::Exclamation => "/*! ",
64 CommentStyle::Custom(opener) => opener,
68 pub fn closer(&self) -> &'a str {
70 CommentStyle::DoubleSlash |
71 CommentStyle::TripleSlash |
72 CommentStyle::Custom(..) |
73 CommentStyle::Doc => "",
74 CommentStyle::DoubleBullet => " **/",
75 CommentStyle::SingleBullet |
76 CommentStyle::Exclamation => " */",
80 pub fn line_start(&self) -> &'a str {
82 CommentStyle::DoubleSlash => "// ",
83 CommentStyle::TripleSlash => "/// ",
84 CommentStyle::Doc => "//! ",
85 CommentStyle::SingleBullet |
86 CommentStyle::Exclamation => " * ",
87 CommentStyle::DoubleBullet => " ** ",
88 CommentStyle::Custom(opener) => opener,
92 pub fn to_str_tuplet(&self) -> (&'a str, &'a str, &'a str) {
93 (self.opener(), self.closer(), self.line_start())
96 pub fn line_with_same_comment_style(&self, line: &str, normalize_comments: bool) -> bool {
98 CommentStyle::DoubleSlash |
99 CommentStyle::TripleSlash |
100 CommentStyle::Doc => {
101 line.trim_left().starts_with(self.line_start().trim_left()) ||
102 comment_style(line, normalize_comments) == *self
104 CommentStyle::DoubleBullet |
105 CommentStyle::SingleBullet |
106 CommentStyle::Exclamation => {
107 line.trim_left().starts_with(self.closer().trim_left()) ||
108 line.trim_left().starts_with(self.line_start().trim_left()) ||
109 comment_style(line, normalize_comments) == *self
111 CommentStyle::Custom(opener) => line.trim_left().starts_with(opener.trim_right()),
116 fn comment_style(orig: &str, normalize_comments: bool) -> CommentStyle {
117 if !normalize_comments {
118 if orig.starts_with("/**") && !orig.starts_with("/**/") {
119 CommentStyle::DoubleBullet
120 } else if orig.starts_with("/*!") {
121 CommentStyle::Exclamation
122 } else if orig.starts_with("/*") {
123 CommentStyle::SingleBullet
124 } else if orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/') {
125 CommentStyle::TripleSlash
126 } else if orig.starts_with("//!") {
128 } else if is_custom_comment(orig) {
129 CommentStyle::Custom(custom_opener(orig))
131 CommentStyle::DoubleSlash
133 } else if (orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/')) ||
134 (orig.starts_with("/**") && !orig.starts_with("/**/"))
136 CommentStyle::TripleSlash
137 } else if orig.starts_with("//!") || orig.starts_with("/*!") {
139 } else if is_custom_comment(orig) {
140 CommentStyle::Custom(custom_opener(orig))
142 CommentStyle::DoubleSlash
146 pub fn rewrite_comment(
151 ) -> Option<String> {
152 // If there are lines without a starting sigil, we won't format them correctly
153 // so in that case we won't even re-align (if !config.normalize_comments()) and
154 // we should stop now.
155 let num_bare_lines = orig.lines()
156 .map(|line| line.trim())
158 !(l.starts_with('*') || l.starts_with("//") || l.starts_with("/*"))
161 if num_bare_lines > 0 && !config.normalize_comments() {
162 return Some(orig.to_owned());
164 if !config.normalize_comments() && !config.wrap_comments() {
165 return light_rewrite_comment(orig, shape.indent, config);
168 identify_comment(orig, block_style, shape, config)
176 ) -> Option<String> {
177 let style = comment_style(orig, false);
178 let first_group = orig.lines()
179 .take_while(|l| style.line_with_same_comment_style(l, false))
182 let rest = orig.lines()
183 .skip(first_group.lines().count())
187 let first_group_str = try_opt!(rewrite_comment_inner(
195 Some(first_group_str)
197 identify_comment(&rest, block_style, shape, config).map(|rest_str| {
201 shape.indent.to_string(config),
208 fn rewrite_comment_inner(
214 ) -> Option<String> {
215 let (opener, closer, line_start) = if block_style {
216 CommentStyle::SingleBullet.to_str_tuplet()
218 comment_style(orig, config.normalize_comments()).to_str_tuplet()
221 let max_chars = shape
223 .checked_sub(closer.len() + opener.len())
225 let indent_str = shape.indent.to_string(config);
226 let fmt = StringFormat {
229 line_start: line_start,
231 shape: Shape::legacy(max_chars, shape.indent + (opener.len() - line_start.len())),
236 let line_breaks = orig.trim_right().chars().filter(|&c| c == '\n').count();
237 let lines = orig.lines()
239 .map(|(i, mut line)| {
242 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
243 line = &line[..(line.len() - 2)].trim_right();
248 .map(|s| left_trim_comment_line(s, &style))
249 .map(|line| if orig.starts_with("/*") && line_breaks == 0 {
255 let mut result = opener.to_owned();
257 if result == opener {
263 result.push_str(&indent_str);
264 result.push_str(line_start);
267 if config.wrap_comments() && line.len() > max_chars {
268 let rewrite = rewrite_string(line, &fmt).unwrap_or(line.to_owned());
269 result.push_str(&rewrite);
271 if line.is_empty() && result.ends_with(' ') {
272 // Remove space if this is an empty comment or a doc comment.
275 result.push_str(line);
279 result.push_str(closer);
280 if result == opener && result.ends_with(' ') {
288 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
289 fn light_rewrite_comment(orig: &str, offset: Indent, config: &Config) -> Option<String> {
290 let lines: Vec<&str> = orig.lines()
292 // This is basically just l.trim(), but in the case that a line starts
293 // with `*` we want to leave one space before it, so it aligns with the
295 let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
296 if let Some(fnw) = first_non_whitespace {
297 if l.as_bytes()[fnw] == '*' as u8 && fnw > 0 {
307 Some(lines.join(&format!("\n{}", offset.to_string(config))))
310 /// Trims comment characters and possibly a single space from the left of a string.
311 /// Does not trim all whitespace.
312 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle) -> &'a str {
313 if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") ||
314 line.starts_with("/** ")
317 } else if let &CommentStyle::Custom(opener) = style {
318 if line.starts_with(opener) {
319 &line[opener.len()..]
321 &line[opener.trim_right().len()..]
323 } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!") ||
324 line.starts_with("///") ||
325 line.starts_with("** ") || line.starts_with("/*!") ||
326 (line.starts_with("/**") && !line.starts_with("/**/"))
329 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") ||
330 line.starts_with("**")
333 } else if line.starts_with('*') {
340 pub trait FindUncommented {
341 fn find_uncommented(&self, pat: &str) -> Option<usize>;
344 impl FindUncommented for str {
345 fn find_uncommented(&self, pat: &str) -> Option<usize> {
346 let mut needle_iter = pat.chars();
347 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
348 match needle_iter.next() {
350 return Some(i - pat.len());
354 FullCodeCharKind::Normal if b == c => {}
356 needle_iter = pat.chars();
363 // Handle case where the pattern is a suffix of the search string
364 match needle_iter.next() {
366 None => Some(self.len() - pat.len()),
371 // Returns the first byte position after the first comment. The given string
372 // is expected to be prefixed by a comment, including delimiters.
373 // Good: "/* /* inner */ outer */ code();"
374 // Bad: "code(); // hello\n world!"
375 pub fn find_comment_end(s: &str) -> Option<usize> {
376 let mut iter = CharClasses::new(s.char_indices());
377 for (kind, (i, _c)) in &mut iter {
378 if kind == FullCodeCharKind::Normal {
383 // Handle case where the comment ends at the end of s.
384 if iter.status == CharClassesStatus::Normal {
391 /// Returns true if text contains any comment.
392 pub fn contains_comment(text: &str) -> bool {
393 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
396 struct CharClasses<T>
401 base: iter::Peekable<T>,
402 status: CharClassesStatus,
406 fn get_char(&self) -> char;
409 impl RichChar for char {
410 fn get_char(&self) -> char {
415 impl RichChar for (usize, char) {
416 fn get_char(&self) -> char {
421 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
422 enum CharClassesStatus {
428 // The u32 is the nesting deepness of the comment
430 // Status when the '/' has been consumed, but not yet the '*', deepness is
431 // the new deepness (after the comment opening).
432 BlockCommentOpening(u32),
433 // Status when the '*' has been consumed, but not yet the '/', deepness is
434 // the new deepness (after the comment closing).
435 BlockCommentClosing(u32),
439 /// Distinguish between functional part of code and comments
440 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
441 pub enum CodeCharKind {
446 /// Distinguish between functional part of code and comments,
447 /// describing opening and closing of comments for ease when chunking
448 /// code from tagged characters
449 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
450 enum FullCodeCharKind {
452 /// The first character of a comment, there is only one for a comment (always '/')
454 /// Any character inside a comment including the second character of comment
455 /// marks ("//", "/*")
457 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
461 impl FullCodeCharKind {
462 fn is_comment(&self) -> bool {
464 FullCodeCharKind::Normal => false,
465 FullCodeCharKind::StartComment |
466 FullCodeCharKind::InComment |
467 FullCodeCharKind::EndComment => true,
471 fn to_codecharkind(&self) -> CodeCharKind {
472 if self.is_comment() {
473 CodeCharKind::Comment
480 impl<T> CharClasses<T>
485 fn new(base: T) -> CharClasses<T> {
487 base: base.peekable(),
488 status: CharClassesStatus::Normal,
493 impl<T> Iterator for CharClasses<T>
498 type Item = (FullCodeCharKind, T::Item);
500 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
501 let item = try_opt!(self.base.next());
502 let chr = item.get_char();
503 self.status = match self.status {
504 CharClassesStatus::LitString => {
506 '"' => CharClassesStatus::Normal,
507 '\\' => CharClassesStatus::LitStringEscape,
508 _ => CharClassesStatus::LitString,
511 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
512 CharClassesStatus::LitChar => {
514 '\\' => CharClassesStatus::LitCharEscape,
515 '\'' => CharClassesStatus::Normal,
516 _ => CharClassesStatus::LitChar,
519 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
520 CharClassesStatus::Normal => {
522 '"' => CharClassesStatus::LitString,
523 '\'' => CharClassesStatus::LitChar,
525 match self.base.peek() {
526 Some(next) if next.get_char() == '*' => {
527 self.status = CharClassesStatus::BlockCommentOpening(1);
528 return Some((FullCodeCharKind::StartComment, item));
530 Some(next) if next.get_char() == '/' => {
531 self.status = CharClassesStatus::LineComment;
532 return Some((FullCodeCharKind::StartComment, item));
534 _ => CharClassesStatus::Normal,
537 _ => CharClassesStatus::Normal,
540 CharClassesStatus::BlockComment(deepness) => {
541 assert!(deepness != 0);
542 self.status = match self.base.peek() {
543 Some(next) if next.get_char() == '/' && chr == '*' => {
544 CharClassesStatus::BlockCommentClosing(deepness - 1)
546 Some(next) if next.get_char() == '*' && chr == '/' => {
547 CharClassesStatus::BlockCommentOpening(deepness + 1)
549 _ => CharClassesStatus::BlockComment(deepness),
551 return Some((FullCodeCharKind::InComment, item));
553 CharClassesStatus::BlockCommentOpening(deepness) => {
554 assert_eq!(chr, '*');
555 self.status = CharClassesStatus::BlockComment(deepness);
556 return Some((FullCodeCharKind::InComment, item));
558 CharClassesStatus::BlockCommentClosing(deepness) => {
559 assert_eq!(chr, '/');
561 self.status = CharClassesStatus::Normal;
562 return Some((FullCodeCharKind::EndComment, item));
564 self.status = CharClassesStatus::BlockComment(deepness);
565 return Some((FullCodeCharKind::InComment, item));
568 CharClassesStatus::LineComment => {
571 self.status = CharClassesStatus::Normal;
572 return Some((FullCodeCharKind::EndComment, item));
575 self.status = CharClassesStatus::LineComment;
576 return Some((FullCodeCharKind::InComment, item));
581 Some((FullCodeCharKind::Normal, item))
585 /// Iterator over functional and commented parts of a string. Any part of a string is either
586 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
587 /// comments is functional code. Line comments contain their ending newlines.
588 struct UngroupedCommentCodeSlices<'a> {
590 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
593 impl<'a> UngroupedCommentCodeSlices<'a> {
594 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
595 UngroupedCommentCodeSlices {
597 iter: CharClasses::new(code.char_indices()).peekable(),
602 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
603 type Item = (CodeCharKind, usize, &'a str);
605 fn next(&mut self) -> Option<Self::Item> {
606 let (kind, (start_idx, _)) = try_opt!(self.iter.next());
608 FullCodeCharKind::Normal => {
609 // Consume all the Normal code
610 while let Some(&(FullCodeCharKind::Normal, (_, _))) = self.iter.peek() {
611 let _ = self.iter.next();
614 FullCodeCharKind::StartComment => {
615 // Consume the whole comment
616 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
620 let slice = match self.iter.peek() {
621 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
622 None => &self.slice[start_idx..],
625 if kind.is_comment() {
626 CodeCharKind::Comment
639 /// Iterator over an alternating sequence of functional and commented parts of
640 /// a string. The first item is always a, possibly zero length, subslice of
641 /// functional text. Line style comments contain their ending newlines.
642 pub struct CommentCodeSlices<'a> {
644 last_slice_kind: CodeCharKind,
645 last_slice_end: usize,
648 impl<'a> CommentCodeSlices<'a> {
649 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
652 last_slice_kind: CodeCharKind::Comment,
658 impl<'a> Iterator for CommentCodeSlices<'a> {
659 type Item = (CodeCharKind, usize, &'a str);
661 fn next(&mut self) -> Option<Self::Item> {
662 if self.last_slice_end == self.slice.len() {
666 let mut sub_slice_end = self.last_slice_end;
667 let mut first_whitespace = None;
668 let subslice = &self.slice[self.last_slice_end..];
669 let mut iter = CharClasses::new(subslice.char_indices());
671 for (kind, (i, c)) in &mut iter {
672 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
673 &subslice[..2] == "//" &&
674 [' ', '\t'].contains(&c);
676 if is_comment_connector && first_whitespace.is_none() {
677 first_whitespace = Some(i);
680 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
681 let last_index = match first_whitespace {
685 sub_slice_end = self.last_slice_end + last_index;
689 if !is_comment_connector {
690 first_whitespace = None;
694 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
695 // This was the last subslice.
696 sub_slice_end = match first_whitespace {
697 Some(i) => self.last_slice_end + i,
698 None => self.slice.len(),
702 let kind = match self.last_slice_kind {
703 CodeCharKind::Comment => CodeCharKind::Normal,
704 CodeCharKind::Normal => CodeCharKind::Comment,
709 &self.slice[self.last_slice_end..sub_slice_end],
711 self.last_slice_end = sub_slice_end;
712 self.last_slice_kind = kind;
718 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
719 /// (if it fits in the width/offset, else return None), else return `new`
720 pub fn recover_comment_removed(
723 context: &RewriteContext,
725 ) -> Option<String> {
726 let snippet = context.snippet(span);
727 if changed_comment_content(&snippet, &new) {
728 // We missed some comments
729 // Keep previous formatting if it satisfies the constrains
730 wrap_str(snippet, context.config.max_width(), shape)
736 /// Return true if the two strings of code have the same payload of comments.
737 /// The payload of comments is everything in the string except:
738 /// - actual code (not comments)
739 /// - comment start/end marks
741 /// - '*' at the beginning of lines in block comments
742 fn changed_comment_content(orig: &str, new: &str) -> bool {
743 // Cannot write this as a fn since we cannot return types containing closures
744 let code_comment_content = |code| {
745 let slices = UngroupedCommentCodeSlices::new(code);
747 .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
748 .flat_map(|(_, _, s)| CommentReducer::new(s))
750 let res = code_comment_content(orig).ne(code_comment_content(new));
752 "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
756 code_comment_content(orig).collect::<String>(),
757 code_comment_content(new).collect::<String>()
763 /// Iterator over the 'payload' characters of a comment.
764 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
765 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
767 struct CommentReducer<'a> {
770 iter: std::str::Chars<'a>,
773 impl<'a> CommentReducer<'a> {
774 fn new(comment: &'a str) -> CommentReducer<'a> {
775 let is_block = comment.starts_with("/*");
776 let comment = remove_comment_header(comment);
779 at_start_line: false, // There are no supplementary '*' on the first line
780 iter: comment.chars(),
785 impl<'a> Iterator for CommentReducer<'a> {
787 fn next(&mut self) -> Option<Self::Item> {
789 let mut c = try_opt!(self.iter.next());
790 if self.is_block && self.at_start_line {
791 while c.is_whitespace() {
792 c = try_opt!(self.iter.next());
794 // Ignore leading '*'
796 c = try_opt!(self.iter.next());
800 self.at_start_line = true;
803 if !c.is_whitespace() {
811 fn remove_comment_header(comment: &str) -> &str {
812 if comment.starts_with("///") || comment.starts_with("//!") {
814 } else if comment.starts_with("//") {
816 } else if (comment.starts_with("/**") && !comment.starts_with("/**/")) ||
817 comment.starts_with("/*!")
819 &comment[3..comment.len() - 2]
822 comment.starts_with("/*"),
823 format!("string '{}' is not a comment", comment)
825 &comment[2..comment.len() - 2]
831 use super::{CharClasses, CodeCharKind, FullCodeCharKind, contains_comment, rewrite_comment,
832 FindUncommented, CommentCodeSlices};
837 let mut iter = CharClasses::new("//\n\n".chars());
839 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
840 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
841 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
842 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
843 assert_eq!(None, iter.next());
847 fn comment_code_slices() {
848 let input = "code(); /* test */ 1 + 1";
849 let mut iter = CommentCodeSlices::new(input);
851 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
853 (CodeCharKind::Comment, 8, "/* test */"),
856 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
857 assert_eq!(None, iter.next());
861 fn comment_code_slices_two() {
862 let input = "// comment\n test();";
863 let mut iter = CommentCodeSlices::new(input);
865 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
867 (CodeCharKind::Comment, 0, "// comment\n"),
871 (CodeCharKind::Normal, 11, " test();"),
874 assert_eq!(None, iter.next());
878 fn comment_code_slices_three() {
879 let input = "1 // comment\n // comment2\n\n";
880 let mut iter = CommentCodeSlices::new(input);
882 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
884 (CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
887 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
888 assert_eq!(None, iter.next());
892 #[cfg_attr(rustfmt, rustfmt_skip)]
893 fn format_comments() {
894 let mut config: ::config::Config = Default::default();
895 config.set().wrap_comments(true);
896 config.set().normalize_comments(true);
898 let comment = rewrite_comment(" //test",
900 Shape::legacy(100, Indent::new(0, 100)),
902 assert_eq!("/* test */", comment);
904 let comment = rewrite_comment("// comment on a",
906 Shape::legacy(10, Indent::empty()),
908 assert_eq!("// comment\n// on a", comment);
910 let comment = rewrite_comment("// A multi line comment\n // between args.",
912 Shape::legacy(60, Indent::new(0, 12)),
914 assert_eq!("// A multi line comment\n // between args.", comment);
916 let input = "// comment";
919 let comment = rewrite_comment(input,
921 Shape::legacy(9, Indent::new(0, 69)),
923 assert_eq!(expected, comment);
925 let comment = rewrite_comment("/* trimmed */",
927 Shape::legacy(100, Indent::new(0, 100)),
929 assert_eq!("/* trimmed */", comment);
932 // This is probably intended to be a non-test fn, but it is not used. I'm
933 // keeping it around unless it helps us test stuff.
934 fn uncommented(text: &str) -> String {
935 CharClasses::new(text.chars())
936 .filter_map(|(s, c)| match s {
937 FullCodeCharKind::Normal => Some(c),
944 fn test_uncommented() {
945 assert_eq!(&uncommented("abc/*...*/"), "abc");
947 &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
950 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
954 fn test_contains_comment() {
955 assert_eq!(contains_comment("abc"), false);
956 assert_eq!(contains_comment("abc // qsdf"), true);
957 assert_eq!(contains_comment("abc /* kqsdf"), true);
958 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
962 fn test_find_uncommented() {
963 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
964 assert_eq!(expected, haystack.find_uncommented(needle));
967 check("/*/ */test", "test", Some(6));
968 check("//test\ntest", "test", Some(7));
969 check("/* comment only */", "whatever", None);
971 "/* comment */ some text /* more commentary */ result",
975 check("sup // sup", "p", Some(2));
976 check("sup", "x", None);
977 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
978 check("/*sup yo? \n sup*/ sup", "p", Some(20));
979 check("hel/*lohello*/lo", "hello", None);
980 check("acb", "ab", None);
981 check(",/*A*/ ", ",", Some(0));
982 check("abc", "abc", Some(0));
983 check("/* abc */", "abc", None);
984 check("/**/abc/* */", "abc", Some(4));
985 check("\"/* abc */\"", "abc", Some(4));
986 check("\"/* abc", "abc", Some(4));