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