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