]> git.lizzy.rs Git - rust.git/blob - src/comment.rs
Don't apply the function args heuristic to tuple lits.
[rust.git] / src / comment.rs
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.
4 //
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.
10
11 // Formatting and tools for comments.
12
13 use std::{self, iter};
14
15 use syntax::codemap::Span;
16
17 use Indent;
18 use config::Config;
19 use rewrite::RewriteContext;
20 use string::{StringFormat, rewrite_string};
21 use utils::wrap_str;
22
23 pub fn rewrite_comment(orig: &str,
24                        block_style: bool,
25                        width: usize,
26                        offset: Indent,
27                        config: &Config)
28                        -> Option<String> {
29     let s = orig.trim();
30
31     // Edge case: block comments. Let's not trim their lines (for now).
32     let (opener, closer, line_start) = if block_style {
33         ("/* ", " */", " * ")
34     } else if !config.normalise_comments {
35         if orig.starts_with("/**") {
36             ("/** ", " **/", " ** ")
37         } else if orig.starts_with("/*!") {
38             ("/*! ", " */", " * ")
39         } else if orig.starts_with("/*") {
40             ("/* ", " */", " * ")
41         } else if orig.starts_with("///") {
42             ("/// ", "", "/// ")
43         } else if orig.starts_with("//!") {
44             ("//! ", "", "//! ")
45         } else {
46             ("// ", "", "// ")
47         }
48     } else if orig.starts_with("///") || orig.starts_with("/**") {
49         ("/// ", "", "/// ")
50     } else if orig.starts_with("//!") || orig.starts_with("/*!") {
51         ("//! ", "", "//! ")
52     } else {
53         ("// ", "", "// ")
54     };
55
56     let max_chars = width.checked_sub(closer.len() + opener.len()).unwrap_or(1);
57
58     let fmt = StringFormat {
59         opener: "",
60         closer: "",
61         line_start: line_start,
62         line_end: "",
63         width: max_chars,
64         offset: offset + (opener.len() - line_start.len()),
65         trim_end: true,
66         config: config,
67     };
68
69     let indent_str = offset.to_string(config);
70     let line_breaks = s.chars().filter(|&c| c == '\n').count();
71
72     let lines = s.lines()
73                  .enumerate()
74                  .map(|(i, mut line)| {
75                      line = line.trim();
76                      // Drop old closer.
77                      if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
78                          line = &line[..(line.len() - 2)];
79                      }
80
81                      line.trim_right()
82                  })
83                  .map(left_trim_comment_line)
84                  .map(|line| {
85                      if line_breaks == 0 {
86                          line.trim_left()
87                      } else {
88                          line
89                      }
90                  });
91
92     let mut result = opener.to_owned();
93     for line in lines {
94         if result == opener {
95             if line.len() == 0 {
96                 continue;
97             }
98         } else {
99             result.push('\n');
100             result.push_str(&indent_str);
101             result.push_str(line_start);
102         }
103
104         if config.wrap_comments && line.len() > max_chars {
105             let rewrite = try_opt!(rewrite_string(line, &fmt));
106             result.push_str(&rewrite);
107         } else {
108             if line.len() == 0 {
109                 // Remove space if this is an empty comment or a doc comment.
110                 result.pop();
111             }
112             result.push_str(line);
113         }
114     }
115
116     result.push_str(closer);
117     if result == opener {
118         // Trailing space.
119         result.pop();
120     }
121
122     Some(result)
123 }
124
125 fn left_trim_comment_line(line: &str) -> &str {
126     if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") ||
127        line.starts_with("/** ") {
128         &line[4..]
129     } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!") ||
130        line.starts_with("///") || line.starts_with("** ") || line.starts_with("/*!") ||
131        line.starts_with("/**") {
132         &line[3..]
133     } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") ||
134        line.starts_with("**") {
135         &line[2..]
136     } else if line.starts_with("*") {
137         &line[1..]
138     } else {
139         line
140     }
141 }
142
143 pub trait FindUncommented {
144     fn find_uncommented(&self, pat: &str) -> Option<usize>;
145 }
146
147 impl FindUncommented for str {
148     fn find_uncommented(&self, pat: &str) -> Option<usize> {
149         let mut needle_iter = pat.chars();
150         for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
151             match needle_iter.next() {
152                 None => {
153                     return Some(i - pat.len());
154                 }
155                 Some(c) => {
156                     match kind {
157                         FullCodeCharKind::Normal if b == c => {}
158                         _ => {
159                             needle_iter = pat.chars();
160                         }
161                     }
162                 }
163             }
164         }
165
166         // Handle case where the pattern is a suffix of the search string
167         match needle_iter.next() {
168             Some(_) => None,
169             None => Some(self.len() - pat.len()),
170         }
171     }
172 }
173
174 // Returns the first byte position after the first comment. The given string
175 // is expected to be prefixed by a comment, including delimiters.
176 // Good: "/* /* inner */ outer */ code();"
177 // Bad:  "code(); // hello\n world!"
178 pub fn find_comment_end(s: &str) -> Option<usize> {
179     let mut iter = CharClasses::new(s.char_indices());
180     for (kind, (i, _c)) in &mut iter {
181         if kind == FullCodeCharKind::Normal {
182             return Some(i);
183         }
184     }
185
186     // Handle case where the comment ends at the end of s.
187     if iter.status == CharClassesStatus::Normal {
188         Some(s.len())
189     } else {
190         None
191     }
192 }
193
194 /// Returns true if text contains any comment.
195 pub fn contains_comment(text: &str) -> bool {
196     CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
197 }
198
199 struct CharClasses<T>
200     where T: Iterator,
201           T::Item: RichChar
202 {
203     base: iter::Peekable<T>,
204     status: CharClassesStatus,
205 }
206
207 trait RichChar {
208     fn get_char(&self) -> char;
209 }
210
211 impl RichChar for char {
212     fn get_char(&self) -> char {
213         *self
214     }
215 }
216
217 impl RichChar for (usize, char) {
218     fn get_char(&self) -> char {
219         self.1
220     }
221 }
222
223 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
224 enum CharClassesStatus {
225     Normal,
226     LitString,
227     LitStringEscape,
228     LitChar,
229     LitCharEscape,
230     // The u32 is the nesting deepness of the comment
231     BlockComment(u32),
232     // Status when the '/' has been consumed, but not yet the '*', deepness is
233     // the new deepness (after the comment opening).
234     BlockCommentOpening(u32),
235     // Status when the '*' has been consumed, but not yet the '/', deepness is
236     // the new deepness (after the comment closing).
237     BlockCommentClosing(u32),
238     LineComment,
239 }
240
241 /// Distinguish between functionnal part of code and comments
242 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
243 pub enum CodeCharKind {
244     Normal,
245     Comment,
246 }
247
248 /// Distinguish between functionnal part of code and comments,
249 /// describing opening and closing of comments for ease when chunking
250 /// code from tagged characters
251 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
252 enum FullCodeCharKind {
253     Normal,
254     /// The first character of a comment, there is only one for a comment (always '/')
255     StartComment,
256     /// Any character inside a comment including the second character of comment
257     /// marks ("//", "/*")
258     InComment,
259     /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
260     EndComment,
261 }
262
263 impl FullCodeCharKind {
264     fn is_comment(&self) -> bool {
265         match *self {
266             FullCodeCharKind::Normal => false,
267             FullCodeCharKind::StartComment |
268             FullCodeCharKind::InComment |
269             FullCodeCharKind::EndComment => true,
270         }
271     }
272
273     fn to_codecharkind(&self) -> CodeCharKind {
274         if self.is_comment() {
275             CodeCharKind::Comment
276         } else {
277             CodeCharKind::Normal
278         }
279     }
280 }
281
282 impl<T> CharClasses<T>
283     where T: Iterator,
284           T::Item: RichChar
285 {
286     fn new(base: T) -> CharClasses<T> {
287         CharClasses {
288             base: base.peekable(),
289             status: CharClassesStatus::Normal,
290         }
291     }
292 }
293
294 impl<T> Iterator for CharClasses<T>
295     where T: Iterator,
296           T::Item: RichChar
297 {
298     type Item = (FullCodeCharKind, T::Item);
299
300     fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
301         let item = try_opt!(self.base.next());
302         let chr = item.get_char();
303         self.status = match self.status {
304             CharClassesStatus::LitString => {
305                 match chr {
306                     '"' => CharClassesStatus::Normal,
307                     '\\' => CharClassesStatus::LitStringEscape,
308                     _ => CharClassesStatus::LitString,
309                 }
310             }
311             CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
312             CharClassesStatus::LitChar => {
313                 match chr {
314                     '\\' => CharClassesStatus::LitCharEscape,
315                     '\'' => CharClassesStatus::Normal,
316                     _ => CharClassesStatus::LitChar,
317                 }
318             }
319             CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
320             CharClassesStatus::Normal => {
321                 match chr {
322                     '"' => CharClassesStatus::LitString,
323                     '\'' => CharClassesStatus::LitChar,
324                     '/' => {
325                         match self.base.peek() {
326                             Some(next) if next.get_char() == '*' => {
327                                 self.status = CharClassesStatus::BlockCommentOpening(1);
328                                 return Some((FullCodeCharKind::StartComment, item));
329                             }
330                             Some(next) if next.get_char() == '/' => {
331                                 self.status = CharClassesStatus::LineComment;
332                                 return Some((FullCodeCharKind::StartComment, item));
333                             }
334                             _ => CharClassesStatus::Normal,
335                         }
336                     }
337                     _ => CharClassesStatus::Normal,
338                 }
339             }
340             CharClassesStatus::BlockComment(deepness) => {
341                 assert!(deepness != 0);
342                 self.status = match self.base.peek() {
343                     Some(next) if next.get_char() == '/' && chr == '*' => {
344                         CharClassesStatus::BlockCommentClosing(deepness - 1)
345                     }
346                     Some(next) if next.get_char() == '*' && chr == '/' => {
347                         CharClassesStatus::BlockCommentOpening(deepness + 1)
348                     }
349                     _ => CharClassesStatus::BlockComment(deepness),
350                 };
351                 return Some((FullCodeCharKind::InComment, item));
352             }
353             CharClassesStatus::BlockCommentOpening(deepness) => {
354                 assert_eq!(chr, '*');
355                 self.status = CharClassesStatus::BlockComment(deepness);
356                 return Some((FullCodeCharKind::InComment, item));
357             }
358             CharClassesStatus::BlockCommentClosing(deepness) => {
359                 assert_eq!(chr, '/');
360                 if deepness == 0 {
361                     self.status = CharClassesStatus::Normal;
362                     return Some((FullCodeCharKind::EndComment, item));
363                 } else {
364                     self.status = CharClassesStatus::BlockComment(deepness);
365                     return Some((FullCodeCharKind::InComment, item));
366                 }
367             }
368             CharClassesStatus::LineComment => {
369                 match chr {
370                     '\n' => {
371                         self.status = CharClassesStatus::Normal;
372                         return Some((FullCodeCharKind::EndComment, item));
373                     }
374                     _ => {
375                         self.status = CharClassesStatus::LineComment;
376                         return Some((FullCodeCharKind::InComment, item));
377                     }
378                 }
379             }
380         };
381         Some((FullCodeCharKind::Normal, item))
382     }
383 }
384
385 /// Iterator over functional and commented parts of a string. Any part of a string is either
386 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
387 /// comments is functional code. Line comments contain their ending newlines.
388 struct UngroupedCommentCodeSlices<'a> {
389     slice: &'a str,
390     iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
391 }
392
393 impl<'a> UngroupedCommentCodeSlices<'a> {
394     fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
395         UngroupedCommentCodeSlices {
396             slice: code,
397             iter: CharClasses::new(code.char_indices()).peekable(),
398         }
399     }
400 }
401
402 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
403     type Item = (CodeCharKind, usize, &'a str);
404
405     fn next(&mut self) -> Option<Self::Item> {
406         let (kind, (start_idx, _)) = try_opt!(self.iter.next());
407         match kind {
408             FullCodeCharKind::Normal => {
409                 // Consume all the Normal code
410                 while let Some(&(FullCodeCharKind::Normal, (_, _))) = self.iter.peek() {
411                     let _ = self.iter.next();
412                 }
413             }
414             FullCodeCharKind::StartComment => {
415                 // Consume the whole comment
416                 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
417             }
418             _ => panic!(),
419         }
420         let slice = match self.iter.peek() {
421             Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
422             None => &self.slice[start_idx..],
423         };
424         Some((if kind.is_comment() {
425             CodeCharKind::Comment
426         } else {
427             CodeCharKind::Normal
428         },
429               start_idx,
430               slice))
431     }
432 }
433
434
435
436
437 /// Iterator over an alternating sequence of functional and commented parts of
438 /// a string. The first item is always a, possibly zero length, subslice of
439 /// functional text. Line style comments contain their ending newlines.
440 pub struct CommentCodeSlices<'a> {
441     slice: &'a str,
442     last_slice_kind: CodeCharKind,
443     last_slice_end: usize,
444 }
445
446 impl<'a> CommentCodeSlices<'a> {
447     pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
448         CommentCodeSlices {
449             slice: slice,
450             last_slice_kind: CodeCharKind::Comment,
451             last_slice_end: 0,
452         }
453     }
454 }
455
456 impl<'a> Iterator for CommentCodeSlices<'a> {
457     type Item = (CodeCharKind, usize, &'a str);
458
459     fn next(&mut self) -> Option<Self::Item> {
460         if self.last_slice_end == self.slice.len() {
461             return None;
462         }
463
464         let mut sub_slice_end = self.last_slice_end;
465         let mut first_whitespace = None;
466         let subslice = &self.slice[self.last_slice_end..];
467         let mut iter = CharClasses::new(subslice.char_indices());
468
469         for (kind, (i, c)) in &mut iter {
470             let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
471                                        &subslice[..2] == "//" &&
472                                        [' ', '\t'].contains(&c);
473
474             if is_comment_connector && first_whitespace.is_none() {
475                 first_whitespace = Some(i);
476             }
477
478             if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
479                 let last_index = match first_whitespace {
480                     Some(j) => j,
481                     None => i,
482                 };
483                 sub_slice_end = self.last_slice_end + last_index;
484                 break;
485             }
486
487             if !is_comment_connector {
488                 first_whitespace = None;
489             }
490         }
491
492         if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
493             // This was the last subslice.
494             sub_slice_end = match first_whitespace {
495                 Some(i) => self.last_slice_end + i,
496                 None => self.slice.len(),
497             };
498         }
499
500         let kind = match self.last_slice_kind {
501             CodeCharKind::Comment => CodeCharKind::Normal,
502             CodeCharKind::Normal => CodeCharKind::Comment,
503         };
504         let res = (kind, self.last_slice_end, &self.slice[self.last_slice_end..sub_slice_end]);
505         self.last_slice_end = sub_slice_end;
506         self.last_slice_kind = kind;
507
508         Some(res)
509     }
510 }
511
512 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
513 /// (if it fits in the width/offset, else return None), else return `new`
514 pub fn recover_comment_removed(new: String,
515                                span: Span,
516                                context: &RewriteContext,
517                                width: usize,
518                                offset: Indent)
519                                -> Option<String> {
520     let snippet = context.snippet(span);
521     if changed_comment_content(&snippet, &new) {
522         // We missed some comments
523         // Keep previous formatting if it satisfies the constrains
524         return wrap_str(snippet, context.config.max_width, width, offset);
525     } else {
526         Some(new)
527     }
528 }
529
530 /// Return true if the two strings of code have the same payload of comments.
531 /// The payload of comments is everything in the string except:
532 ///     - actual code (not comments)
533 ///     - comment start/end marks
534 ///             - whitespace
535 ///             - '*' at the beginning of lines in block comments
536 fn changed_comment_content(orig: &str, new: &str) -> bool {
537     // Cannot write this as a fn since we cannot return types containing closures
538     let code_comment_content = |code| {
539         let slices = UngroupedCommentCodeSlices::new(code);
540         slices.filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
541               .flat_map(|(_, _, s)| CommentReducer::new(s))
542     };
543     let res = code_comment_content(orig).ne(code_comment_content(new));
544     debug!("comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
545            res,
546            orig,
547            new,
548            code_comment_content(orig).collect::<String>(),
549            code_comment_content(new).collect::<String>());
550     res
551 }
552
553
554 /// Iterator over the 'payload' characters of a comment.
555 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
556 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
557 /// for example).
558 struct CommentReducer<'a> {
559     is_block: bool,
560     at_start_line: bool,
561     iter: std::str::Chars<'a>,
562 }
563
564 impl<'a> CommentReducer<'a> {
565     fn new(comment: &'a str) -> CommentReducer<'a> {
566         let is_block = comment.starts_with("/*");
567         let comment = remove_comment_header(comment);
568         CommentReducer {
569             is_block: is_block,
570             at_start_line: false, // There are no supplementary '*' on the first line
571             iter: comment.chars(),
572         }
573     }
574 }
575
576 impl<'a> Iterator for CommentReducer<'a> {
577     type Item = char;
578     fn next(&mut self) -> Option<Self::Item> {
579         loop {
580             let mut c = try_opt!(self.iter.next());
581             if self.is_block && self.at_start_line {
582                 while c.is_whitespace() {
583                     c = try_opt!(self.iter.next());
584                 }
585                 // Ignore leading '*'
586                 if c == '*' {
587                     c = try_opt!(self.iter.next());
588                 }
589             } else {
590                 if c == '\n' {
591                     self.at_start_line = true;
592                 }
593             }
594             if !c.is_whitespace() {
595                 return Some(c);
596             }
597         }
598     }
599 }
600
601
602 fn remove_comment_header(comment: &str) -> &str {
603     if comment.starts_with("///") || comment.starts_with("//!") {
604         &comment[3..]
605     } else if comment.starts_with("//") {
606         &comment[2..]
607     } else if comment.starts_with("/**") || comment.starts_with("/*!") {
608         &comment[3..comment.len() - 2]
609     } else {
610         assert!(comment.starts_with("/*"),
611                 format!("string '{}' is not a comment", comment));
612         &comment[2..comment.len() - 2]
613     }
614 }
615
616 #[cfg(test)]
617 mod test {
618     use super::{CharClasses, CodeCharKind, FullCodeCharKind, contains_comment, rewrite_comment,
619                 FindUncommented, CommentCodeSlices};
620     use Indent;
621
622     #[test]
623     fn char_classes() {
624         let mut iter = CharClasses::new("//\n\n".chars());
625
626         assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
627         assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
628         assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
629         assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
630         assert_eq!(None, iter.next());
631     }
632
633     #[test]
634     fn comment_code_slices() {
635         let input = "code(); /* test */ 1 + 1";
636         let mut iter = CommentCodeSlices::new(input);
637
638         assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
639         assert_eq!((CodeCharKind::Comment, 8, "/* test */"),
640                    iter.next().unwrap());
641         assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
642         assert_eq!(None, iter.next());
643     }
644
645     #[test]
646     fn comment_code_slices_two() {
647         let input = "// comment\n    test();";
648         let mut iter = CommentCodeSlices::new(input);
649
650         assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
651         assert_eq!((CodeCharKind::Comment, 0, "// comment\n"),
652                    iter.next().unwrap());
653         assert_eq!((CodeCharKind::Normal, 11, "    test();"),
654                    iter.next().unwrap());
655         assert_eq!(None, iter.next());
656     }
657
658     #[test]
659     fn comment_code_slices_three() {
660         let input = "1 // comment\n    // comment2\n\n";
661         let mut iter = CommentCodeSlices::new(input);
662
663         assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
664         assert_eq!((CodeCharKind::Comment, 2, "// comment\n    // comment2\n"),
665                    iter.next().unwrap());
666         assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
667         assert_eq!(None, iter.next());
668     }
669
670     #[test]
671     #[cfg_attr(rustfmt, rustfmt_skip)]
672     fn format_comments() {
673         let mut config: ::config::Config = Default::default();
674         config.wrap_comments = true;
675         assert_eq!("/* test */", rewrite_comment(" //test", true, 100, Indent::new(0, 100),
676                                                  &config).unwrap());
677         assert_eq!("// comment\n// on a", rewrite_comment("// comment on a", false, 10,
678                                                           Indent::empty(), &config).unwrap());
679
680         assert_eq!("//  A multi line comment\n            // between args.",
681                    rewrite_comment("//  A multi line comment\n             // between args.",
682                                    false,
683                                    60,
684                                    Indent::new(0, 12),
685                                    &config).unwrap());
686
687         let input = "// comment";
688         let expected =
689             "/* com\n                                                                      \
690              * men\n                                                                      \
691              * t */";
692         assert_eq!(expected, rewrite_comment(input, true, 9, Indent::new(0, 69), &config).unwrap());
693
694         assert_eq!("/* trimmed */", rewrite_comment("/*   trimmed    */", true, 100,
695                                                     Indent::new(0, 100), &config).unwrap());
696     }
697
698     // This is probably intended to be a non-test fn, but it is not used. I'm
699     // keeping it around unless it helps us test stuff.
700     fn uncommented(text: &str) -> String {
701         CharClasses::new(text.chars())
702             .filter_map(|(s, c)| {
703                 match s {
704                     FullCodeCharKind::Normal => Some(c),
705                     _ => None,
706                 }
707             })
708             .collect()
709     }
710
711     #[test]
712     fn test_uncommented() {
713         assert_eq!(&uncommented("abc/*...*/"), "abc");
714         assert_eq!(&uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
715                    "..ac\n");
716         assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
717     }
718
719     #[test]
720     fn test_contains_comment() {
721         assert_eq!(contains_comment("abc"), false);
722         assert_eq!(contains_comment("abc // qsdf"), true);
723         assert_eq!(contains_comment("abc /* kqsdf"), true);
724         assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
725     }
726
727     #[test]
728     fn test_find_uncommented() {
729         fn check(haystack: &str, needle: &str, expected: Option<usize>) {
730             assert_eq!(expected, haystack.find_uncommented(needle));
731         }
732
733         check("/*/ */test", "test", Some(6));
734         check("//test\ntest", "test", Some(7));
735         check("/* comment only */", "whatever", None);
736         check("/* comment */ some text /* more commentary */ result",
737               "result",
738               Some(46));
739         check("sup // sup", "p", Some(2));
740         check("sup", "x", None);
741         check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
742         check("/*sup yo? \n sup*/ sup", "p", Some(20));
743         check("hel/*lohello*/lo", "hello", None);
744         check("acb", "ab", None);
745         check(",/*A*/ ", ",", Some(0));
746         check("abc", "abc", Some(0));
747         check("/* abc */", "abc", None);
748         check("/**/abc/* */", "abc", Some(4));
749         check("\"/* abc */\"", "abc", Some(4));
750         check("\"/* abc", "abc", Some(4));
751     }
752 }