]> git.lizzy.rs Git - rust.git/blob - src/comment.rs
Add recover_missing_comment_in_span() and rewrite_missing_comment()
[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 /// Given the span, rewrite the missing comment inside it if available.
369 /// Note that the given span must only include comments (or leading/trailing whitespaces).
370 pub fn rewrite_missing_comment(
371     span: Span,
372     shape: Shape,
373     context: &RewriteContext,
374 ) -> Option<String> {
375     let missing_snippet = context.snippet(span);
376     let trimmed_snippet = missing_snippet.trim();
377     if !trimmed_snippet.is_empty() {
378         rewrite_comment(trimmed_snippet, false, shape, context.config)
379     } else {
380         Some(String::new())
381     }
382 }
383
384 /// Recover the missing comments in the specified span, if available.
385 /// The layout of the comments will be preserved as long as it does not break the code
386 /// and its total width does not exceed the max width.
387 pub fn recover_missing_comment_in_span(
388     span: Span,
389     shape: Shape,
390     context: &RewriteContext,
391     used_width: usize,
392 ) -> Option<String> {
393     let missing_comment = try_opt!(rewrite_missing_comment(span, shape, context));
394     if missing_comment.is_empty() {
395         Some(String::new())
396     } else {
397         let missing_snippet = context.snippet(span);
398         let pos = missing_snippet.chars().position(|c| c == '/').unwrap_or(0);
399         // 1 = ` `
400         let total_width = missing_comment.len() + used_width + 1;
401         let force_new_line_before_comment =
402             missing_snippet[..pos].contains('\n') || total_width > context.config.max_width();
403         let sep = if force_new_line_before_comment {
404             format!("\n{}", shape.indent.to_string(context.config))
405         } else {
406             String::from(" ")
407         };
408         Some(format!("{}{}", sep, missing_comment))
409     }
410 }
411
412 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
413 fn light_rewrite_comment(orig: &str, offset: Indent, config: &Config) -> Option<String> {
414     let lines: Vec<&str> = orig.lines()
415         .map(|l| {
416             // This is basically just l.trim(), but in the case that a line starts
417             // with `*` we want to leave one space before it, so it aligns with the
418             // `*` in `/*`.
419             let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
420             if let Some(fnw) = first_non_whitespace {
421                 if l.as_bytes()[fnw] == '*' as u8 && fnw > 0 {
422                     &l[fnw - 1..]
423                 } else {
424                     &l[fnw..]
425                 }
426             } else {
427                 ""
428             }.trim_right()
429         })
430         .collect();
431     Some(lines.join(&format!("\n{}", offset.to_string(config))))
432 }
433
434 /// Trims comment characters and possibly a single space from the left of a string.
435 /// Does not trim all whitespace.
436 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle) -> &'a str {
437     if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") ||
438         line.starts_with("/** ")
439     {
440         &line[4..]
441     } else if let &CommentStyle::Custom(opener) = style {
442         if line.starts_with(opener) {
443             &line[opener.len()..]
444         } else {
445             &line[opener.trim_right().len()..]
446         }
447     } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!") ||
448         line.starts_with("///") || line.starts_with("** ") ||
449         line.starts_with("/*!") ||
450         (line.starts_with("/**") && !line.starts_with("/**/"))
451     {
452         &line[3..]
453     } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") ||
454         line.starts_with("**")
455     {
456         &line[2..]
457     } else if line.starts_with('*') {
458         &line[1..]
459     } else {
460         line
461     }
462 }
463
464 pub trait FindUncommented {
465     fn find_uncommented(&self, pat: &str) -> Option<usize>;
466 }
467
468 impl FindUncommented for str {
469     fn find_uncommented(&self, pat: &str) -> Option<usize> {
470         let mut needle_iter = pat.chars();
471         for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
472             match needle_iter.next() {
473                 None => {
474                     return Some(i - pat.len());
475                 }
476                 Some(c) => match kind {
477                     FullCodeCharKind::Normal if b == c => {}
478                     _ => {
479                         needle_iter = pat.chars();
480                     }
481                 },
482             }
483         }
484
485         // Handle case where the pattern is a suffix of the search string
486         match needle_iter.next() {
487             Some(_) => None,
488             None => Some(self.len() - pat.len()),
489         }
490     }
491 }
492
493 // Returns the first byte position after the first comment. The given string
494 // is expected to be prefixed by a comment, including delimiters.
495 // Good: "/* /* inner */ outer */ code();"
496 // Bad:  "code(); // hello\n world!"
497 pub fn find_comment_end(s: &str) -> Option<usize> {
498     let mut iter = CharClasses::new(s.char_indices());
499     for (kind, (i, _c)) in &mut iter {
500         if kind == FullCodeCharKind::Normal {
501             return Some(i);
502         }
503     }
504
505     // Handle case where the comment ends at the end of s.
506     if iter.status == CharClassesStatus::Normal {
507         Some(s.len())
508     } else {
509         None
510     }
511 }
512
513 /// Returns true if text contains any comment.
514 pub fn contains_comment(text: &str) -> bool {
515     CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
516 }
517
518 struct CharClasses<T>
519 where
520     T: Iterator,
521     T::Item: RichChar,
522 {
523     base: iter::Peekable<T>,
524     status: CharClassesStatus,
525 }
526
527 trait RichChar {
528     fn get_char(&self) -> char;
529 }
530
531 impl RichChar for char {
532     fn get_char(&self) -> char {
533         *self
534     }
535 }
536
537 impl RichChar for (usize, char) {
538     fn get_char(&self) -> char {
539         self.1
540     }
541 }
542
543 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
544 enum CharClassesStatus {
545     Normal,
546     LitString,
547     LitStringEscape,
548     LitChar,
549     LitCharEscape,
550     // The u32 is the nesting deepness of the comment
551     BlockComment(u32),
552     // Status when the '/' has been consumed, but not yet the '*', deepness is
553     // the new deepness (after the comment opening).
554     BlockCommentOpening(u32),
555     // Status when the '*' has been consumed, but not yet the '/', deepness is
556     // the new deepness (after the comment closing).
557     BlockCommentClosing(u32),
558     LineComment,
559 }
560
561 /// Distinguish between functional part of code and comments
562 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
563 pub enum CodeCharKind {
564     Normal,
565     Comment,
566 }
567
568 /// Distinguish between functional part of code and comments,
569 /// describing opening and closing of comments for ease when chunking
570 /// code from tagged characters
571 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
572 enum FullCodeCharKind {
573     Normal,
574     /// The first character of a comment, there is only one for a comment (always '/')
575     StartComment,
576     /// Any character inside a comment including the second character of comment
577     /// marks ("//", "/*")
578     InComment,
579     /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
580     EndComment,
581 }
582
583 impl FullCodeCharKind {
584     fn is_comment(&self) -> bool {
585         match *self {
586             FullCodeCharKind::Normal => false,
587             FullCodeCharKind::StartComment |
588             FullCodeCharKind::InComment |
589             FullCodeCharKind::EndComment => true,
590         }
591     }
592
593     fn to_codecharkind(&self) -> CodeCharKind {
594         if self.is_comment() {
595             CodeCharKind::Comment
596         } else {
597             CodeCharKind::Normal
598         }
599     }
600 }
601
602 impl<T> CharClasses<T>
603 where
604     T: Iterator,
605     T::Item: RichChar,
606 {
607     fn new(base: T) -> CharClasses<T> {
608         CharClasses {
609             base: base.peekable(),
610             status: CharClassesStatus::Normal,
611         }
612     }
613 }
614
615 impl<T> Iterator for CharClasses<T>
616 where
617     T: Iterator,
618     T::Item: RichChar,
619 {
620     type Item = (FullCodeCharKind, T::Item);
621
622     fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
623         let item = try_opt!(self.base.next());
624         let chr = item.get_char();
625         self.status = match self.status {
626             CharClassesStatus::LitString => match chr {
627                 '"' => CharClassesStatus::Normal,
628                 '\\' => CharClassesStatus::LitStringEscape,
629                 _ => CharClassesStatus::LitString,
630             },
631             CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
632             CharClassesStatus::LitChar => match chr {
633                 '\\' => CharClassesStatus::LitCharEscape,
634                 '\'' => CharClassesStatus::Normal,
635                 _ => CharClassesStatus::LitChar,
636             },
637             CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
638             CharClassesStatus::Normal => match chr {
639                 '"' => CharClassesStatus::LitString,
640                 '\'' => CharClassesStatus::LitChar,
641                 '/' => match self.base.peek() {
642                     Some(next) if next.get_char() == '*' => {
643                         self.status = CharClassesStatus::BlockCommentOpening(1);
644                         return Some((FullCodeCharKind::StartComment, item));
645                     }
646                     Some(next) if next.get_char() == '/' => {
647                         self.status = CharClassesStatus::LineComment;
648                         return Some((FullCodeCharKind::StartComment, item));
649                     }
650                     _ => CharClassesStatus::Normal,
651                 },
652                 _ => CharClassesStatus::Normal,
653             },
654             CharClassesStatus::BlockComment(deepness) => {
655                 assert!(deepness != 0);
656                 self.status = match self.base.peek() {
657                     Some(next) if next.get_char() == '/' && chr == '*' => {
658                         CharClassesStatus::BlockCommentClosing(deepness - 1)
659                     }
660                     Some(next) if next.get_char() == '*' && chr == '/' => {
661                         CharClassesStatus::BlockCommentOpening(deepness + 1)
662                     }
663                     _ => CharClassesStatus::BlockComment(deepness),
664                 };
665                 return Some((FullCodeCharKind::InComment, item));
666             }
667             CharClassesStatus::BlockCommentOpening(deepness) => {
668                 assert_eq!(chr, '*');
669                 self.status = CharClassesStatus::BlockComment(deepness);
670                 return Some((FullCodeCharKind::InComment, item));
671             }
672             CharClassesStatus::BlockCommentClosing(deepness) => {
673                 assert_eq!(chr, '/');
674                 if deepness == 0 {
675                     self.status = CharClassesStatus::Normal;
676                     return Some((FullCodeCharKind::EndComment, item));
677                 } else {
678                     self.status = CharClassesStatus::BlockComment(deepness);
679                     return Some((FullCodeCharKind::InComment, item));
680                 }
681             }
682             CharClassesStatus::LineComment => match chr {
683                 '\n' => {
684                     self.status = CharClassesStatus::Normal;
685                     return Some((FullCodeCharKind::EndComment, item));
686                 }
687                 _ => {
688                     self.status = CharClassesStatus::LineComment;
689                     return Some((FullCodeCharKind::InComment, item));
690                 }
691             },
692         };
693         Some((FullCodeCharKind::Normal, item))
694     }
695 }
696
697 /// Iterator over functional and commented parts of a string. Any part of a string is either
698 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
699 /// comments is functional code. Line comments contain their ending newlines.
700 struct UngroupedCommentCodeSlices<'a> {
701     slice: &'a str,
702     iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
703 }
704
705 impl<'a> UngroupedCommentCodeSlices<'a> {
706     fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
707         UngroupedCommentCodeSlices {
708             slice: code,
709             iter: CharClasses::new(code.char_indices()).peekable(),
710         }
711     }
712 }
713
714 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
715     type Item = (CodeCharKind, usize, &'a str);
716
717     fn next(&mut self) -> Option<Self::Item> {
718         let (kind, (start_idx, _)) = try_opt!(self.iter.next());
719         match kind {
720             FullCodeCharKind::Normal => {
721                 // Consume all the Normal code
722                 while let Some(&(FullCodeCharKind::Normal, (_, _))) = self.iter.peek() {
723                     let _ = self.iter.next();
724                 }
725             }
726             FullCodeCharKind::StartComment => {
727                 // Consume the whole comment
728                 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
729             }
730             _ => panic!(),
731         }
732         let slice = match self.iter.peek() {
733             Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
734             None => &self.slice[start_idx..],
735         };
736         Some((
737             if kind.is_comment() {
738                 CodeCharKind::Comment
739             } else {
740                 CodeCharKind::Normal
741             },
742             start_idx,
743             slice,
744         ))
745     }
746 }
747
748
749
750
751 /// Iterator over an alternating sequence of functional and commented parts of
752 /// a string. The first item is always a, possibly zero length, subslice of
753 /// functional text. Line style comments contain their ending newlines.
754 pub struct CommentCodeSlices<'a> {
755     slice: &'a str,
756     last_slice_kind: CodeCharKind,
757     last_slice_end: usize,
758 }
759
760 impl<'a> CommentCodeSlices<'a> {
761     pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
762         CommentCodeSlices {
763             slice: slice,
764             last_slice_kind: CodeCharKind::Comment,
765             last_slice_end: 0,
766         }
767     }
768 }
769
770 impl<'a> Iterator for CommentCodeSlices<'a> {
771     type Item = (CodeCharKind, usize, &'a str);
772
773     fn next(&mut self) -> Option<Self::Item> {
774         if self.last_slice_end == self.slice.len() {
775             return None;
776         }
777
778         let mut sub_slice_end = self.last_slice_end;
779         let mut first_whitespace = None;
780         let subslice = &self.slice[self.last_slice_end..];
781         let mut iter = CharClasses::new(subslice.char_indices());
782
783         for (kind, (i, c)) in &mut iter {
784             let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
785                 &subslice[..2] == "//" &&
786                 [' ', '\t'].contains(&c);
787
788             if is_comment_connector && first_whitespace.is_none() {
789                 first_whitespace = Some(i);
790             }
791
792             if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
793                 let last_index = match first_whitespace {
794                     Some(j) => j,
795                     None => i,
796                 };
797                 sub_slice_end = self.last_slice_end + last_index;
798                 break;
799             }
800
801             if !is_comment_connector {
802                 first_whitespace = None;
803             }
804         }
805
806         if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
807             // This was the last subslice.
808             sub_slice_end = match first_whitespace {
809                 Some(i) => self.last_slice_end + i,
810                 None => self.slice.len(),
811             };
812         }
813
814         let kind = match self.last_slice_kind {
815             CodeCharKind::Comment => CodeCharKind::Normal,
816             CodeCharKind::Normal => CodeCharKind::Comment,
817         };
818         let res = (
819             kind,
820             self.last_slice_end,
821             &self.slice[self.last_slice_end..sub_slice_end],
822         );
823         self.last_slice_end = sub_slice_end;
824         self.last_slice_kind = kind;
825
826         Some(res)
827     }
828 }
829
830 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
831 /// (if it fits in the width/offset, else return None), else return `new`
832 pub fn recover_comment_removed(
833     new: String,
834     span: Span,
835     context: &RewriteContext,
836     shape: Shape,
837 ) -> Option<String> {
838     let snippet = context.snippet(span);
839     if changed_comment_content(&snippet, &new) {
840         // We missed some comments
841         // Keep previous formatting if it satisfies the constrains
842         wrap_str(snippet, context.config.max_width(), shape)
843     } else {
844         Some(new)
845     }
846 }
847
848 /// Return true if the two strings of code have the same payload of comments.
849 /// The payload of comments is everything in the string except:
850 ///     - actual code (not comments)
851 ///     - comment start/end marks
852 ///     - whitespace
853 ///     - '*' at the beginning of lines in block comments
854 fn changed_comment_content(orig: &str, new: &str) -> bool {
855     // Cannot write this as a fn since we cannot return types containing closures
856     let code_comment_content = |code| {
857         let slices = UngroupedCommentCodeSlices::new(code);
858         slices
859             .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
860             .flat_map(|(_, _, s)| CommentReducer::new(s))
861     };
862     let res = code_comment_content(orig).ne(code_comment_content(new));
863     debug!(
864         "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
865         res,
866         orig,
867         new,
868         code_comment_content(orig).collect::<String>(),
869         code_comment_content(new).collect::<String>()
870     );
871     res
872 }
873
874
875 /// Iterator over the 'payload' characters of a comment.
876 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
877 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
878 /// for example).
879 struct CommentReducer<'a> {
880     is_block: bool,
881     at_start_line: bool,
882     iter: std::str::Chars<'a>,
883 }
884
885 impl<'a> CommentReducer<'a> {
886     fn new(comment: &'a str) -> CommentReducer<'a> {
887         let is_block = comment.starts_with("/*");
888         let comment = remove_comment_header(comment);
889         CommentReducer {
890             is_block: is_block,
891             at_start_line: false, // There are no supplementary '*' on the first line
892             iter: comment.chars(),
893         }
894     }
895 }
896
897 impl<'a> Iterator for CommentReducer<'a> {
898     type Item = char;
899     fn next(&mut self) -> Option<Self::Item> {
900         loop {
901             let mut c = try_opt!(self.iter.next());
902             if self.is_block && self.at_start_line {
903                 while c.is_whitespace() {
904                     c = try_opt!(self.iter.next());
905                 }
906                 // Ignore leading '*'
907                 if c == '*' {
908                     c = try_opt!(self.iter.next());
909                 }
910             } else {
911                 if c == '\n' {
912                     self.at_start_line = true;
913                 }
914             }
915             if !c.is_whitespace() {
916                 return Some(c);
917             }
918         }
919     }
920 }
921
922
923 fn remove_comment_header(comment: &str) -> &str {
924     if comment.starts_with("///") || comment.starts_with("//!") {
925         &comment[3..]
926     } else if comment.starts_with("//") {
927         &comment[2..]
928     } else if (comment.starts_with("/**") && !comment.starts_with("/**/")) ||
929         comment.starts_with("/*!")
930     {
931         &comment[3..comment.len() - 2]
932     } else {
933         assert!(
934             comment.starts_with("/*"),
935             format!("string '{}' is not a comment", comment)
936         );
937         &comment[2..comment.len() - 2]
938     }
939 }
940
941 #[cfg(test)]
942 mod test {
943     use super::{contains_comment, rewrite_comment, CharClasses, CodeCharKind, CommentCodeSlices,
944                 FindUncommented, FullCodeCharKind};
945     use {Indent, Shape};
946
947     #[test]
948     fn char_classes() {
949         let mut iter = CharClasses::new("//\n\n".chars());
950
951         assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
952         assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
953         assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
954         assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
955         assert_eq!(None, iter.next());
956     }
957
958     #[test]
959     fn comment_code_slices() {
960         let input = "code(); /* test */ 1 + 1";
961         let mut iter = CommentCodeSlices::new(input);
962
963         assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
964         assert_eq!(
965             (CodeCharKind::Comment, 8, "/* test */"),
966             iter.next().unwrap()
967         );
968         assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
969         assert_eq!(None, iter.next());
970     }
971
972     #[test]
973     fn comment_code_slices_two() {
974         let input = "// comment\n    test();";
975         let mut iter = CommentCodeSlices::new(input);
976
977         assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
978         assert_eq!(
979             (CodeCharKind::Comment, 0, "// comment\n"),
980             iter.next().unwrap()
981         );
982         assert_eq!(
983             (CodeCharKind::Normal, 11, "    test();"),
984             iter.next().unwrap()
985         );
986         assert_eq!(None, iter.next());
987     }
988
989     #[test]
990     fn comment_code_slices_three() {
991         let input = "1 // comment\n    // comment2\n\n";
992         let mut iter = CommentCodeSlices::new(input);
993
994         assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
995         assert_eq!(
996             (CodeCharKind::Comment, 2, "// comment\n    // comment2\n"),
997             iter.next().unwrap()
998         );
999         assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
1000         assert_eq!(None, iter.next());
1001     }
1002
1003     #[test]
1004     #[cfg_attr(rustfmt, rustfmt_skip)]
1005     fn format_comments() {
1006         let mut config: ::config::Config = Default::default();
1007         config.set().wrap_comments(true);
1008         config.set().normalize_comments(true);
1009
1010         let comment = rewrite_comment(" //test",
1011                                       true,
1012                                       Shape::legacy(100, Indent::new(0, 100)),
1013                                       &config).unwrap();
1014         assert_eq!("/* test */", comment);
1015
1016         let comment = rewrite_comment("// comment on a",
1017                                       false,
1018                                       Shape::legacy(10, Indent::empty()),
1019                                       &config).unwrap();
1020         assert_eq!("// comment\n// on a", comment);
1021
1022         let comment = rewrite_comment("//  A multi line comment\n             // between args.",
1023                                       false,
1024                                       Shape::legacy(60, Indent::new(0, 12)),
1025                                       &config).unwrap();
1026         assert_eq!("//  A multi line comment\n            // between args.", comment);
1027
1028         let input = "// comment";
1029         let expected =
1030             "/* comment */";
1031         let comment = rewrite_comment(input,
1032                                       true,
1033                                       Shape::legacy(9, Indent::new(0, 69)),
1034                                       &config).unwrap();
1035         assert_eq!(expected, comment);
1036
1037         let comment = rewrite_comment("/*   trimmed    */",
1038                                       true,
1039                                       Shape::legacy(100, Indent::new(0, 100)),
1040                                       &config).unwrap();
1041         assert_eq!("/* trimmed */", comment);
1042     }
1043
1044     // This is probably intended to be a non-test fn, but it is not used. I'm
1045     // keeping it around unless it helps us test stuff.
1046     fn uncommented(text: &str) -> String {
1047         CharClasses::new(text.chars())
1048             .filter_map(|(s, c)| match s {
1049                 FullCodeCharKind::Normal => Some(c),
1050                 _ => None,
1051             })
1052             .collect()
1053     }
1054
1055     #[test]
1056     fn test_uncommented() {
1057         assert_eq!(&uncommented("abc/*...*/"), "abc");
1058         assert_eq!(
1059             &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
1060             "..ac\n"
1061         );
1062         assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
1063     }
1064
1065     #[test]
1066     fn test_contains_comment() {
1067         assert_eq!(contains_comment("abc"), false);
1068         assert_eq!(contains_comment("abc // qsdf"), true);
1069         assert_eq!(contains_comment("abc /* kqsdf"), true);
1070         assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
1071     }
1072
1073     #[test]
1074     fn test_find_uncommented() {
1075         fn check(haystack: &str, needle: &str, expected: Option<usize>) {
1076             assert_eq!(expected, haystack.find_uncommented(needle));
1077         }
1078
1079         check("/*/ */test", "test", Some(6));
1080         check("//test\ntest", "test", Some(7));
1081         check("/* comment only */", "whatever", None);
1082         check(
1083             "/* comment */ some text /* more commentary */ result",
1084             "result",
1085             Some(46),
1086         );
1087         check("sup // sup", "p", Some(2));
1088         check("sup", "x", None);
1089         check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
1090         check("/*sup yo? \n sup*/ sup", "p", Some(20));
1091         check("hel/*lohello*/lo", "hello", None);
1092         check("acb", "ab", None);
1093         check(",/*A*/ ", ",", Some(0));
1094         check("abc", "abc", Some(0));
1095         check("/* abc */", "abc", None);
1096         check("/**/abc/* */", "abc", Some(4));
1097         check("\"/* abc */\"", "abc", Some(4));
1098         check("\"/* abc", "abc", Some(4));
1099     }
1100 }