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