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