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