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