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