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