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