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