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