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