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::{rewrite_string, StringFormat};
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());
345 Some(c) => match kind {
346 FullCodeCharKind::Normal if b == c => {}
348 needle_iter = pat.chars();
354 // Handle case where the pattern is a suffix of the search string
355 match needle_iter.next() {
357 None => Some(self.len() - pat.len()),
362 // Returns the first byte position after the first comment. The given string
363 // is expected to be prefixed by a comment, including delimiters.
364 // Good: "/* /* inner */ outer */ code();"
365 // Bad: "code(); // hello\n world!"
366 pub fn find_comment_end(s: &str) -> Option<usize> {
367 let mut iter = CharClasses::new(s.char_indices());
368 for (kind, (i, _c)) in &mut iter {
369 if kind == FullCodeCharKind::Normal {
374 // Handle case where the comment ends at the end of s.
375 if iter.status == CharClassesStatus::Normal {
382 /// Returns true if text contains any comment.
383 pub fn contains_comment(text: &str) -> bool {
384 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
387 struct CharClasses<T>
392 base: iter::Peekable<T>,
393 status: CharClassesStatus,
397 fn get_char(&self) -> char;
400 impl RichChar for char {
401 fn get_char(&self) -> char {
406 impl RichChar for (usize, char) {
407 fn get_char(&self) -> char {
412 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
413 enum CharClassesStatus {
419 // The u32 is the nesting deepness of the comment
421 // Status when the '/' has been consumed, but not yet the '*', deepness is
422 // the new deepness (after the comment opening).
423 BlockCommentOpening(u32),
424 // Status when the '*' has been consumed, but not yet the '/', deepness is
425 // the new deepness (after the comment closing).
426 BlockCommentClosing(u32),
430 /// Distinguish between functional part of code and comments
431 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
432 pub enum CodeCharKind {
437 /// Distinguish between functional part of code and comments,
438 /// describing opening and closing of comments for ease when chunking
439 /// code from tagged characters
440 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
441 enum FullCodeCharKind {
443 /// The first character of a comment, there is only one for a comment (always '/')
445 /// Any character inside a comment including the second character of comment
446 /// marks ("//", "/*")
448 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
452 impl FullCodeCharKind {
453 fn is_comment(&self) -> bool {
455 FullCodeCharKind::Normal => false,
456 FullCodeCharKind::StartComment |
457 FullCodeCharKind::InComment |
458 FullCodeCharKind::EndComment => true,
462 fn to_codecharkind(&self) -> CodeCharKind {
463 if self.is_comment() {
464 CodeCharKind::Comment
471 impl<T> CharClasses<T>
476 fn new(base: T) -> CharClasses<T> {
478 base: base.peekable(),
479 status: CharClassesStatus::Normal,
484 impl<T> Iterator for CharClasses<T>
489 type Item = (FullCodeCharKind, T::Item);
491 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
492 let item = try_opt!(self.base.next());
493 let chr = item.get_char();
494 self.status = match self.status {
495 CharClassesStatus::LitString => match chr {
496 '"' => CharClassesStatus::Normal,
497 '\\' => CharClassesStatus::LitStringEscape,
498 _ => CharClassesStatus::LitString,
500 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
501 CharClassesStatus::LitChar => match chr {
502 '\\' => CharClassesStatus::LitCharEscape,
503 '\'' => CharClassesStatus::Normal,
504 _ => CharClassesStatus::LitChar,
506 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
507 CharClassesStatus::Normal => match chr {
508 '"' => CharClassesStatus::LitString,
509 '\'' => CharClassesStatus::LitChar,
510 '/' => match self.base.peek() {
511 Some(next) if next.get_char() == '*' => {
512 self.status = CharClassesStatus::BlockCommentOpening(1);
513 return Some((FullCodeCharKind::StartComment, item));
515 Some(next) if next.get_char() == '/' => {
516 self.status = CharClassesStatus::LineComment;
517 return Some((FullCodeCharKind::StartComment, item));
519 _ => CharClassesStatus::Normal,
521 _ => CharClassesStatus::Normal,
523 CharClassesStatus::BlockComment(deepness) => {
524 assert!(deepness != 0);
525 self.status = match self.base.peek() {
526 Some(next) if next.get_char() == '/' && chr == '*' => {
527 CharClassesStatus::BlockCommentClosing(deepness - 1)
529 Some(next) if next.get_char() == '*' && chr == '/' => {
530 CharClassesStatus::BlockCommentOpening(deepness + 1)
532 _ => CharClassesStatus::BlockComment(deepness),
534 return Some((FullCodeCharKind::InComment, item));
536 CharClassesStatus::BlockCommentOpening(deepness) => {
537 assert_eq!(chr, '*');
538 self.status = CharClassesStatus::BlockComment(deepness);
539 return Some((FullCodeCharKind::InComment, item));
541 CharClassesStatus::BlockCommentClosing(deepness) => {
542 assert_eq!(chr, '/');
544 self.status = CharClassesStatus::Normal;
545 return Some((FullCodeCharKind::EndComment, item));
547 self.status = CharClassesStatus::BlockComment(deepness);
548 return Some((FullCodeCharKind::InComment, item));
551 CharClassesStatus::LineComment => match chr {
553 self.status = CharClassesStatus::Normal;
554 return Some((FullCodeCharKind::EndComment, item));
557 self.status = CharClassesStatus::LineComment;
558 return Some((FullCodeCharKind::InComment, item));
562 Some((FullCodeCharKind::Normal, item))
566 /// Iterator over functional and commented parts of a string. Any part of a string is either
567 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
568 /// comments is functional code. Line comments contain their ending newlines.
569 struct UngroupedCommentCodeSlices<'a> {
571 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
574 impl<'a> UngroupedCommentCodeSlices<'a> {
575 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
576 UngroupedCommentCodeSlices {
578 iter: CharClasses::new(code.char_indices()).peekable(),
583 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
584 type Item = (CodeCharKind, usize, &'a str);
586 fn next(&mut self) -> Option<Self::Item> {
587 let (kind, (start_idx, _)) = try_opt!(self.iter.next());
589 FullCodeCharKind::Normal => {
590 // Consume all the Normal code
591 while let Some(&(FullCodeCharKind::Normal, (_, _))) = self.iter.peek() {
592 let _ = self.iter.next();
595 FullCodeCharKind::StartComment => {
596 // Consume the whole comment
597 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
601 let slice = match self.iter.peek() {
602 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
603 None => &self.slice[start_idx..],
606 if kind.is_comment() {
607 CodeCharKind::Comment
620 /// Iterator over an alternating sequence of functional and commented parts of
621 /// a string. The first item is always a, possibly zero length, subslice of
622 /// functional text. Line style comments contain their ending newlines.
623 pub struct CommentCodeSlices<'a> {
625 last_slice_kind: CodeCharKind,
626 last_slice_end: usize,
629 impl<'a> CommentCodeSlices<'a> {
630 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
633 last_slice_kind: CodeCharKind::Comment,
639 impl<'a> Iterator for CommentCodeSlices<'a> {
640 type Item = (CodeCharKind, usize, &'a str);
642 fn next(&mut self) -> Option<Self::Item> {
643 if self.last_slice_end == self.slice.len() {
647 let mut sub_slice_end = self.last_slice_end;
648 let mut first_whitespace = None;
649 let subslice = &self.slice[self.last_slice_end..];
650 let mut iter = CharClasses::new(subslice.char_indices());
652 for (kind, (i, c)) in &mut iter {
653 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
654 &subslice[..2] == "//" &&
655 [' ', '\t'].contains(&c);
657 if is_comment_connector && first_whitespace.is_none() {
658 first_whitespace = Some(i);
661 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
662 let last_index = match first_whitespace {
666 sub_slice_end = self.last_slice_end + last_index;
670 if !is_comment_connector {
671 first_whitespace = None;
675 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
676 // This was the last subslice.
677 sub_slice_end = match first_whitespace {
678 Some(i) => self.last_slice_end + i,
679 None => self.slice.len(),
683 let kind = match self.last_slice_kind {
684 CodeCharKind::Comment => CodeCharKind::Normal,
685 CodeCharKind::Normal => CodeCharKind::Comment,
690 &self.slice[self.last_slice_end..sub_slice_end],
692 self.last_slice_end = sub_slice_end;
693 self.last_slice_kind = kind;
699 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
700 /// (if it fits in the width/offset, else return None), else return `new`
701 pub fn recover_comment_removed(
704 context: &RewriteContext,
706 ) -> Option<String> {
707 let snippet = context.snippet(span);
708 if changed_comment_content(&snippet, &new) {
709 // We missed some comments
710 // Keep previous formatting if it satisfies the constrains
711 wrap_str(snippet, context.config.max_width(), shape)
717 /// Return true if the two strings of code have the same payload of comments.
718 /// The payload of comments is everything in the string except:
719 /// - actual code (not comments)
720 /// - comment start/end marks
722 /// - '*' at the beginning of lines in block comments
723 fn changed_comment_content(orig: &str, new: &str) -> bool {
724 // Cannot write this as a fn since we cannot return types containing closures
725 let code_comment_content = |code| {
726 let slices = UngroupedCommentCodeSlices::new(code);
728 .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
729 .flat_map(|(_, _, s)| CommentReducer::new(s))
731 let res = code_comment_content(orig).ne(code_comment_content(new));
733 "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
737 code_comment_content(orig).collect::<String>(),
738 code_comment_content(new).collect::<String>()
744 /// Iterator over the 'payload' characters of a comment.
745 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
746 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
748 struct CommentReducer<'a> {
751 iter: std::str::Chars<'a>,
754 impl<'a> CommentReducer<'a> {
755 fn new(comment: &'a str) -> CommentReducer<'a> {
756 let is_block = comment.starts_with("/*");
757 let comment = remove_comment_header(comment);
760 at_start_line: false, // There are no supplementary '*' on the first line
761 iter: comment.chars(),
766 impl<'a> Iterator for CommentReducer<'a> {
768 fn next(&mut self) -> Option<Self::Item> {
770 let mut c = try_opt!(self.iter.next());
771 if self.is_block && self.at_start_line {
772 while c.is_whitespace() {
773 c = try_opt!(self.iter.next());
775 // Ignore leading '*'
777 c = try_opt!(self.iter.next());
781 self.at_start_line = true;
784 if !c.is_whitespace() {
792 fn remove_comment_header(comment: &str) -> &str {
793 if comment.starts_with("///") || comment.starts_with("//!") {
795 } else if comment.starts_with("//") {
797 } else if (comment.starts_with("/**") && !comment.starts_with("/**/")) ||
798 comment.starts_with("/*!")
800 &comment[3..comment.len() - 2]
803 comment.starts_with("/*"),
804 format!("string '{}' is not a comment", comment)
806 &comment[2..comment.len() - 2]
812 use super::{contains_comment, rewrite_comment, CharClasses, CodeCharKind, CommentCodeSlices,
813 FindUncommented, FullCodeCharKind};
818 let mut iter = CharClasses::new("//\n\n".chars());
820 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
821 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
822 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
823 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
824 assert_eq!(None, iter.next());
828 fn comment_code_slices() {
829 let input = "code(); /* test */ 1 + 1";
830 let mut iter = CommentCodeSlices::new(input);
832 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
834 (CodeCharKind::Comment, 8, "/* test */"),
837 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
838 assert_eq!(None, iter.next());
842 fn comment_code_slices_two() {
843 let input = "// comment\n test();";
844 let mut iter = CommentCodeSlices::new(input);
846 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
848 (CodeCharKind::Comment, 0, "// comment\n"),
852 (CodeCharKind::Normal, 11, " test();"),
855 assert_eq!(None, iter.next());
859 fn comment_code_slices_three() {
860 let input = "1 // comment\n // comment2\n\n";
861 let mut iter = CommentCodeSlices::new(input);
863 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
865 (CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
868 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
869 assert_eq!(None, iter.next());
873 #[cfg_attr(rustfmt, rustfmt_skip)]
874 fn format_comments() {
875 let mut config: ::config::Config = Default::default();
876 config.set().wrap_comments(true);
877 config.set().normalize_comments(true);
879 let comment = rewrite_comment(" //test",
881 Shape::legacy(100, Indent::new(0, 100)),
883 assert_eq!("/* test */", comment);
885 let comment = rewrite_comment("// comment on a",
887 Shape::legacy(10, Indent::empty()),
889 assert_eq!("// comment\n// on a", comment);
891 let comment = rewrite_comment("// A multi line comment\n // between args.",
893 Shape::legacy(60, Indent::new(0, 12)),
895 assert_eq!("// A multi line comment\n // between args.", comment);
897 let input = "// comment";
900 let comment = rewrite_comment(input,
902 Shape::legacy(9, Indent::new(0, 69)),
904 assert_eq!(expected, comment);
906 let comment = rewrite_comment("/* trimmed */",
908 Shape::legacy(100, Indent::new(0, 100)),
910 assert_eq!("/* trimmed */", comment);
913 // This is probably intended to be a non-test fn, but it is not used. I'm
914 // keeping it around unless it helps us test stuff.
915 fn uncommented(text: &str) -> String {
916 CharClasses::new(text.chars())
917 .filter_map(|(s, c)| match s {
918 FullCodeCharKind::Normal => Some(c),
925 fn test_uncommented() {
926 assert_eq!(&uncommented("abc/*...*/"), "abc");
928 &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
931 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
935 fn test_contains_comment() {
936 assert_eq!(contains_comment("abc"), false);
937 assert_eq!(contains_comment("abc // qsdf"), true);
938 assert_eq!(contains_comment("abc /* kqsdf"), true);
939 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
943 fn test_find_uncommented() {
944 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
945 assert_eq!(expected, haystack.find_uncommented(needle));
948 check("/*/ */test", "test", Some(6));
949 check("//test\ntest", "test", Some(7));
950 check("/* comment only */", "whatever", None);
952 "/* comment */ some text /* more commentary */ result",
956 check("sup // sup", "p", Some(2));
957 check("sup", "x", None);
958 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
959 check("/*sup yo? \n sup*/ sup", "p", Some(20));
960 check("hel/*lohello*/lo", "hello", None);
961 check("acb", "ab", None);
962 check(",/*A*/ ", ",", Some(0));
963 check("abc", "abc", Some(0));
964 check("/* abc */", "abc", None);
965 check("/**/abc/* */", "abc", Some(4));
966 check("\"/* abc */\"", "abc", Some(4));
967 check("\"/* abc", "abc", Some(4));