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