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 |
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("/**/")) {
134 CommentStyle::TripleSlash
135 } else if orig.starts_with("//!") || orig.starts_with("/*!") {
137 } else if is_custom_comment(orig) {
138 CommentStyle::Custom(custom_opener(orig))
140 CommentStyle::DoubleSlash
144 pub fn rewrite_comment(orig: &str,
149 // If there are lines without a starting sigil, we won't format them correctly
150 // so in that case we won't even re-align (if !config.normalize_comments()) and
151 // we should stop now.
152 let num_bare_lines = orig.lines()
153 .map(|line| line.trim())
154 .filter(|l| !(l.starts_with('*') || l.starts_with("//") || l.starts_with("/*")))
156 if num_bare_lines > 0 && !config.normalize_comments() {
157 return Some(orig.to_owned());
159 if !config.normalize_comments() && !config.wrap_comments() {
160 return light_rewrite_comment(orig, shape.indent, config);
163 identify_comment(orig, block_style, shape, config)
166 fn identify_comment(orig: &str,
171 let style = comment_style(orig, false);
172 let first_group = orig.lines()
173 .take_while(|l| style.line_with_same_comment_style(l, false))
176 let rest = orig.lines()
177 .skip(first_group.lines().count())
181 let first_group_str =
182 try_opt!(rewrite_comment_inner(&first_group, block_style, style, shape, config));
184 Some(first_group_str)
186 identify_comment(&rest, block_style, shape, config).map(|rest_str| {
197 fn rewrite_comment_inner(orig: &str,
203 let (opener, closer, line_start) = if block_style {
204 CommentStyle::SingleBullet.to_str_tuplet()
206 comment_style(orig, config.normalize_comments()).to_str_tuplet()
209 let max_chars = shape
211 .checked_sub(closer.len() + opener.len())
213 let indent_str = shape.indent.to_string(config);
214 let fmt = StringFormat {
217 line_start: line_start,
219 shape: Shape::legacy(max_chars, shape.indent + (opener.len() - line_start.len())),
224 let line_breaks = orig.trim_right().chars().filter(|&c| c == '\n').count();
225 let lines = orig.lines()
227 .map(|(i, mut line)| {
230 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
231 line = &line[..(line.len() - 2)].trim_right();
236 .map(|s| left_trim_comment_line(s, &style))
237 .map(|line| if orig.starts_with("/*") && line_breaks == 0 {
243 let mut result = opener.to_owned();
245 if result == opener {
251 result.push_str(&indent_str);
252 result.push_str(line_start);
255 if config.wrap_comments() && line.len() > max_chars {
256 let rewrite = rewrite_string(line, &fmt).unwrap_or(line.to_owned());
257 result.push_str(&rewrite);
259 if line.is_empty() && result.ends_with(' ') {
260 // Remove space if this is an empty comment or a doc comment.
263 result.push_str(line);
267 result.push_str(closer);
268 if result == opener && result.ends_with(' ') {
276 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
277 fn light_rewrite_comment(orig: &str, offset: Indent, config: &Config) -> Option<String> {
278 let lines: Vec<&str> = orig.lines()
280 // This is basically just l.trim(), but in the case that a line starts
281 // with `*` we want to leave one space before it, so it aligns with the
283 let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
284 if let Some(fnw) = first_non_whitespace {
285 if l.as_bytes()[fnw] == '*' as u8 && fnw > 0 {
295 Some(lines.join(&format!("\n{}", offset.to_string(config))))
298 /// Trims comment characters and possibly a single space from the left of a string.
299 /// Does not trim all whitespace.
300 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle) -> &'a str {
301 if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") ||
302 line.starts_with("/** ") {
304 } else if let &CommentStyle::Custom(opener) = style {
305 if line.starts_with(opener) {
306 &line[opener.len()..]
308 &line[opener.trim_right().len()..]
310 } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!") ||
311 line.starts_with("///") ||
312 line.starts_with("** ") || line.starts_with("/*!") ||
313 (line.starts_with("/**") && !line.starts_with("/**/")) {
315 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") ||
316 line.starts_with("**") {
318 } else if line.starts_with('*') {
325 pub trait FindUncommented {
326 fn find_uncommented(&self, pat: &str) -> Option<usize>;
329 impl FindUncommented for str {
330 fn find_uncommented(&self, pat: &str) -> Option<usize> {
331 let mut needle_iter = pat.chars();
332 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
333 match needle_iter.next() {
335 return Some(i - pat.len());
339 FullCodeCharKind::Normal if b == c => {}
341 needle_iter = pat.chars();
348 // Handle case where the pattern is a suffix of the search string
349 match needle_iter.next() {
351 None => Some(self.len() - pat.len()),
356 // Returns the first byte position after the first comment. The given string
357 // is expected to be prefixed by a comment, including delimiters.
358 // Good: "/* /* inner */ outer */ code();"
359 // Bad: "code(); // hello\n world!"
360 pub fn find_comment_end(s: &str) -> Option<usize> {
361 let mut iter = CharClasses::new(s.char_indices());
362 for (kind, (i, _c)) in &mut iter {
363 if kind == FullCodeCharKind::Normal {
368 // Handle case where the comment ends at the end of s.
369 if iter.status == CharClassesStatus::Normal {
376 /// Returns true if text contains any comment.
377 pub fn contains_comment(text: &str) -> bool {
378 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
381 struct CharClasses<T>
385 base: iter::Peekable<T>,
386 status: CharClassesStatus,
390 fn get_char(&self) -> char;
393 impl RichChar for char {
394 fn get_char(&self) -> char {
399 impl RichChar for (usize, char) {
400 fn get_char(&self) -> char {
405 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
406 enum CharClassesStatus {
412 // The u32 is the nesting deepness of the comment
414 // Status when the '/' has been consumed, but not yet the '*', deepness is
415 // the new deepness (after the comment opening).
416 BlockCommentOpening(u32),
417 // Status when the '*' has been consumed, but not yet the '/', deepness is
418 // the new deepness (after the comment closing).
419 BlockCommentClosing(u32),
423 /// Distinguish between functional part of code and comments
424 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
425 pub enum CodeCharKind {
430 /// Distinguish between functional part of code and comments,
431 /// describing opening and closing of comments for ease when chunking
432 /// code from tagged characters
433 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
434 enum FullCodeCharKind {
436 /// The first character of a comment, there is only one for a comment (always '/')
438 /// Any character inside a comment including the second character of comment
439 /// marks ("//", "/*")
441 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
445 impl FullCodeCharKind {
446 fn is_comment(&self) -> bool {
448 FullCodeCharKind::Normal => false,
449 FullCodeCharKind::StartComment |
450 FullCodeCharKind::InComment |
451 FullCodeCharKind::EndComment => true,
455 fn to_codecharkind(&self) -> CodeCharKind {
456 if self.is_comment() {
457 CodeCharKind::Comment
464 impl<T> CharClasses<T>
468 fn new(base: T) -> CharClasses<T> {
470 base: base.peekable(),
471 status: CharClassesStatus::Normal,
476 impl<T> Iterator for CharClasses<T>
480 type Item = (FullCodeCharKind, T::Item);
482 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
483 let item = try_opt!(self.base.next());
484 let chr = item.get_char();
485 self.status = match self.status {
486 CharClassesStatus::LitString => {
488 '"' => CharClassesStatus::Normal,
489 '\\' => CharClassesStatus::LitStringEscape,
490 _ => CharClassesStatus::LitString,
493 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
494 CharClassesStatus::LitChar => {
496 '\\' => CharClassesStatus::LitCharEscape,
497 '\'' => CharClassesStatus::Normal,
498 _ => CharClassesStatus::LitChar,
501 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
502 CharClassesStatus::Normal => {
504 '"' => CharClassesStatus::LitString,
505 '\'' => CharClassesStatus::LitChar,
507 match self.base.peek() {
508 Some(next) if next.get_char() == '*' => {
509 self.status = CharClassesStatus::BlockCommentOpening(1);
510 return Some((FullCodeCharKind::StartComment, item));
512 Some(next) if next.get_char() == '/' => {
513 self.status = CharClassesStatus::LineComment;
514 return Some((FullCodeCharKind::StartComment, item));
516 _ => CharClassesStatus::Normal,
519 _ => CharClassesStatus::Normal,
522 CharClassesStatus::BlockComment(deepness) => {
523 assert!(deepness != 0);
524 self.status = match self.base.peek() {
525 Some(next) if next.get_char() == '/' && chr == '*' => {
526 CharClassesStatus::BlockCommentClosing(deepness - 1)
528 Some(next) if next.get_char() == '*' && chr == '/' => {
529 CharClassesStatus::BlockCommentOpening(deepness + 1)
531 _ => CharClassesStatus::BlockComment(deepness),
533 return Some((FullCodeCharKind::InComment, item));
535 CharClassesStatus::BlockCommentOpening(deepness) => {
536 assert_eq!(chr, '*');
537 self.status = CharClassesStatus::BlockComment(deepness);
538 return Some((FullCodeCharKind::InComment, item));
540 CharClassesStatus::BlockCommentClosing(deepness) => {
541 assert_eq!(chr, '/');
543 self.status = CharClassesStatus::Normal;
544 return Some((FullCodeCharKind::EndComment, item));
546 self.status = CharClassesStatus::BlockComment(deepness);
547 return Some((FullCodeCharKind::InComment, item));
550 CharClassesStatus::LineComment => {
553 self.status = CharClassesStatus::Normal;
554 return Some((FullCodeCharKind::EndComment, item));
557 self.status = CharClassesStatus::LineComment;
558 return Some((FullCodeCharKind::InComment, item));
563 Some((FullCodeCharKind::Normal, item))
567 /// Iterator over functional and commented parts of a string. Any part of a string is either
568 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
569 /// comments is functional code. Line comments contain their ending newlines.
570 struct UngroupedCommentCodeSlices<'a> {
572 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
575 impl<'a> UngroupedCommentCodeSlices<'a> {
576 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
577 UngroupedCommentCodeSlices {
579 iter: CharClasses::new(code.char_indices()).peekable(),
584 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
585 type Item = (CodeCharKind, usize, &'a str);
587 fn next(&mut self) -> Option<Self::Item> {
588 let (kind, (start_idx, _)) = try_opt!(self.iter.next());
590 FullCodeCharKind::Normal => {
591 // Consume all the Normal code
592 while let Some(&(FullCodeCharKind::Normal, (_, _))) = self.iter.peek() {
593 let _ = self.iter.next();
596 FullCodeCharKind::StartComment => {
597 // Consume the whole comment
598 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
602 let slice = match self.iter.peek() {
603 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
604 None => &self.slice[start_idx..],
606 Some((if kind.is_comment() {
607 CodeCharKind::Comment
619 /// Iterator over an alternating sequence of functional and commented parts of
620 /// a string. The first item is always a, possibly zero length, subslice of
621 /// functional text. Line style comments contain their ending newlines.
622 pub struct CommentCodeSlices<'a> {
624 last_slice_kind: CodeCharKind,
625 last_slice_end: usize,
628 impl<'a> CommentCodeSlices<'a> {
629 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
632 last_slice_kind: CodeCharKind::Comment,
638 impl<'a> Iterator for CommentCodeSlices<'a> {
639 type Item = (CodeCharKind, usize, &'a str);
641 fn next(&mut self) -> Option<Self::Item> {
642 if self.last_slice_end == self.slice.len() {
646 let mut sub_slice_end = self.last_slice_end;
647 let mut first_whitespace = None;
648 let subslice = &self.slice[self.last_slice_end..];
649 let mut iter = CharClasses::new(subslice.char_indices());
651 for (kind, (i, c)) in &mut iter {
652 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
653 &subslice[..2] == "//" &&
654 [' ', '\t'].contains(&c);
656 if is_comment_connector && first_whitespace.is_none() {
657 first_whitespace = Some(i);
660 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
661 let last_index = match first_whitespace {
665 sub_slice_end = self.last_slice_end + last_index;
669 if !is_comment_connector {
670 first_whitespace = None;
674 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
675 // This was the last subslice.
676 sub_slice_end = match first_whitespace {
677 Some(i) => self.last_slice_end + i,
678 None => self.slice.len(),
682 let kind = match self.last_slice_kind {
683 CodeCharKind::Comment => CodeCharKind::Normal,
684 CodeCharKind::Normal => CodeCharKind::Comment,
686 let res = (kind, self.last_slice_end, &self.slice[self.last_slice_end..sub_slice_end]);
687 self.last_slice_end = sub_slice_end;
688 self.last_slice_kind = kind;
694 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
695 /// (if it fits in the width/offset, else return None), else return `new`
696 pub fn recover_comment_removed(new: String,
698 context: &RewriteContext,
701 let snippet = context.snippet(span);
702 if changed_comment_content(&snippet, &new) {
703 // We missed some comments
704 // Keep previous formatting if it satisfies the constrains
705 wrap_str(snippet, context.config.max_width(), shape)
711 /// Return true if the two strings of code have the same payload of comments.
712 /// The payload of comments is everything in the string except:
713 /// - actual code (not comments)
714 /// - comment start/end marks
716 /// - '*' at the beginning of lines in block comments
717 fn changed_comment_content(orig: &str, new: &str) -> bool {
718 // Cannot write this as a fn since we cannot return types containing closures
719 let code_comment_content = |code| {
720 let slices = UngroupedCommentCodeSlices::new(code);
722 .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
723 .flat_map(|(_, _, s)| CommentReducer::new(s))
725 let res = code_comment_content(orig).ne(code_comment_content(new));
726 debug!("comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
730 code_comment_content(orig).collect::<String>(),
731 code_comment_content(new).collect::<String>());
736 /// Iterator over the 'payload' characters of a comment.
737 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
738 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
740 struct CommentReducer<'a> {
743 iter: std::str::Chars<'a>,
746 impl<'a> CommentReducer<'a> {
747 fn new(comment: &'a str) -> CommentReducer<'a> {
748 let is_block = comment.starts_with("/*");
749 let comment = remove_comment_header(comment);
752 at_start_line: false, // There are no supplementary '*' on the first line
753 iter: comment.chars(),
758 impl<'a> Iterator for CommentReducer<'a> {
760 fn next(&mut self) -> Option<Self::Item> {
762 let mut c = try_opt!(self.iter.next());
763 if self.is_block && self.at_start_line {
764 while c.is_whitespace() {
765 c = try_opt!(self.iter.next());
767 // Ignore leading '*'
769 c = try_opt!(self.iter.next());
773 self.at_start_line = true;
776 if !c.is_whitespace() {
784 fn remove_comment_header(comment: &str) -> &str {
785 if comment.starts_with("///") || comment.starts_with("//!") {
787 } else if comment.starts_with("//") {
789 } else if (comment.starts_with("/**") && !comment.starts_with("/**/")) ||
790 comment.starts_with("/*!") {
791 &comment[3..comment.len() - 2]
793 assert!(comment.starts_with("/*"),
794 format!("string '{}' is not a comment", comment));
795 &comment[2..comment.len() - 2]
801 use super::{CharClasses, CodeCharKind, FullCodeCharKind, contains_comment, rewrite_comment,
802 FindUncommented, CommentCodeSlices};
807 let mut iter = CharClasses::new("//\n\n".chars());
809 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
810 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
811 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
812 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
813 assert_eq!(None, iter.next());
817 fn comment_code_slices() {
818 let input = "code(); /* test */ 1 + 1";
819 let mut iter = CommentCodeSlices::new(input);
821 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
822 assert_eq!((CodeCharKind::Comment, 8, "/* test */"),
823 iter.next().unwrap());
824 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
825 assert_eq!(None, iter.next());
829 fn comment_code_slices_two() {
830 let input = "// comment\n test();";
831 let mut iter = CommentCodeSlices::new(input);
833 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
834 assert_eq!((CodeCharKind::Comment, 0, "// comment\n"),
835 iter.next().unwrap());
836 assert_eq!((CodeCharKind::Normal, 11, " test();"),
837 iter.next().unwrap());
838 assert_eq!(None, iter.next());
842 fn comment_code_slices_three() {
843 let input = "1 // comment\n // comment2\n\n";
844 let mut iter = CommentCodeSlices::new(input);
846 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
847 assert_eq!((CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
848 iter.next().unwrap());
849 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
850 assert_eq!(None, iter.next());
854 #[cfg_attr(rustfmt, rustfmt_skip)]
855 fn format_comments() {
856 let mut config: ::config::Config = Default::default();
857 config.set().wrap_comments(true);
858 config.set().normalize_comments(true);
860 let comment = rewrite_comment(" //test",
862 Shape::legacy(100, Indent::new(0, 100)),
864 assert_eq!("/* test */", comment);
866 let comment = rewrite_comment("// comment on a",
868 Shape::legacy(10, Indent::empty()),
870 assert_eq!("// comment\n// on a", comment);
872 let comment = rewrite_comment("// A multi line comment\n // between args.",
874 Shape::legacy(60, Indent::new(0, 12)),
876 assert_eq!("// A multi line comment\n // between args.", comment);
878 let input = "// comment";
881 let comment = rewrite_comment(input,
883 Shape::legacy(9, Indent::new(0, 69)),
885 assert_eq!(expected, comment);
887 let comment = rewrite_comment("/* trimmed */",
889 Shape::legacy(100, Indent::new(0, 100)),
891 assert_eq!("/* trimmed */", comment);
894 // This is probably intended to be a non-test fn, but it is not used. I'm
895 // keeping it around unless it helps us test stuff.
896 fn uncommented(text: &str) -> String {
897 CharClasses::new(text.chars())
898 .filter_map(|(s, c)| match s {
899 FullCodeCharKind::Normal => Some(c),
906 fn test_uncommented() {
907 assert_eq!(&uncommented("abc/*...*/"), "abc");
908 assert_eq!(&uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
910 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
914 fn test_contains_comment() {
915 assert_eq!(contains_comment("abc"), false);
916 assert_eq!(contains_comment("abc // qsdf"), true);
917 assert_eq!(contains_comment("abc /* kqsdf"), true);
918 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
922 fn test_find_uncommented() {
923 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
924 assert_eq!(expected, haystack.find_uncommented(needle));
927 check("/*/ */test", "test", Some(6));
928 check("//test\ntest", "test", Some(7));
929 check("/* comment only */", "whatever", None);
930 check("/* comment */ some text /* more commentary */ result",
933 check("sup // sup", "p", Some(2));
934 check("sup", "x", None);
935 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
936 check("/*sup yo? \n sup*/ sup", "p", Some(20));
937 check("hel/*lohello*/lo", "hello", None);
938 check("acb", "ab", None);
939 check(",/*A*/ ", ",", Some(0));
940 check("abc", "abc", Some(0));
941 check("/* abc */", "abc", None);
942 check("/**/abc/* */", "abc", Some(4));
943 check("\"/* abc */\"", "abc", Some(4));
944 check("\"/* abc", "abc", Some(4));