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