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