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(first_line, |space_index| {
49 &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 |
75 CommentStyle::Exclamation => " */",
79 pub fn line_start(&self) -> &'a str {
81 CommentStyle::DoubleSlash => "// ",
82 CommentStyle::TripleSlash => "/// ",
83 CommentStyle::Doc => "//! ",
84 CommentStyle::SingleBullet |
85 CommentStyle::Exclamation => " * ",
86 CommentStyle::DoubleBullet => " ** ",
87 CommentStyle::Custom(opener) => opener,
91 pub fn to_str_tuplet(&self) -> (&'a str, &'a str, &'a str) {
92 (self.opener(), self.closer(), self.line_start())
95 pub fn line_with_same_comment_style(&self, line: &str, normalize_comments: bool) -> bool {
97 CommentStyle::DoubleSlash |
98 CommentStyle::TripleSlash |
99 CommentStyle::Doc => {
100 line.trim_left().starts_with(self.line_start().trim_left()) ||
101 comment_style(line, normalize_comments) == *self
103 CommentStyle::DoubleBullet |
104 CommentStyle::SingleBullet |
105 CommentStyle::Exclamation => {
106 line.trim_left().starts_with(self.closer().trim_left()) ||
107 line.trim_left().starts_with(self.line_start().trim_left()) ||
108 comment_style(line, normalize_comments) == *self
110 CommentStyle::Custom(opener) => line.trim_left().starts_with(opener.trim_right()),
115 fn comment_style(orig: &str, normalize_comments: bool) -> CommentStyle {
116 if !normalize_comments {
117 if orig.starts_with("/**") && !orig.starts_with("/**/") {
118 CommentStyle::DoubleBullet
119 } else if orig.starts_with("/*!") {
120 CommentStyle::Exclamation
121 } else if orig.starts_with("/*") {
122 CommentStyle::SingleBullet
123 } else if orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/') {
124 CommentStyle::TripleSlash
125 } else if orig.starts_with("//!") {
127 } else if is_custom_comment(orig) {
128 CommentStyle::Custom(custom_opener(orig))
130 CommentStyle::DoubleSlash
132 } else if (orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/')) ||
133 (orig.starts_with("/**") && !orig.starts_with("/**/"))
135 CommentStyle::TripleSlash
136 } else if orig.starts_with("//!") || orig.starts_with("/*!") {
138 } else if is_custom_comment(orig) {
139 CommentStyle::Custom(custom_opener(orig))
141 CommentStyle::DoubleSlash
145 pub fn rewrite_comment(
150 ) -> Option<String> {
151 // If there are lines without a starting sigil, we won't format them correctly
152 // so in that case we won't even re-align (if !config.normalize_comments()) and
153 // we should stop now.
154 let num_bare_lines = orig.lines()
155 .map(|line| line.trim())
157 !(l.starts_with('*') || l.starts_with("//") || l.starts_with("/*"))
160 if num_bare_lines > 0 && !config.normalize_comments() {
161 return Some(orig.to_owned());
163 if !config.normalize_comments() && !config.wrap_comments() {
164 return light_rewrite_comment(orig, shape.indent, config);
167 identify_comment(orig, block_style, shape, config)
175 ) -> Option<String> {
176 let style = comment_style(orig, false);
177 let first_group = orig.lines()
178 .take_while(|l| style.line_with_same_comment_style(l, false))
181 let rest = orig.lines()
182 .skip(first_group.lines().count())
186 let first_group_str = try_opt!(rewrite_comment_inner(
194 Some(first_group_str)
196 identify_comment(&rest, block_style, shape, config).map(|rest_str| {
200 shape.indent.to_string(config),
207 fn rewrite_comment_inner(
213 ) -> Option<String> {
214 let (opener, closer, line_start) = if block_style {
215 CommentStyle::SingleBullet.to_str_tuplet()
217 comment_style(orig, config.normalize_comments()).to_str_tuplet()
220 let max_chars = shape
222 .checked_sub(closer.len() + opener.len())
224 let indent_str = shape.indent.to_string(config);
225 let fmt = StringFormat {
228 line_start: line_start,
230 shape: Shape::legacy(max_chars, shape.indent + (opener.len() - line_start.len())),
235 let line_breaks = orig.trim_right().chars().filter(|&c| c == '\n').count();
236 let lines = orig.lines()
238 .map(|(i, mut line)| {
241 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
242 line = &line[..(line.len() - 2)].trim_right();
247 .map(|s| left_trim_comment_line(s, &style))
248 .map(|line| if orig.starts_with("/*") && line_breaks == 0 {
254 let mut result = opener.to_owned();
256 if result == opener {
262 result.push_str(&indent_str);
263 result.push_str(line_start);
266 if config.wrap_comments() && line.len() > max_chars {
267 let rewrite = rewrite_string(line, &fmt).unwrap_or(line.to_owned());
268 result.push_str(&rewrite);
270 if line.is_empty() && result.ends_with(' ') {
271 // Remove space if this is an empty comment or a doc comment.
274 result.push_str(line);
278 result.push_str(closer);
279 if result == opener && result.ends_with(' ') {
287 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
288 fn light_rewrite_comment(orig: &str, offset: Indent, config: &Config) -> Option<String> {
289 let lines: Vec<&str> = orig.lines()
291 // This is basically just l.trim(), but in the case that a line starts
292 // with `*` we want to leave one space before it, so it aligns with the
294 let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
295 if let Some(fnw) = first_non_whitespace {
296 if l.as_bytes()[fnw] == '*' as u8 && fnw > 0 {
306 Some(lines.join(&format!("\n{}", offset.to_string(config))))
309 /// Trims comment characters and possibly a single space from the left of a string.
310 /// Does not trim all whitespace.
311 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle) -> &'a str {
312 if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") ||
313 line.starts_with("/** ")
316 } else if let &CommentStyle::Custom(opener) = style {
317 if line.starts_with(opener) {
318 &line[opener.len()..]
320 &line[opener.trim_right().len()..]
322 } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!") ||
323 line.starts_with("///") ||
324 line.starts_with("** ") || line.starts_with("/*!") ||
325 (line.starts_with("/**") && !line.starts_with("/**/"))
328 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") ||
329 line.starts_with("**")
332 } else if line.starts_with('*') {
339 pub trait FindUncommented {
340 fn find_uncommented(&self, pat: &str) -> Option<usize>;
343 impl FindUncommented for str {
344 fn find_uncommented(&self, pat: &str) -> Option<usize> {
345 let mut needle_iter = pat.chars();
346 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
347 match needle_iter.next() {
349 return Some(i - pat.len());
353 FullCodeCharKind::Normal if b == c => {}
355 needle_iter = pat.chars();
362 // Handle case where the pattern is a suffix of the search string
363 match needle_iter.next() {
365 None => Some(self.len() - pat.len()),
370 // Returns the first byte position after the first comment. The given string
371 // is expected to be prefixed by a comment, including delimiters.
372 // Good: "/* /* inner */ outer */ code();"
373 // Bad: "code(); // hello\n world!"
374 pub fn find_comment_end(s: &str) -> Option<usize> {
375 let mut iter = CharClasses::new(s.char_indices());
376 for (kind, (i, _c)) in &mut iter {
377 if kind == FullCodeCharKind::Normal {
382 // Handle case where the comment ends at the end of s.
383 if iter.status == CharClassesStatus::Normal {
390 /// Returns true if text contains any comment.
391 pub fn contains_comment(text: &str) -> bool {
392 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
395 struct CharClasses<T>
400 base: iter::Peekable<T>,
401 status: CharClassesStatus,
405 fn get_char(&self) -> char;
408 impl RichChar for char {
409 fn get_char(&self) -> char {
414 impl RichChar for (usize, char) {
415 fn get_char(&self) -> char {
420 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
421 enum CharClassesStatus {
427 // The u32 is the nesting deepness of the comment
429 // Status when the '/' has been consumed, but not yet the '*', deepness is
430 // the new deepness (after the comment opening).
431 BlockCommentOpening(u32),
432 // Status when the '*' has been consumed, but not yet the '/', deepness is
433 // the new deepness (after the comment closing).
434 BlockCommentClosing(u32),
438 /// Distinguish between functional part of code and comments
439 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
440 pub enum CodeCharKind {
445 /// Distinguish between functional part of code and comments,
446 /// describing opening and closing of comments for ease when chunking
447 /// code from tagged characters
448 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
449 enum FullCodeCharKind {
451 /// The first character of a comment, there is only one for a comment (always '/')
453 /// Any character inside a comment including the second character of comment
454 /// marks ("//", "/*")
456 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
460 impl FullCodeCharKind {
461 fn is_comment(&self) -> bool {
463 FullCodeCharKind::Normal => false,
464 FullCodeCharKind::StartComment |
465 FullCodeCharKind::InComment |
466 FullCodeCharKind::EndComment => true,
470 fn to_codecharkind(&self) -> CodeCharKind {
471 if self.is_comment() {
472 CodeCharKind::Comment
479 impl<T> CharClasses<T>
484 fn new(base: T) -> CharClasses<T> {
486 base: base.peekable(),
487 status: CharClassesStatus::Normal,
492 impl<T> Iterator for CharClasses<T>
497 type Item = (FullCodeCharKind, T::Item);
499 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
500 let item = try_opt!(self.base.next());
501 let chr = item.get_char();
502 self.status = match self.status {
503 CharClassesStatus::LitString => {
505 '"' => CharClassesStatus::Normal,
506 '\\' => CharClassesStatus::LitStringEscape,
507 _ => CharClassesStatus::LitString,
510 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
511 CharClassesStatus::LitChar => {
513 '\\' => CharClassesStatus::LitCharEscape,
514 '\'' => CharClassesStatus::Normal,
515 _ => CharClassesStatus::LitChar,
518 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
519 CharClassesStatus::Normal => {
521 '"' => CharClassesStatus::LitString,
522 '\'' => CharClassesStatus::LitChar,
524 match self.base.peek() {
525 Some(next) if next.get_char() == '*' => {
526 self.status = CharClassesStatus::BlockCommentOpening(1);
527 return Some((FullCodeCharKind::StartComment, item));
529 Some(next) if next.get_char() == '/' => {
530 self.status = CharClassesStatus::LineComment;
531 return Some((FullCodeCharKind::StartComment, item));
533 _ => CharClassesStatus::Normal,
536 _ => CharClassesStatus::Normal,
539 CharClassesStatus::BlockComment(deepness) => {
540 assert!(deepness != 0);
541 self.status = match self.base.peek() {
542 Some(next) if next.get_char() == '/' && chr == '*' => {
543 CharClassesStatus::BlockCommentClosing(deepness - 1)
545 Some(next) if next.get_char() == '*' && chr == '/' => {
546 CharClassesStatus::BlockCommentOpening(deepness + 1)
548 _ => CharClassesStatus::BlockComment(deepness),
550 return Some((FullCodeCharKind::InComment, item));
552 CharClassesStatus::BlockCommentOpening(deepness) => {
553 assert_eq!(chr, '*');
554 self.status = CharClassesStatus::BlockComment(deepness);
555 return Some((FullCodeCharKind::InComment, item));
557 CharClassesStatus::BlockCommentClosing(deepness) => {
558 assert_eq!(chr, '/');
560 self.status = CharClassesStatus::Normal;
561 return Some((FullCodeCharKind::EndComment, item));
563 self.status = CharClassesStatus::BlockComment(deepness);
564 return Some((FullCodeCharKind::InComment, item));
567 CharClassesStatus::LineComment => {
570 self.status = CharClassesStatus::Normal;
571 return Some((FullCodeCharKind::EndComment, item));
574 self.status = CharClassesStatus::LineComment;
575 return Some((FullCodeCharKind::InComment, item));
580 Some((FullCodeCharKind::Normal, item))
584 /// Iterator over functional and commented parts of a string. Any part of a string is either
585 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
586 /// comments is functional code. Line comments contain their ending newlines.
587 struct UngroupedCommentCodeSlices<'a> {
589 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
592 impl<'a> UngroupedCommentCodeSlices<'a> {
593 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
594 UngroupedCommentCodeSlices {
596 iter: CharClasses::new(code.char_indices()).peekable(),
601 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
602 type Item = (CodeCharKind, usize, &'a str);
604 fn next(&mut self) -> Option<Self::Item> {
605 let (kind, (start_idx, _)) = try_opt!(self.iter.next());
607 FullCodeCharKind::Normal => {
608 // Consume all the Normal code
609 while let Some(&(FullCodeCharKind::Normal, (_, _))) = self.iter.peek() {
610 let _ = self.iter.next();
613 FullCodeCharKind::StartComment => {
614 // Consume the whole comment
615 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
619 let slice = match self.iter.peek() {
620 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
621 None => &self.slice[start_idx..],
624 if kind.is_comment() {
625 CodeCharKind::Comment
638 /// Iterator over an alternating sequence of functional and commented parts of
639 /// a string. The first item is always a, possibly zero length, subslice of
640 /// functional text. Line style comments contain their ending newlines.
641 pub struct CommentCodeSlices<'a> {
643 last_slice_kind: CodeCharKind,
644 last_slice_end: usize,
647 impl<'a> CommentCodeSlices<'a> {
648 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
651 last_slice_kind: CodeCharKind::Comment,
657 impl<'a> Iterator for CommentCodeSlices<'a> {
658 type Item = (CodeCharKind, usize, &'a str);
660 fn next(&mut self) -> Option<Self::Item> {
661 if self.last_slice_end == self.slice.len() {
665 let mut sub_slice_end = self.last_slice_end;
666 let mut first_whitespace = None;
667 let subslice = &self.slice[self.last_slice_end..];
668 let mut iter = CharClasses::new(subslice.char_indices());
670 for (kind, (i, c)) in &mut iter {
671 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
672 &subslice[..2] == "//" &&
673 [' ', '\t'].contains(&c);
675 if is_comment_connector && first_whitespace.is_none() {
676 first_whitespace = Some(i);
679 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
680 let last_index = match first_whitespace {
684 sub_slice_end = self.last_slice_end + last_index;
688 if !is_comment_connector {
689 first_whitespace = None;
693 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
694 // This was the last subslice.
695 sub_slice_end = match first_whitespace {
696 Some(i) => self.last_slice_end + i,
697 None => self.slice.len(),
701 let kind = match self.last_slice_kind {
702 CodeCharKind::Comment => CodeCharKind::Normal,
703 CodeCharKind::Normal => CodeCharKind::Comment,
708 &self.slice[self.last_slice_end..sub_slice_end],
710 self.last_slice_end = sub_slice_end;
711 self.last_slice_kind = kind;
717 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
718 /// (if it fits in the width/offset, else return None), else return `new`
719 pub fn recover_comment_removed(
722 context: &RewriteContext,
724 ) -> Option<String> {
725 let snippet = context.snippet(span);
726 if changed_comment_content(&snippet, &new) {
727 // We missed some comments
728 // Keep previous formatting if it satisfies the constrains
729 wrap_str(snippet, context.config.max_width(), shape)
735 /// Return true if the two strings of code have the same payload of comments.
736 /// The payload of comments is everything in the string except:
737 /// - actual code (not comments)
738 /// - comment start/end marks
740 /// - '*' at the beginning of lines in block comments
741 fn changed_comment_content(orig: &str, new: &str) -> bool {
742 // Cannot write this as a fn since we cannot return types containing closures
743 let code_comment_content = |code| {
744 let slices = UngroupedCommentCodeSlices::new(code);
746 .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
747 .flat_map(|(_, _, s)| CommentReducer::new(s))
749 let res = code_comment_content(orig).ne(code_comment_content(new));
751 "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
755 code_comment_content(orig).collect::<String>(),
756 code_comment_content(new).collect::<String>()
762 /// Iterator over the 'payload' characters of a comment.
763 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
764 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
766 struct CommentReducer<'a> {
769 iter: std::str::Chars<'a>,
772 impl<'a> CommentReducer<'a> {
773 fn new(comment: &'a str) -> CommentReducer<'a> {
774 let is_block = comment.starts_with("/*");
775 let comment = remove_comment_header(comment);
778 at_start_line: false, // There are no supplementary '*' on the first line
779 iter: comment.chars(),
784 impl<'a> Iterator for CommentReducer<'a> {
786 fn next(&mut self) -> Option<Self::Item> {
788 let mut c = try_opt!(self.iter.next());
789 if self.is_block && self.at_start_line {
790 while c.is_whitespace() {
791 c = try_opt!(self.iter.next());
793 // Ignore leading '*'
795 c = try_opt!(self.iter.next());
799 self.at_start_line = true;
802 if !c.is_whitespace() {
810 fn remove_comment_header(comment: &str) -> &str {
811 if comment.starts_with("///") || comment.starts_with("//!") {
813 } else if comment.starts_with("//") {
815 } else if (comment.starts_with("/**") && !comment.starts_with("/**/")) ||
816 comment.starts_with("/*!")
818 &comment[3..comment.len() - 2]
821 comment.starts_with("/*"),
822 format!("string '{}' is not a comment", comment)
824 &comment[2..comment.len() - 2]
830 use super::{CharClasses, CodeCharKind, FullCodeCharKind, contains_comment, rewrite_comment,
831 FindUncommented, CommentCodeSlices};
836 let mut iter = CharClasses::new("//\n\n".chars());
838 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
839 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
840 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
841 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
842 assert_eq!(None, iter.next());
846 fn comment_code_slices() {
847 let input = "code(); /* test */ 1 + 1";
848 let mut iter = CommentCodeSlices::new(input);
850 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
852 (CodeCharKind::Comment, 8, "/* test */"),
855 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
856 assert_eq!(None, iter.next());
860 fn comment_code_slices_two() {
861 let input = "// comment\n test();";
862 let mut iter = CommentCodeSlices::new(input);
864 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
866 (CodeCharKind::Comment, 0, "// comment\n"),
870 (CodeCharKind::Normal, 11, " test();"),
873 assert_eq!(None, iter.next());
877 fn comment_code_slices_three() {
878 let input = "1 // comment\n // comment2\n\n";
879 let mut iter = CommentCodeSlices::new(input);
881 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
883 (CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
886 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
887 assert_eq!(None, iter.next());
891 #[cfg_attr(rustfmt, rustfmt_skip)]
892 fn format_comments() {
893 let mut config: ::config::Config = Default::default();
894 config.set().wrap_comments(true);
895 config.set().normalize_comments(true);
897 let comment = rewrite_comment(" //test",
899 Shape::legacy(100, Indent::new(0, 100)),
901 assert_eq!("/* test */", comment);
903 let comment = rewrite_comment("// comment on a",
905 Shape::legacy(10, Indent::empty()),
907 assert_eq!("// comment\n// on a", comment);
909 let comment = rewrite_comment("// A multi line comment\n // between args.",
911 Shape::legacy(60, Indent::new(0, 12)),
913 assert_eq!("// A multi line comment\n // between args.", comment);
915 let input = "// comment";
918 let comment = rewrite_comment(input,
920 Shape::legacy(9, Indent::new(0, 69)),
922 assert_eq!(expected, comment);
924 let comment = rewrite_comment("/* trimmed */",
926 Shape::legacy(100, Indent::new(0, 100)),
928 assert_eq!("/* trimmed */", comment);
931 // This is probably intended to be a non-test fn, but it is not used. I'm
932 // keeping it around unless it helps us test stuff.
933 fn uncommented(text: &str) -> String {
934 CharClasses::new(text.chars())
935 .filter_map(|(s, c)| match s {
936 FullCodeCharKind::Normal => Some(c),
943 fn test_uncommented() {
944 assert_eq!(&uncommented("abc/*...*/"), "abc");
946 &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
949 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
953 fn test_contains_comment() {
954 assert_eq!(contains_comment("abc"), false);
955 assert_eq!(contains_comment("abc // qsdf"), true);
956 assert_eq!(contains_comment("abc /* kqsdf"), true);
957 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
961 fn test_find_uncommented() {
962 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
963 assert_eq!(expected, haystack.find_uncommented(needle));
966 check("/*/ */test", "test", Some(6));
967 check("//test\ntest", "test", Some(7));
968 check("/* comment only */", "whatever", None);
970 "/* comment */ some text /* more commentary */ result",
974 check("sup // sup", "p", Some(2));
975 check("sup", "x", None);
976 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
977 check("/*sup yo? \n sup*/ sup", "p", Some(20));
978 check("hel/*lohello*/lo", "hello", None);
979 check("acb", "ab", None);
980 check(",/*A*/ ", ",", Some(0));
981 check("abc", "abc", Some(0));
982 check("/* abc */", "abc", None);
983 check("/**/abc/* */", "abc", Some(4));
984 check("\"/* abc */\"", "abc", Some(4));
985 check("\"/* abc", "abc", Some(4));