]> git.lizzy.rs Git - rust.git/blob - src/comment.rs
Merge pull request #1782 from topecongiro/rfc/combining-match-arm
[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) => match kind {
346                     FullCodeCharKind::Normal if b == c => {}
347                     _ => {
348                         needle_iter = pat.chars();
349                     }
350                 },
351             }
352         }
353
354         // Handle case where the pattern is a suffix of the search string
355         match needle_iter.next() {
356             Some(_) => None,
357             None => Some(self.len() - pat.len()),
358         }
359     }
360 }
361
362 // Returns the first byte position after the first comment. The given string
363 // is expected to be prefixed by a comment, including delimiters.
364 // Good: "/* /* inner */ outer */ code();"
365 // Bad:  "code(); // hello\n world!"
366 pub fn find_comment_end(s: &str) -> Option<usize> {
367     let mut iter = CharClasses::new(s.char_indices());
368     for (kind, (i, _c)) in &mut iter {
369         if kind == FullCodeCharKind::Normal {
370             return Some(i);
371         }
372     }
373
374     // Handle case where the comment ends at the end of s.
375     if iter.status == CharClassesStatus::Normal {
376         Some(s.len())
377     } else {
378         None
379     }
380 }
381
382 /// Returns true if text contains any comment.
383 pub fn contains_comment(text: &str) -> bool {
384     CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
385 }
386
387 struct CharClasses<T>
388 where
389     T: Iterator,
390     T::Item: RichChar,
391 {
392     base: iter::Peekable<T>,
393     status: CharClassesStatus,
394 }
395
396 trait RichChar {
397     fn get_char(&self) -> char;
398 }
399
400 impl RichChar for char {
401     fn get_char(&self) -> char {
402         *self
403     }
404 }
405
406 impl RichChar for (usize, char) {
407     fn get_char(&self) -> char {
408         self.1
409     }
410 }
411
412 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
413 enum CharClassesStatus {
414     Normal,
415     LitString,
416     LitStringEscape,
417     LitChar,
418     LitCharEscape,
419     // The u32 is the nesting deepness of the comment
420     BlockComment(u32),
421     // Status when the '/' has been consumed, but not yet the '*', deepness is
422     // the new deepness (after the comment opening).
423     BlockCommentOpening(u32),
424     // Status when the '*' has been consumed, but not yet the '/', deepness is
425     // the new deepness (after the comment closing).
426     BlockCommentClosing(u32),
427     LineComment,
428 }
429
430 /// Distinguish between functional part of code and comments
431 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
432 pub enum CodeCharKind {
433     Normal,
434     Comment,
435 }
436
437 /// Distinguish between functional part of code and comments,
438 /// describing opening and closing of comments for ease when chunking
439 /// code from tagged characters
440 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
441 enum FullCodeCharKind {
442     Normal,
443     /// The first character of a comment, there is only one for a comment (always '/')
444     StartComment,
445     /// Any character inside a comment including the second character of comment
446     /// marks ("//", "/*")
447     InComment,
448     /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
449     EndComment,
450 }
451
452 impl FullCodeCharKind {
453     fn is_comment(&self) -> bool {
454         match *self {
455             FullCodeCharKind::Normal => false,
456             FullCodeCharKind::StartComment |
457             FullCodeCharKind::InComment |
458             FullCodeCharKind::EndComment => true,
459         }
460     }
461
462     fn to_codecharkind(&self) -> CodeCharKind {
463         if self.is_comment() {
464             CodeCharKind::Comment
465         } else {
466             CodeCharKind::Normal
467         }
468     }
469 }
470
471 impl<T> CharClasses<T>
472 where
473     T: Iterator,
474     T::Item: RichChar,
475 {
476     fn new(base: T) -> CharClasses<T> {
477         CharClasses {
478             base: base.peekable(),
479             status: CharClassesStatus::Normal,
480         }
481     }
482 }
483
484 impl<T> Iterator for CharClasses<T>
485 where
486     T: Iterator,
487     T::Item: RichChar,
488 {
489     type Item = (FullCodeCharKind, T::Item);
490
491     fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
492         let item = try_opt!(self.base.next());
493         let chr = item.get_char();
494         self.status = match self.status {
495             CharClassesStatus::LitString => match chr {
496                 '"' => CharClassesStatus::Normal,
497                 '\\' => CharClassesStatus::LitStringEscape,
498                 _ => CharClassesStatus::LitString,
499             },
500             CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
501             CharClassesStatus::LitChar => match chr {
502                 '\\' => CharClassesStatus::LitCharEscape,
503                 '\'' => CharClassesStatus::Normal,
504                 _ => CharClassesStatus::LitChar,
505             },
506             CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
507             CharClassesStatus::Normal => match chr {
508                 '"' => CharClassesStatus::LitString,
509                 '\'' => CharClassesStatus::LitChar,
510                 '/' => match self.base.peek() {
511                     Some(next) if next.get_char() == '*' => {
512                         self.status = CharClassesStatus::BlockCommentOpening(1);
513                         return Some((FullCodeCharKind::StartComment, item));
514                     }
515                     Some(next) if next.get_char() == '/' => {
516                         self.status = CharClassesStatus::LineComment;
517                         return Some((FullCodeCharKind::StartComment, item));
518                     }
519                     _ => CharClassesStatus::Normal,
520                 },
521                 _ => CharClassesStatus::Normal,
522             },
523             CharClassesStatus::BlockComment(deepness) => {
524                 assert!(deepness != 0);
525                 self.status = match self.base.peek() {
526                     Some(next) if next.get_char() == '/' && chr == '*' => {
527                         CharClassesStatus::BlockCommentClosing(deepness - 1)
528                     }
529                     Some(next) if next.get_char() == '*' && chr == '/' => {
530                         CharClassesStatus::BlockCommentOpening(deepness + 1)
531                     }
532                     _ => CharClassesStatus::BlockComment(deepness),
533                 };
534                 return Some((FullCodeCharKind::InComment, item));
535             }
536             CharClassesStatus::BlockCommentOpening(deepness) => {
537                 assert_eq!(chr, '*');
538                 self.status = CharClassesStatus::BlockComment(deepness);
539                 return Some((FullCodeCharKind::InComment, item));
540             }
541             CharClassesStatus::BlockCommentClosing(deepness) => {
542                 assert_eq!(chr, '/');
543                 if deepness == 0 {
544                     self.status = CharClassesStatus::Normal;
545                     return Some((FullCodeCharKind::EndComment, item));
546                 } else {
547                     self.status = CharClassesStatus::BlockComment(deepness);
548                     return Some((FullCodeCharKind::InComment, item));
549                 }
550             }
551             CharClassesStatus::LineComment => 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         Some((FullCodeCharKind::Normal, item))
563     }
564 }
565
566 /// Iterator over functional and commented parts of a string. Any part of a string is either
567 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
568 /// comments is functional code. Line comments contain their ending newlines.
569 struct UngroupedCommentCodeSlices<'a> {
570     slice: &'a str,
571     iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
572 }
573
574 impl<'a> UngroupedCommentCodeSlices<'a> {
575     fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
576         UngroupedCommentCodeSlices {
577             slice: code,
578             iter: CharClasses::new(code.char_indices()).peekable(),
579         }
580     }
581 }
582
583 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
584     type Item = (CodeCharKind, usize, &'a str);
585
586     fn next(&mut self) -> Option<Self::Item> {
587         let (kind, (start_idx, _)) = try_opt!(self.iter.next());
588         match kind {
589             FullCodeCharKind::Normal => {
590                 // Consume all the Normal code
591                 while let Some(&(FullCodeCharKind::Normal, (_, _))) = self.iter.peek() {
592                     let _ = self.iter.next();
593                 }
594             }
595             FullCodeCharKind::StartComment => {
596                 // Consume the whole comment
597                 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
598             }
599             _ => panic!(),
600         }
601         let slice = match self.iter.peek() {
602             Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
603             None => &self.slice[start_idx..],
604         };
605         Some((
606             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
620 /// Iterator over an alternating sequence of functional and commented parts of
621 /// a string. The first item is always a, possibly zero length, subslice of
622 /// functional text. Line style comments contain their ending newlines.
623 pub struct CommentCodeSlices<'a> {
624     slice: &'a str,
625     last_slice_kind: CodeCharKind,
626     last_slice_end: usize,
627 }
628
629 impl<'a> CommentCodeSlices<'a> {
630     pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
631         CommentCodeSlices {
632             slice: slice,
633             last_slice_kind: CodeCharKind::Comment,
634             last_slice_end: 0,
635         }
636     }
637 }
638
639 impl<'a> Iterator for CommentCodeSlices<'a> {
640     type Item = (CodeCharKind, usize, &'a str);
641
642     fn next(&mut self) -> Option<Self::Item> {
643         if self.last_slice_end == self.slice.len() {
644             return None;
645         }
646
647         let mut sub_slice_end = self.last_slice_end;
648         let mut first_whitespace = None;
649         let subslice = &self.slice[self.last_slice_end..];
650         let mut iter = CharClasses::new(subslice.char_indices());
651
652         for (kind, (i, c)) in &mut iter {
653             let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
654                 &subslice[..2] == "//" &&
655                 [' ', '\t'].contains(&c);
656
657             if is_comment_connector && first_whitespace.is_none() {
658                 first_whitespace = Some(i);
659             }
660
661             if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
662                 let last_index = match first_whitespace {
663                     Some(j) => j,
664                     None => i,
665                 };
666                 sub_slice_end = self.last_slice_end + last_index;
667                 break;
668             }
669
670             if !is_comment_connector {
671                 first_whitespace = None;
672             }
673         }
674
675         if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
676             // This was the last subslice.
677             sub_slice_end = match first_whitespace {
678                 Some(i) => self.last_slice_end + i,
679                 None => self.slice.len(),
680             };
681         }
682
683         let kind = match self.last_slice_kind {
684             CodeCharKind::Comment => CodeCharKind::Normal,
685             CodeCharKind::Normal => CodeCharKind::Comment,
686         };
687         let res = (
688             kind,
689             self.last_slice_end,
690             &self.slice[self.last_slice_end..sub_slice_end],
691         );
692         self.last_slice_end = sub_slice_end;
693         self.last_slice_kind = kind;
694
695         Some(res)
696     }
697 }
698
699 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
700 /// (if it fits in the width/offset, else return None), else return `new`
701 pub fn recover_comment_removed(
702     new: String,
703     span: Span,
704     context: &RewriteContext,
705     shape: Shape,
706 ) -> Option<String> {
707     let snippet = context.snippet(span);
708     if changed_comment_content(&snippet, &new) {
709         // We missed some comments
710         // Keep previous formatting if it satisfies the constrains
711         wrap_str(snippet, context.config.max_width(), shape)
712     } else {
713         Some(new)
714     }
715 }
716
717 /// Return true if the two strings of code have the same payload of comments.
718 /// The payload of comments is everything in the string except:
719 ///     - actual code (not comments)
720 ///     - comment start/end marks
721 ///     - whitespace
722 ///     - '*' at the beginning of lines in block comments
723 fn changed_comment_content(orig: &str, new: &str) -> bool {
724     // Cannot write this as a fn since we cannot return types containing closures
725     let code_comment_content = |code| {
726         let slices = UngroupedCommentCodeSlices::new(code);
727         slices
728             .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
729             .flat_map(|(_, _, s)| CommentReducer::new(s))
730     };
731     let res = code_comment_content(orig).ne(code_comment_content(new));
732     debug!(
733         "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
734         res,
735         orig,
736         new,
737         code_comment_content(orig).collect::<String>(),
738         code_comment_content(new).collect::<String>()
739     );
740     res
741 }
742
743
744 /// Iterator over the 'payload' characters of a comment.
745 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
746 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
747 /// for example).
748 struct CommentReducer<'a> {
749     is_block: bool,
750     at_start_line: bool,
751     iter: std::str::Chars<'a>,
752 }
753
754 impl<'a> CommentReducer<'a> {
755     fn new(comment: &'a str) -> CommentReducer<'a> {
756         let is_block = comment.starts_with("/*");
757         let comment = remove_comment_header(comment);
758         CommentReducer {
759             is_block: is_block,
760             at_start_line: false, // There are no supplementary '*' on the first line
761             iter: comment.chars(),
762         }
763     }
764 }
765
766 impl<'a> Iterator for CommentReducer<'a> {
767     type Item = char;
768     fn next(&mut self) -> Option<Self::Item> {
769         loop {
770             let mut c = try_opt!(self.iter.next());
771             if self.is_block && self.at_start_line {
772                 while c.is_whitespace() {
773                     c = try_opt!(self.iter.next());
774                 }
775                 // Ignore leading '*'
776                 if c == '*' {
777                     c = try_opt!(self.iter.next());
778                 }
779             } else {
780                 if c == '\n' {
781                     self.at_start_line = true;
782                 }
783             }
784             if !c.is_whitespace() {
785                 return Some(c);
786             }
787         }
788     }
789 }
790
791
792 fn remove_comment_header(comment: &str) -> &str {
793     if comment.starts_with("///") || comment.starts_with("//!") {
794         &comment[3..]
795     } else if comment.starts_with("//") {
796         &comment[2..]
797     } else if (comment.starts_with("/**") && !comment.starts_with("/**/")) ||
798                comment.starts_with("/*!")
799     {
800         &comment[3..comment.len() - 2]
801     } else {
802         assert!(
803             comment.starts_with("/*"),
804             format!("string '{}' is not a comment", comment)
805         );
806         &comment[2..comment.len() - 2]
807     }
808 }
809
810 #[cfg(test)]
811 mod test {
812     use super::{CharClasses, CodeCharKind, FullCodeCharKind, contains_comment, rewrite_comment,
813                 FindUncommented, CommentCodeSlices};
814     use {Indent, Shape};
815
816     #[test]
817     fn char_classes() {
818         let mut iter = CharClasses::new("//\n\n".chars());
819
820         assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
821         assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
822         assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
823         assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
824         assert_eq!(None, iter.next());
825     }
826
827     #[test]
828     fn comment_code_slices() {
829         let input = "code(); /* test */ 1 + 1";
830         let mut iter = CommentCodeSlices::new(input);
831
832         assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
833         assert_eq!(
834             (CodeCharKind::Comment, 8, "/* test */"),
835             iter.next().unwrap()
836         );
837         assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
838         assert_eq!(None, iter.next());
839     }
840
841     #[test]
842     fn comment_code_slices_two() {
843         let input = "// comment\n    test();";
844         let mut iter = CommentCodeSlices::new(input);
845
846         assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
847         assert_eq!(
848             (CodeCharKind::Comment, 0, "// comment\n"),
849             iter.next().unwrap()
850         );
851         assert_eq!(
852             (CodeCharKind::Normal, 11, "    test();"),
853             iter.next().unwrap()
854         );
855         assert_eq!(None, iter.next());
856     }
857
858     #[test]
859     fn comment_code_slices_three() {
860         let input = "1 // comment\n    // comment2\n\n";
861         let mut iter = CommentCodeSlices::new(input);
862
863         assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
864         assert_eq!(
865             (CodeCharKind::Comment, 2, "// comment\n    // comment2\n"),
866             iter.next().unwrap()
867         );
868         assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
869         assert_eq!(None, iter.next());
870     }
871
872     #[test]
873     #[cfg_attr(rustfmt, rustfmt_skip)]
874     fn format_comments() {
875         let mut config: ::config::Config = Default::default();
876         config.set().wrap_comments(true);
877         config.set().normalize_comments(true);
878
879         let comment = rewrite_comment(" //test",
880                                       true,
881                                       Shape::legacy(100, Indent::new(0, 100)),
882                                       &config).unwrap();
883         assert_eq!("/* test */", comment);
884
885         let comment = rewrite_comment("// comment on a",
886                                       false,
887                                       Shape::legacy(10, Indent::empty()),
888                                       &config).unwrap();
889         assert_eq!("// comment\n// on a", comment);
890
891         let comment = rewrite_comment("//  A multi line comment\n             // between args.",
892                                       false,
893                                       Shape::legacy(60, Indent::new(0, 12)),
894                                       &config).unwrap();
895         assert_eq!("//  A multi line comment\n            // between args.", comment);
896
897         let input = "// comment";
898         let expected =
899             "/* comment */";
900         let comment = rewrite_comment(input,
901                                       true,
902                                       Shape::legacy(9, Indent::new(0, 69)),
903                                       &config).unwrap();
904         assert_eq!(expected, comment);
905
906         let comment = rewrite_comment("/*   trimmed    */",
907                                       true,
908                                       Shape::legacy(100, Indent::new(0, 100)),
909                                       &config).unwrap();
910         assert_eq!("/* trimmed */", comment);
911     }
912
913     // This is probably intended to be a non-test fn, but it is not used. I'm
914     // keeping it around unless it helps us test stuff.
915     fn uncommented(text: &str) -> String {
916         CharClasses::new(text.chars())
917             .filter_map(|(s, c)| match s {
918                 FullCodeCharKind::Normal => Some(c),
919                 _ => None,
920             })
921             .collect()
922     }
923
924     #[test]
925     fn test_uncommented() {
926         assert_eq!(&uncommented("abc/*...*/"), "abc");
927         assert_eq!(
928             &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
929             "..ac\n"
930         );
931         assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
932     }
933
934     #[test]
935     fn test_contains_comment() {
936         assert_eq!(contains_comment("abc"), false);
937         assert_eq!(contains_comment("abc // qsdf"), true);
938         assert_eq!(contains_comment("abc /* kqsdf"), true);
939         assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
940     }
941
942     #[test]
943     fn test_find_uncommented() {
944         fn check(haystack: &str, needle: &str, expected: Option<usize>) {
945             assert_eq!(expected, haystack.find_uncommented(needle));
946         }
947
948         check("/*/ */test", "test", Some(6));
949         check("//test\ntest", "test", Some(7));
950         check("/* comment only */", "whatever", None);
951         check(
952             "/* comment */ some text /* more commentary */ result",
953             "result",
954             Some(46),
955         );
956         check("sup // sup", "p", Some(2));
957         check("sup", "x", None);
958         check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
959         check("/*sup yo? \n sup*/ sup", "p", Some(20));
960         check("hel/*lohello*/lo", "hello", None);
961         check("acb", "ab", None);
962         check(",/*A*/ ", ",", Some(0));
963         check("abc", "abc", Some(0));
964         check("/* abc */", "abc", None);
965         check("/**/abc/* */", "abc", Some(4));
966         check("\"/* abc */\"", "abc", Some(4));
967         check("\"/* abc", "abc", Some(4));
968     }
969 }