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