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