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