]> git.lizzy.rs Git - rust.git/blob - src/comment.rs
Merge pull request #4100 from calebcartwright/rustfmt1x-rustc-v650
[rust.git] / src / comment.rs
1 // Formatting and tools for comments.
2
3 use std::{self, borrow::Cow, iter};
4
5 use itertools::{multipeek, MultiPeek};
6 use rustc_span::Span;
7
8 use crate::config::Config;
9 use crate::rewrite::RewriteContext;
10 use crate::shape::{Indent, Shape};
11 use crate::string::{rewrite_string, StringFormat};
12 use crate::utils::{
13     count_newlines, first_line_width, last_line_width, trim_left_preserve_layout, unicode_str_width,
14 };
15 use crate::{ErrorKind, FormattingError};
16
17 fn is_custom_comment(comment: &str) -> bool {
18     if !comment.starts_with("//") {
19         false
20     } else if let Some(c) = comment.chars().nth(2) {
21         !c.is_alphanumeric() && !c.is_whitespace()
22     } else {
23         false
24     }
25 }
26
27 #[derive(Copy, Clone, PartialEq, Eq)]
28 pub(crate) enum CommentStyle<'a> {
29     DoubleSlash,
30     TripleSlash,
31     Doc,
32     SingleBullet,
33     DoubleBullet,
34     Exclamation,
35     Custom(&'a str),
36 }
37
38 fn custom_opener(s: &str) -> &str {
39     s.lines().next().map_or("", |first_line| {
40         first_line
41             .find(' ')
42             .map_or(first_line, |space_index| &first_line[0..=space_index])
43     })
44 }
45
46 impl<'a> CommentStyle<'a> {
47     /// Returns `true` if the commenting style covers a line only.
48     pub(crate) fn is_line_comment(&self) -> bool {
49         match *self {
50             CommentStyle::DoubleSlash
51             | CommentStyle::TripleSlash
52             | CommentStyle::Doc
53             | CommentStyle::Custom(_) => true,
54             _ => false,
55         }
56     }
57
58     /// Returns `true` if the commenting style can span over multiple lines.
59     pub(crate) fn is_block_comment(&self) -> bool {
60         match *self {
61             CommentStyle::SingleBullet | CommentStyle::DoubleBullet | CommentStyle::Exclamation => {
62                 true
63             }
64             _ => false,
65         }
66     }
67
68     /// Returns `true` if the commenting style is for documentation.
69     pub(crate) fn is_doc_comment(&self) -> bool {
70         match *self {
71             CommentStyle::TripleSlash | CommentStyle::Doc => true,
72             _ => false,
73         }
74     }
75
76     pub(crate) fn opener(&self) -> &'a str {
77         match *self {
78             CommentStyle::DoubleSlash => "// ",
79             CommentStyle::TripleSlash => "/// ",
80             CommentStyle::Doc => "//! ",
81             CommentStyle::SingleBullet => "/* ",
82             CommentStyle::DoubleBullet => "/** ",
83             CommentStyle::Exclamation => "/*! ",
84             CommentStyle::Custom(opener) => opener,
85         }
86     }
87
88     pub(crate) fn closer(&self) -> &'a str {
89         match *self {
90             CommentStyle::DoubleSlash
91             | CommentStyle::TripleSlash
92             | CommentStyle::Custom(..)
93             | CommentStyle::Doc => "",
94             CommentStyle::DoubleBullet => " **/",
95             CommentStyle::SingleBullet | CommentStyle::Exclamation => " */",
96         }
97     }
98
99     pub(crate) fn line_start(&self) -> &'a str {
100         match *self {
101             CommentStyle::DoubleSlash => "// ",
102             CommentStyle::TripleSlash => "/// ",
103             CommentStyle::Doc => "//! ",
104             CommentStyle::SingleBullet | CommentStyle::Exclamation => " * ",
105             CommentStyle::DoubleBullet => " ** ",
106             CommentStyle::Custom(opener) => opener,
107         }
108     }
109
110     pub(crate) fn to_str_tuplet(&self) -> (&'a str, &'a str, &'a str) {
111         (self.opener(), self.closer(), self.line_start())
112     }
113 }
114
115 pub(crate) 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 /// Returns true if the last line of the passed string finishes with a block-comment.
146 pub(crate) fn is_last_comment_block(s: &str) -> bool {
147     s.trim_end().ends_with("*/")
148 }
149
150 /// Combine `prev_str` and `next_str` into a single `String`. `span` may contain
151 /// comments between two strings. If there are such comments, then that will be
152 /// recovered. If `allow_extend` is true and there is no comment between the two
153 /// strings, then they will be put on a single line as long as doing so does not
154 /// exceed max width.
155 pub(crate) fn combine_strs_with_missing_comments(
156     context: &RewriteContext<'_>,
157     prev_str: &str,
158     next_str: &str,
159     span: Span,
160     shape: Shape,
161     allow_extend: bool,
162 ) -> Option<String> {
163     trace!(
164         "combine_strs_with_missing_comments `{}` `{}` {:?} {:?}",
165         prev_str,
166         next_str,
167         span,
168         shape
169     );
170
171     let mut result =
172         String::with_capacity(prev_str.len() + next_str.len() + shape.indent.width() + 128);
173     result.push_str(prev_str);
174     let mut allow_one_line = !prev_str.contains('\n') && !next_str.contains('\n');
175     let first_sep = if prev_str.is_empty() || next_str.is_empty() {
176         ""
177     } else {
178         " "
179     };
180     let mut one_line_width =
181         last_line_width(prev_str) + first_line_width(next_str) + first_sep.len();
182
183     let config = context.config;
184     let indent = shape.indent;
185     let missing_comment = rewrite_missing_comment(span, shape, context)?;
186
187     if missing_comment.is_empty() {
188         if allow_extend && prev_str.len() + first_sep.len() + next_str.len() <= shape.width {
189             result.push_str(first_sep);
190         } else if !prev_str.is_empty() {
191             result.push_str(&indent.to_string_with_newline(config))
192         }
193         result.push_str(next_str);
194         return Some(result);
195     }
196
197     // We have a missing comment between the first expression and the second expression.
198
199     // Peek the the original source code and find out whether there is a newline between the first
200     // expression and the second expression or the missing comment. We will preserve the original
201     // layout whenever possible.
202     let original_snippet = context.snippet(span);
203     let prefer_same_line = if let Some(pos) = original_snippet.find('/') {
204         !original_snippet[..pos].contains('\n')
205     } else {
206         !original_snippet.contains('\n')
207     };
208
209     one_line_width -= first_sep.len();
210     let first_sep = if prev_str.is_empty() || missing_comment.is_empty() {
211         Cow::from("")
212     } else {
213         let one_line_width = last_line_width(prev_str) + first_line_width(&missing_comment) + 1;
214         if prefer_same_line && one_line_width <= shape.width {
215             Cow::from(" ")
216         } else {
217             indent.to_string_with_newline(config)
218         }
219     };
220     result.push_str(&first_sep);
221     result.push_str(&missing_comment);
222
223     let second_sep = if missing_comment.is_empty() || next_str.is_empty() {
224         Cow::from("")
225     } else if missing_comment.starts_with("//") {
226         indent.to_string_with_newline(config)
227     } else {
228         one_line_width += missing_comment.len() + first_sep.len() + 1;
229         allow_one_line &= !missing_comment.starts_with("//") && !missing_comment.contains('\n');
230         if prefer_same_line && allow_one_line && one_line_width <= shape.width {
231             Cow::from(" ")
232         } else {
233             indent.to_string_with_newline(config)
234         }
235     };
236     result.push_str(&second_sep);
237     result.push_str(next_str);
238
239     Some(result)
240 }
241
242 pub(crate) fn rewrite_doc_comment(orig: &str, shape: Shape, config: &Config) -> Option<String> {
243     identify_comment(orig, false, shape, config, true)
244 }
245
246 pub(crate) fn rewrite_comment(
247     orig: &str,
248     block_style: bool,
249     shape: Shape,
250     config: &Config,
251 ) -> Option<String> {
252     identify_comment(orig, block_style, shape, config, false)
253 }
254
255 fn identify_comment(
256     orig: &str,
257     block_style: bool,
258     shape: Shape,
259     config: &Config,
260     is_doc_comment: bool,
261 ) -> Option<String> {
262     let style = comment_style(orig, false);
263
264     // Computes the byte length of line taking into account a newline if the line is part of a
265     // paragraph.
266     fn compute_len(orig: &str, line: &str) -> usize {
267         if orig.len() > line.len() {
268             if orig.as_bytes()[line.len()] == b'\r' {
269                 line.len() + 2
270             } else {
271                 line.len() + 1
272             }
273         } else {
274             line.len()
275         }
276     }
277
278     // Get the first group of line comments having the same commenting style.
279     //
280     // Returns a tuple with:
281     // - a boolean indicating if there is a blank line
282     // - a number indicating the size of the first group of comments
283     fn consume_same_line_comments(
284         style: CommentStyle<'_>,
285         orig: &str,
286         line_start: &str,
287     ) -> (bool, usize) {
288         let mut first_group_ending = 0;
289         let mut hbl = false;
290
291         for line in orig.lines() {
292             let trimmed_line = line.trim_start();
293             if trimmed_line.is_empty() {
294                 hbl = true;
295                 break;
296             } else if trimmed_line.starts_with(line_start)
297                 || comment_style(trimmed_line, false) == style
298             {
299                 first_group_ending += compute_len(&orig[first_group_ending..], line);
300             } else {
301                 break;
302             }
303         }
304         (hbl, first_group_ending)
305     }
306
307     let (has_bare_lines, first_group_ending) = match style {
308         CommentStyle::DoubleSlash | CommentStyle::TripleSlash | CommentStyle::Doc => {
309             let line_start = style.line_start().trim_start();
310             consume_same_line_comments(style, orig, line_start)
311         }
312         CommentStyle::Custom(opener) => {
313             let trimmed_opener = opener.trim_end();
314             consume_same_line_comments(style, orig, trimmed_opener)
315         }
316         // for a block comment, search for the closing symbol
317         CommentStyle::DoubleBullet | CommentStyle::SingleBullet | CommentStyle::Exclamation => {
318             let closer = style.closer().trim_start();
319             let mut count = orig.matches(closer).count();
320             let mut closing_symbol_offset = 0;
321             let mut hbl = false;
322             let mut first = true;
323             for line in orig.lines() {
324                 closing_symbol_offset += compute_len(&orig[closing_symbol_offset..], line);
325                 let mut trimmed_line = line.trim_start();
326                 if !trimmed_line.starts_with('*')
327                     && !trimmed_line.starts_with("//")
328                     && !trimmed_line.starts_with("/*")
329                 {
330                     hbl = true;
331                 }
332
333                 // Remove opener from consideration when searching for closer
334                 if first {
335                     let opener = style.opener().trim_end();
336                     trimmed_line = &trimmed_line[opener.len()..];
337                     first = false;
338                 }
339                 if trimmed_line.ends_with(closer) {
340                     count -= 1;
341                     if count == 0 {
342                         break;
343                     }
344                 }
345             }
346             (hbl, closing_symbol_offset)
347         }
348     };
349
350     let (first_group, rest) = orig.split_at(first_group_ending);
351     let rewritten_first_group =
352         if !config.normalize_comments() && has_bare_lines && style.is_block_comment() {
353             trim_left_preserve_layout(first_group, shape.indent, config)?
354         } else if !config.normalize_comments()
355             && !config.wrap_comments()
356             && !config.format_code_in_doc_comments()
357         {
358             light_rewrite_comment(first_group, shape.indent, config, is_doc_comment)
359         } else {
360             rewrite_comment_inner(
361                 first_group,
362                 block_style,
363                 style,
364                 shape,
365                 config,
366                 is_doc_comment || style.is_doc_comment(),
367             )?
368         };
369     if rest.is_empty() {
370         Some(rewritten_first_group)
371     } else {
372         identify_comment(
373             rest.trim_start(),
374             block_style,
375             shape,
376             config,
377             is_doc_comment,
378         )
379         .map(|rest_str| {
380             format!(
381                 "{}\n{}{}{}",
382                 rewritten_first_group,
383                 // insert back the blank line
384                 if has_bare_lines && style.is_line_comment() {
385                     "\n"
386                 } else {
387                     ""
388                 },
389                 shape.indent.to_string(config),
390                 rest_str
391             )
392         })
393     }
394 }
395
396 /// Attributes for code blocks in rustdoc.
397 /// See https://doc.rust-lang.org/rustdoc/print.html#attributes
398 enum CodeBlockAttribute {
399     Rust,
400     Ignore,
401     Text,
402     ShouldPanic,
403     NoRun,
404     CompileFail,
405 }
406
407 impl CodeBlockAttribute {
408     fn new(attribute: &str) -> CodeBlockAttribute {
409         match attribute {
410             "rust" | "" => CodeBlockAttribute::Rust,
411             "ignore" => CodeBlockAttribute::Ignore,
412             "text" => CodeBlockAttribute::Text,
413             "should_panic" => CodeBlockAttribute::ShouldPanic,
414             "no_run" => CodeBlockAttribute::NoRun,
415             "compile_fail" => CodeBlockAttribute::CompileFail,
416             _ => CodeBlockAttribute::Text,
417         }
418     }
419 }
420
421 /// Block that is formatted as an item.
422 ///
423 /// An item starts with either a star `*` or a dash `-`. Different level of indentation are
424 /// handled by shrinking the shape accordingly.
425 struct ItemizedBlock {
426     /// the lines that are identified as part of an itemized block
427     lines: Vec<String>,
428     /// the number of whitespaces up to the item sigil
429     indent: usize,
430     /// the string that marks the start of an item
431     opener: String,
432     /// sequence of whitespaces to prefix new lines that are part of the item
433     line_start: String,
434 }
435
436 impl ItemizedBlock {
437     /// Returns `true` if the line is formatted as an item
438     fn is_itemized_line(line: &str) -> bool {
439         let trimmed = line.trim_start();
440         trimmed.starts_with("* ") || trimmed.starts_with("- ")
441     }
442
443     /// Creates a new ItemizedBlock described with the given line.
444     /// The `is_itemized_line` needs to be called first.
445     fn new(line: &str) -> ItemizedBlock {
446         let space_to_sigil = line.chars().take_while(|c| c.is_whitespace()).count();
447         let indent = space_to_sigil + 2;
448         ItemizedBlock {
449             lines: vec![line[indent..].to_string()],
450             indent,
451             opener: line[..indent].to_string(),
452             line_start: " ".repeat(indent),
453         }
454     }
455
456     /// Returns a `StringFormat` used for formatting the content of an item.
457     fn create_string_format<'a>(&'a self, fmt: &'a StringFormat<'_>) -> StringFormat<'a> {
458         StringFormat {
459             opener: "",
460             closer: "",
461             line_start: "",
462             line_end: "",
463             shape: Shape::legacy(fmt.shape.width.saturating_sub(self.indent), Indent::empty()),
464             trim_end: true,
465             config: fmt.config,
466         }
467     }
468
469     /// Returns `true` if the line is part of the current itemized block.
470     /// If it is, then it is added to the internal lines list.
471     fn add_line(&mut self, line: &str) -> bool {
472         if !ItemizedBlock::is_itemized_line(line)
473             && self.indent <= line.chars().take_while(|c| c.is_whitespace()).count()
474         {
475             self.lines.push(line.to_string());
476             return true;
477         }
478         false
479     }
480
481     /// Returns the block as a string, with each line trimmed at the start.
482     fn trimmed_block_as_string(&self) -> String {
483         self.lines
484             .iter()
485             .map(|line| format!("{} ", line.trim_start()))
486             .collect::<String>()
487     }
488
489     /// Returns the block as a string under its original form.
490     fn original_block_as_string(&self) -> String {
491         self.lines.join("\n")
492     }
493 }
494
495 struct CommentRewrite<'a> {
496     result: String,
497     code_block_buffer: String,
498     is_prev_line_multi_line: bool,
499     code_block_attr: Option<CodeBlockAttribute>,
500     item_block: Option<ItemizedBlock>,
501     comment_line_separator: String,
502     indent_str: String,
503     max_width: usize,
504     fmt_indent: Indent,
505     fmt: StringFormat<'a>,
506
507     opener: String,
508     closer: String,
509     line_start: String,
510 }
511
512 impl<'a> CommentRewrite<'a> {
513     fn new(
514         orig: &'a str,
515         block_style: bool,
516         shape: Shape,
517         config: &'a Config,
518     ) -> CommentRewrite<'a> {
519         let (opener, closer, line_start) = if block_style {
520             CommentStyle::SingleBullet.to_str_tuplet()
521         } else {
522             comment_style(orig, config.normalize_comments()).to_str_tuplet()
523         };
524
525         let max_width = shape
526             .width
527             .checked_sub(closer.len() + opener.len())
528             .unwrap_or(1);
529         let indent_str = shape.indent.to_string_with_newline(config).to_string();
530         let fmt_indent = shape.indent + (opener.len() - line_start.len());
531
532         let mut cr = CommentRewrite {
533             result: String::with_capacity(orig.len() * 2),
534             code_block_buffer: String::with_capacity(128),
535             is_prev_line_multi_line: false,
536             code_block_attr: None,
537             item_block: None,
538             comment_line_separator: format!("{}{}", indent_str, line_start),
539             max_width,
540             indent_str,
541             fmt_indent,
542
543             fmt: StringFormat {
544                 opener: "",
545                 closer: "",
546                 line_start,
547                 line_end: "",
548                 shape: Shape::legacy(max_width, fmt_indent),
549                 trim_end: true,
550                 config,
551             },
552
553             opener: opener.to_owned(),
554             closer: closer.to_owned(),
555             line_start: line_start.to_owned(),
556         };
557         cr.result.push_str(opener);
558         cr
559     }
560
561     fn join_block(s: &str, sep: &str) -> String {
562         let mut result = String::with_capacity(s.len() + 128);
563         let mut iter = s.lines().peekable();
564         while let Some(line) = iter.next() {
565             result.push_str(line);
566             result.push_str(match iter.peek() {
567                 Some(next_line) if next_line.is_empty() => sep.trim_end(),
568                 Some(..) => &sep,
569                 None => "",
570             });
571         }
572         result
573     }
574
575     fn finish(mut self) -> String {
576         if !self.code_block_buffer.is_empty() {
577             // There is a code block that is not properly enclosed by backticks.
578             // We will leave them untouched.
579             self.result.push_str(&self.comment_line_separator);
580             self.result.push_str(&Self::join_block(
581                 &trim_custom_comment_prefix(&self.code_block_buffer),
582                 &self.comment_line_separator,
583             ));
584         }
585
586         if let Some(ref ib) = self.item_block {
587             // the last few lines are part of an itemized block
588             self.fmt.shape = Shape::legacy(self.max_width, self.fmt_indent);
589             let item_fmt = ib.create_string_format(&self.fmt);
590             self.result.push_str(&self.comment_line_separator);
591             self.result.push_str(&ib.opener);
592             match rewrite_string(
593                 &ib.trimmed_block_as_string(),
594                 &item_fmt,
595                 self.max_width.saturating_sub(ib.indent),
596             ) {
597                 Some(s) => self.result.push_str(&Self::join_block(
598                     &s,
599                     &format!("{}{}", self.comment_line_separator, ib.line_start),
600                 )),
601                 None => self.result.push_str(&Self::join_block(
602                     &ib.original_block_as_string(),
603                     &self.comment_line_separator,
604                 )),
605             };
606         }
607
608         self.result.push_str(&self.closer);
609         if self.result.ends_with(&self.opener) && self.opener.ends_with(' ') {
610             // Trailing space.
611             self.result.pop();
612         }
613
614         self.result
615     }
616
617     fn handle_line(
618         &mut self,
619         orig: &'a str,
620         i: usize,
621         line: &'a str,
622         has_leading_whitespace: bool,
623     ) -> bool {
624         let is_last = i == count_newlines(orig);
625
626         if let Some(ref mut ib) = self.item_block {
627             if ib.add_line(&line) {
628                 return false;
629             }
630             self.is_prev_line_multi_line = false;
631             self.fmt.shape = Shape::legacy(self.max_width, self.fmt_indent);
632             let item_fmt = ib.create_string_format(&self.fmt);
633             self.result.push_str(&self.comment_line_separator);
634             self.result.push_str(&ib.opener);
635             match rewrite_string(
636                 &ib.trimmed_block_as_string(),
637                 &item_fmt,
638                 self.max_width.saturating_sub(ib.indent),
639             ) {
640                 Some(s) => self.result.push_str(&Self::join_block(
641                     &s,
642                     &format!("{}{}", self.comment_line_separator, ib.line_start),
643                 )),
644                 None => self.result.push_str(&Self::join_block(
645                     &ib.original_block_as_string(),
646                     &self.comment_line_separator,
647                 )),
648             };
649         } else if self.code_block_attr.is_some() {
650             if line.starts_with("```") {
651                 let code_block = match self.code_block_attr.as_ref().unwrap() {
652                     CodeBlockAttribute::Ignore | CodeBlockAttribute::Text => {
653                         trim_custom_comment_prefix(&self.code_block_buffer)
654                     }
655                     _ if self.code_block_buffer.is_empty() => String::new(),
656                     _ => {
657                         let mut config = self.fmt.config.clone();
658                         config.set().wrap_comments(false);
659                         if config.format_code_in_doc_comments() {
660                             if let Some(s) =
661                                 crate::format_code_block(&self.code_block_buffer, &config)
662                             {
663                                 trim_custom_comment_prefix(&s.snippet)
664                             } else {
665                                 trim_custom_comment_prefix(&self.code_block_buffer)
666                             }
667                         } else {
668                             trim_custom_comment_prefix(&self.code_block_buffer)
669                         }
670                     }
671                 };
672                 if !code_block.is_empty() {
673                     self.result.push_str(&self.comment_line_separator);
674                     self.result
675                         .push_str(&Self::join_block(&code_block, &self.comment_line_separator));
676                 }
677                 self.code_block_buffer.clear();
678                 self.result.push_str(&self.comment_line_separator);
679                 self.result.push_str(line);
680                 self.code_block_attr = None;
681             } else {
682                 self.code_block_buffer
683                     .push_str(&hide_sharp_behind_comment(line));
684                 self.code_block_buffer.push('\n');
685             }
686             return false;
687         }
688
689         self.code_block_attr = None;
690         self.item_block = None;
691         if line.starts_with("```") {
692             self.code_block_attr = Some(CodeBlockAttribute::new(&line[3..]))
693         } else if self.fmt.config.wrap_comments() && ItemizedBlock::is_itemized_line(&line) {
694             let ib = ItemizedBlock::new(&line);
695             self.item_block = Some(ib);
696             return false;
697         }
698
699         if self.result == self.opener {
700             let force_leading_whitespace = &self.opener == "/* " && count_newlines(orig) == 0;
701             if !has_leading_whitespace && !force_leading_whitespace && self.result.ends_with(' ') {
702                 self.result.pop();
703             }
704             if line.is_empty() {
705                 return false;
706             }
707         } else if self.is_prev_line_multi_line && !line.is_empty() {
708             self.result.push(' ')
709         } else if is_last && line.is_empty() {
710             // trailing blank lines are unwanted
711             if !self.closer.is_empty() {
712                 self.result.push_str(&self.indent_str);
713             }
714             return true;
715         } else {
716             self.result.push_str(&self.comment_line_separator);
717             if !has_leading_whitespace && self.result.ends_with(' ') {
718                 self.result.pop();
719             }
720         }
721
722         if self.fmt.config.wrap_comments()
723             && unicode_str_width(line) > self.fmt.shape.width
724             && !has_url(line)
725         {
726             match rewrite_string(line, &self.fmt, self.max_width) {
727                 Some(ref s) => {
728                     self.is_prev_line_multi_line = s.contains('\n');
729                     self.result.push_str(s);
730                 }
731                 None if self.is_prev_line_multi_line => {
732                     // We failed to put the current `line` next to the previous `line`.
733                     // Remove the trailing space, then start rewrite on the next line.
734                     self.result.pop();
735                     self.result.push_str(&self.comment_line_separator);
736                     self.fmt.shape = Shape::legacy(self.max_width, self.fmt_indent);
737                     match rewrite_string(line, &self.fmt, self.max_width) {
738                         Some(ref s) => {
739                             self.is_prev_line_multi_line = s.contains('\n');
740                             self.result.push_str(s);
741                         }
742                         None => {
743                             self.is_prev_line_multi_line = false;
744                             self.result.push_str(line);
745                         }
746                     }
747                 }
748                 None => {
749                     self.is_prev_line_multi_line = false;
750                     self.result.push_str(line);
751                 }
752             }
753
754             self.fmt.shape = if self.is_prev_line_multi_line {
755                 // 1 = " "
756                 let offset = 1 + last_line_width(&self.result) - self.line_start.len();
757                 Shape {
758                     width: self.max_width.saturating_sub(offset),
759                     indent: self.fmt_indent,
760                     offset: self.fmt.shape.offset + offset,
761                 }
762             } else {
763                 Shape::legacy(self.max_width, self.fmt_indent)
764             };
765         } else {
766             if line.is_empty() && self.result.ends_with(' ') && !is_last {
767                 // Remove space if this is an empty comment or a doc comment.
768                 self.result.pop();
769             }
770             self.result.push_str(line);
771             self.fmt.shape = Shape::legacy(self.max_width, self.fmt_indent);
772             self.is_prev_line_multi_line = false;
773         }
774
775         false
776     }
777 }
778
779 fn rewrite_comment_inner(
780     orig: &str,
781     block_style: bool,
782     style: CommentStyle<'_>,
783     shape: Shape,
784     config: &Config,
785     is_doc_comment: bool,
786 ) -> Option<String> {
787     let mut rewriter = CommentRewrite::new(orig, block_style, shape, config);
788
789     let line_breaks = count_newlines(orig.trim_end());
790     let lines = orig
791         .lines()
792         .enumerate()
793         .map(|(i, mut line)| {
794             line = trim_end_unless_two_whitespaces(line.trim_start(), is_doc_comment);
795             // Drop old closer.
796             if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
797                 line = line[..(line.len() - 2)].trim_end();
798             }
799
800             line
801         })
802         .map(|s| left_trim_comment_line(s, &style))
803         .map(|(line, has_leading_whitespace)| {
804             if orig.starts_with("/*") && line_breaks == 0 {
805                 (
806                     line.trim_start(),
807                     has_leading_whitespace || config.normalize_comments(),
808                 )
809             } else {
810                 (line, has_leading_whitespace || config.normalize_comments())
811             }
812         });
813
814     for (i, (line, has_leading_whitespace)) in lines.enumerate() {
815         if rewriter.handle_line(orig, i, line, has_leading_whitespace) {
816             break;
817         }
818     }
819
820     Some(rewriter.finish())
821 }
822
823 const RUSTFMT_CUSTOM_COMMENT_PREFIX: &str = "//#### ";
824
825 fn hide_sharp_behind_comment(s: &str) -> Cow<'_, str> {
826     let s_trimmed = s.trim();
827     if s_trimmed.starts_with("# ") || s_trimmed == "#" {
828         Cow::from(format!("{}{}", RUSTFMT_CUSTOM_COMMENT_PREFIX, s))
829     } else {
830         Cow::from(s)
831     }
832 }
833
834 fn trim_custom_comment_prefix(s: &str) -> String {
835     s.lines()
836         .map(|line| {
837             let left_trimmed = line.trim_start();
838             if left_trimmed.starts_with(RUSTFMT_CUSTOM_COMMENT_PREFIX) {
839                 left_trimmed.trim_start_matches(RUSTFMT_CUSTOM_COMMENT_PREFIX)
840             } else {
841                 line
842             }
843         })
844         .collect::<Vec<_>>()
845         .join("\n")
846 }
847
848 /// Returns `true` if the given string MAY include URLs or alike.
849 fn has_url(s: &str) -> bool {
850     // This function may return false positive, but should get its job done in most cases.
851     s.contains("https://") || s.contains("http://") || s.contains("ftp://") || s.contains("file://")
852 }
853
854 /// Given the span, rewrite the missing comment inside it if available.
855 /// Note that the given span must only include comments (or leading/trailing whitespaces).
856 pub(crate) fn rewrite_missing_comment(
857     span: Span,
858     shape: Shape,
859     context: &RewriteContext<'_>,
860 ) -> Option<String> {
861     let missing_snippet = context.snippet(span);
862     let trimmed_snippet = missing_snippet.trim();
863     // check the span starts with a comment
864     let pos = trimmed_snippet.find('/');
865     if !trimmed_snippet.is_empty() && pos.is_some() {
866         rewrite_comment(trimmed_snippet, false, shape, context.config)
867     } else {
868         Some(String::new())
869     }
870 }
871
872 /// Recover the missing comments in the specified span, if available.
873 /// The layout of the comments will be preserved as long as it does not break the code
874 /// and its total width does not exceed the max width.
875 pub(crate) fn recover_missing_comment_in_span(
876     span: Span,
877     shape: Shape,
878     context: &RewriteContext<'_>,
879     used_width: usize,
880 ) -> Option<String> {
881     let missing_comment = rewrite_missing_comment(span, shape, context)?;
882     if missing_comment.is_empty() {
883         Some(String::new())
884     } else {
885         let missing_snippet = context.snippet(span);
886         let pos = missing_snippet.find('/')?;
887         // 1 = ` `
888         let total_width = missing_comment.len() + used_width + 1;
889         let force_new_line_before_comment =
890             missing_snippet[..pos].contains('\n') || total_width > context.config.max_width();
891         let sep = if force_new_line_before_comment {
892             shape.indent.to_string_with_newline(context.config)
893         } else {
894             Cow::from(" ")
895         };
896         Some(format!("{}{}", sep, missing_comment))
897     }
898 }
899
900 /// Trim trailing whitespaces unless they consist of two or more whitespaces.
901 fn trim_end_unless_two_whitespaces(s: &str, is_doc_comment: bool) -> &str {
902     if is_doc_comment && s.ends_with("  ") {
903         s
904     } else {
905         s.trim_end()
906     }
907 }
908
909 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
910 fn light_rewrite_comment(
911     orig: &str,
912     offset: Indent,
913     config: &Config,
914     is_doc_comment: bool,
915 ) -> String {
916     let lines: Vec<&str> = orig
917         .lines()
918         .map(|l| {
919             // This is basically just l.trim(), but in the case that a line starts
920             // with `*` we want to leave one space before it, so it aligns with the
921             // `*` in `/*`.
922             let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
923             let left_trimmed = if let Some(fnw) = first_non_whitespace {
924                 if l.as_bytes()[fnw] == b'*' && fnw > 0 {
925                     &l[fnw - 1..]
926                 } else {
927                     &l[fnw..]
928                 }
929             } else {
930                 ""
931             };
932             // Preserve markdown's double-space line break syntax in doc comment.
933             trim_end_unless_two_whitespaces(left_trimmed, is_doc_comment)
934         })
935         .collect();
936     lines.join(&format!("\n{}", offset.to_string(config)))
937 }
938
939 /// Trims comment characters and possibly a single space from the left of a string.
940 /// Does not trim all whitespace. If a single space is trimmed from the left of the string,
941 /// this function returns true.
942 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle<'_>) -> (&'a str, bool) {
943     if line.starts_with("//! ")
944         || line.starts_with("/// ")
945         || line.starts_with("/*! ")
946         || line.starts_with("/** ")
947     {
948         (&line[4..], true)
949     } else if let CommentStyle::Custom(opener) = *style {
950         if line.starts_with(opener) {
951             (&line[opener.len()..], true)
952         } else {
953             (&line[opener.trim_end().len()..], false)
954         }
955     } else if line.starts_with("/* ")
956         || line.starts_with("// ")
957         || line.starts_with("//!")
958         || line.starts_with("///")
959         || line.starts_with("** ")
960         || line.starts_with("/*!")
961         || (line.starts_with("/**") && !line.starts_with("/**/"))
962     {
963         (&line[3..], line.chars().nth(2).unwrap() == ' ')
964     } else if line.starts_with("/*")
965         || line.starts_with("* ")
966         || line.starts_with("//")
967         || line.starts_with("**")
968     {
969         (&line[2..], line.chars().nth(1).unwrap() == ' ')
970     } else if line.starts_with('*') {
971         (&line[1..], false)
972     } else {
973         (line, line.starts_with(' '))
974     }
975 }
976
977 pub(crate) trait FindUncommented {
978     fn find_uncommented(&self, pat: &str) -> Option<usize>;
979 }
980
981 impl FindUncommented for str {
982     fn find_uncommented(&self, pat: &str) -> Option<usize> {
983         let mut needle_iter = pat.chars();
984         for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
985             match needle_iter.next() {
986                 None => {
987                     return Some(i - pat.len());
988                 }
989                 Some(c) => match kind {
990                     FullCodeCharKind::Normal | FullCodeCharKind::InString if b == c => {}
991                     _ => {
992                         needle_iter = pat.chars();
993                     }
994                 },
995             }
996         }
997
998         // Handle case where the pattern is a suffix of the search string
999         match needle_iter.next() {
1000             Some(_) => None,
1001             None => Some(self.len() - pat.len()),
1002         }
1003     }
1004 }
1005
1006 // Returns the first byte position after the first comment. The given string
1007 // is expected to be prefixed by a comment, including delimiters.
1008 // Good: `/* /* inner */ outer */ code();`
1009 // Bad:  `code(); // hello\n world!`
1010 pub(crate) fn find_comment_end(s: &str) -> Option<usize> {
1011     let mut iter = CharClasses::new(s.char_indices());
1012     for (kind, (i, _c)) in &mut iter {
1013         if kind == FullCodeCharKind::Normal || kind == FullCodeCharKind::InString {
1014             return Some(i);
1015         }
1016     }
1017
1018     // Handle case where the comment ends at the end of `s`.
1019     if iter.status == CharClassesStatus::Normal {
1020         Some(s.len())
1021     } else {
1022         None
1023     }
1024 }
1025
1026 /// Returns `true` if text contains any comment.
1027 pub(crate) fn contains_comment(text: &str) -> bool {
1028     CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
1029 }
1030
1031 pub(crate) struct CharClasses<T>
1032 where
1033     T: Iterator,
1034     T::Item: RichChar,
1035 {
1036     base: MultiPeek<T>,
1037     status: CharClassesStatus,
1038 }
1039
1040 pub(crate) trait RichChar {
1041     fn get_char(&self) -> char;
1042 }
1043
1044 impl RichChar for char {
1045     fn get_char(&self) -> char {
1046         *self
1047     }
1048 }
1049
1050 impl RichChar for (usize, char) {
1051     fn get_char(&self) -> char {
1052         self.1
1053     }
1054 }
1055
1056 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
1057 enum CharClassesStatus {
1058     Normal,
1059     /// Character is within a string
1060     LitString,
1061     LitStringEscape,
1062     /// Character is within a raw string
1063     LitRawString(u32),
1064     RawStringPrefix(u32),
1065     RawStringSuffix(u32),
1066     LitChar,
1067     LitCharEscape,
1068     /// Character inside a block comment, with the integer indicating the nesting deepness of the
1069     /// comment
1070     BlockComment(u32),
1071     /// Character inside a block-commented string, with the integer indicating the nesting deepness
1072     /// of the comment
1073     StringInBlockComment(u32),
1074     /// Status when the '/' has been consumed, but not yet the '*', deepness is
1075     /// the new deepness (after the comment opening).
1076     BlockCommentOpening(u32),
1077     /// Status when the '*' has been consumed, but not yet the '/', deepness is
1078     /// the new deepness (after the comment closing).
1079     BlockCommentClosing(u32),
1080     /// Character is within a line comment
1081     LineComment,
1082 }
1083
1084 /// Distinguish between functional part of code and comments
1085 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
1086 pub(crate) enum CodeCharKind {
1087     Normal,
1088     Comment,
1089 }
1090
1091 /// Distinguish between functional part of code and comments,
1092 /// describing opening and closing of comments for ease when chunking
1093 /// code from tagged characters
1094 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
1095 pub(crate) enum FullCodeCharKind {
1096     Normal,
1097     /// The first character of a comment, there is only one for a comment (always '/')
1098     StartComment,
1099     /// Any character inside a comment including the second character of comment
1100     /// marks ("//", "/*")
1101     InComment,
1102     /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
1103     EndComment,
1104     /// Start of a mutlitine string inside a comment
1105     StartStringCommented,
1106     /// End of a mutlitine string inside a comment
1107     EndStringCommented,
1108     /// Inside a commented string
1109     InStringCommented,
1110     /// Start of a mutlitine string
1111     StartString,
1112     /// End of a mutlitine string
1113     EndString,
1114     /// Inside a string.
1115     InString,
1116 }
1117
1118 impl FullCodeCharKind {
1119     pub(crate) fn is_comment(self) -> bool {
1120         match self {
1121             FullCodeCharKind::StartComment
1122             | FullCodeCharKind::InComment
1123             | FullCodeCharKind::EndComment
1124             | FullCodeCharKind::StartStringCommented
1125             | FullCodeCharKind::InStringCommented
1126             | FullCodeCharKind::EndStringCommented => true,
1127             _ => false,
1128         }
1129     }
1130
1131     /// Returns true if the character is inside a comment
1132     pub(crate) fn inside_comment(self) -> bool {
1133         match self {
1134             FullCodeCharKind::InComment
1135             | FullCodeCharKind::StartStringCommented
1136             | FullCodeCharKind::InStringCommented
1137             | FullCodeCharKind::EndStringCommented => true,
1138             _ => false,
1139         }
1140     }
1141
1142     pub(crate) fn is_string(self) -> bool {
1143         self == FullCodeCharKind::InString || self == FullCodeCharKind::StartString
1144     }
1145
1146     /// Returns true if the character is within a commented string
1147     pub(crate) fn is_commented_string(self) -> bool {
1148         self == FullCodeCharKind::InStringCommented
1149             || self == FullCodeCharKind::StartStringCommented
1150     }
1151
1152     fn to_codecharkind(self) -> CodeCharKind {
1153         if self.is_comment() {
1154             CodeCharKind::Comment
1155         } else {
1156             CodeCharKind::Normal
1157         }
1158     }
1159 }
1160
1161 impl<T> CharClasses<T>
1162 where
1163     T: Iterator,
1164     T::Item: RichChar,
1165 {
1166     pub(crate) fn new(base: T) -> CharClasses<T> {
1167         CharClasses {
1168             base: multipeek(base),
1169             status: CharClassesStatus::Normal,
1170         }
1171     }
1172 }
1173
1174 fn is_raw_string_suffix<T>(iter: &mut MultiPeek<T>, count: u32) -> bool
1175 where
1176     T: Iterator,
1177     T::Item: RichChar,
1178 {
1179     for _ in 0..count {
1180         match iter.peek() {
1181             Some(c) if c.get_char() == '#' => continue,
1182             _ => return false,
1183         }
1184     }
1185     true
1186 }
1187
1188 impl<T> Iterator for CharClasses<T>
1189 where
1190     T: Iterator,
1191     T::Item: RichChar,
1192 {
1193     type Item = (FullCodeCharKind, T::Item);
1194
1195     fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
1196         let item = self.base.next()?;
1197         let chr = item.get_char();
1198         let mut char_kind = FullCodeCharKind::Normal;
1199         self.status = match self.status {
1200             CharClassesStatus::LitRawString(sharps) => {
1201                 char_kind = FullCodeCharKind::InString;
1202                 match chr {
1203                     '"' => {
1204                         if sharps == 0 {
1205                             char_kind = FullCodeCharKind::Normal;
1206                             CharClassesStatus::Normal
1207                         } else if is_raw_string_suffix(&mut self.base, sharps) {
1208                             CharClassesStatus::RawStringSuffix(sharps)
1209                         } else {
1210                             CharClassesStatus::LitRawString(sharps)
1211                         }
1212                     }
1213                     _ => CharClassesStatus::LitRawString(sharps),
1214                 }
1215             }
1216             CharClassesStatus::RawStringPrefix(sharps) => {
1217                 char_kind = FullCodeCharKind::InString;
1218                 match chr {
1219                     '#' => CharClassesStatus::RawStringPrefix(sharps + 1),
1220                     '"' => CharClassesStatus::LitRawString(sharps),
1221                     _ => CharClassesStatus::Normal, // Unreachable.
1222                 }
1223             }
1224             CharClassesStatus::RawStringSuffix(sharps) => {
1225                 match chr {
1226                     '#' => {
1227                         if sharps == 1 {
1228                             CharClassesStatus::Normal
1229                         } else {
1230                             char_kind = FullCodeCharKind::InString;
1231                             CharClassesStatus::RawStringSuffix(sharps - 1)
1232                         }
1233                     }
1234                     _ => CharClassesStatus::Normal, // Unreachable
1235                 }
1236             }
1237             CharClassesStatus::LitString => {
1238                 char_kind = FullCodeCharKind::InString;
1239                 match chr {
1240                     '"' => CharClassesStatus::Normal,
1241                     '\\' => CharClassesStatus::LitStringEscape,
1242                     _ => CharClassesStatus::LitString,
1243                 }
1244             }
1245             CharClassesStatus::LitStringEscape => {
1246                 char_kind = FullCodeCharKind::InString;
1247                 CharClassesStatus::LitString
1248             }
1249             CharClassesStatus::LitChar => match chr {
1250                 '\\' => CharClassesStatus::LitCharEscape,
1251                 '\'' => CharClassesStatus::Normal,
1252                 _ => CharClassesStatus::LitChar,
1253             },
1254             CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
1255             CharClassesStatus::Normal => match chr {
1256                 'r' => match self.base.peek().map(RichChar::get_char) {
1257                     Some('#') | Some('"') => {
1258                         char_kind = FullCodeCharKind::InString;
1259                         CharClassesStatus::RawStringPrefix(0)
1260                     }
1261                     _ => CharClassesStatus::Normal,
1262                 },
1263                 '"' => {
1264                     char_kind = FullCodeCharKind::InString;
1265                     CharClassesStatus::LitString
1266                 }
1267                 '\'' => {
1268                     // HACK: Work around mut borrow.
1269                     match self.base.peek() {
1270                         Some(next) if next.get_char() == '\\' => {
1271                             self.status = CharClassesStatus::LitChar;
1272                             return Some((char_kind, item));
1273                         }
1274                         _ => (),
1275                     }
1276
1277                     match self.base.peek() {
1278                         Some(next) if next.get_char() == '\'' => CharClassesStatus::LitChar,
1279                         _ => CharClassesStatus::Normal,
1280                     }
1281                 }
1282                 '/' => match self.base.peek() {
1283                     Some(next) if next.get_char() == '*' => {
1284                         self.status = CharClassesStatus::BlockCommentOpening(1);
1285                         return Some((FullCodeCharKind::StartComment, item));
1286                     }
1287                     Some(next) if next.get_char() == '/' => {
1288                         self.status = CharClassesStatus::LineComment;
1289                         return Some((FullCodeCharKind::StartComment, item));
1290                     }
1291                     _ => CharClassesStatus::Normal,
1292                 },
1293                 _ => CharClassesStatus::Normal,
1294             },
1295             CharClassesStatus::StringInBlockComment(deepness) => {
1296                 char_kind = FullCodeCharKind::InStringCommented;
1297                 if chr == '"' {
1298                     CharClassesStatus::BlockComment(deepness)
1299                 } else {
1300                     CharClassesStatus::StringInBlockComment(deepness)
1301                 }
1302             }
1303             CharClassesStatus::BlockComment(deepness) => {
1304                 assert_ne!(deepness, 0);
1305                 char_kind = FullCodeCharKind::InComment;
1306                 match self.base.peek() {
1307                     Some(next) if next.get_char() == '/' && chr == '*' => {
1308                         CharClassesStatus::BlockCommentClosing(deepness - 1)
1309                     }
1310                     Some(next) if next.get_char() == '*' && chr == '/' => {
1311                         CharClassesStatus::BlockCommentOpening(deepness + 1)
1312                     }
1313                     _ if chr == '"' => CharClassesStatus::StringInBlockComment(deepness),
1314                     _ => self.status,
1315                 }
1316             }
1317             CharClassesStatus::BlockCommentOpening(deepness) => {
1318                 assert_eq!(chr, '*');
1319                 self.status = CharClassesStatus::BlockComment(deepness);
1320                 return Some((FullCodeCharKind::InComment, item));
1321             }
1322             CharClassesStatus::BlockCommentClosing(deepness) => {
1323                 assert_eq!(chr, '/');
1324                 if deepness == 0 {
1325                     self.status = CharClassesStatus::Normal;
1326                     return Some((FullCodeCharKind::EndComment, item));
1327                 } else {
1328                     self.status = CharClassesStatus::BlockComment(deepness);
1329                     return Some((FullCodeCharKind::InComment, item));
1330                 }
1331             }
1332             CharClassesStatus::LineComment => match chr {
1333                 '\n' => {
1334                     self.status = CharClassesStatus::Normal;
1335                     return Some((FullCodeCharKind::EndComment, item));
1336                 }
1337                 _ => {
1338                     self.status = CharClassesStatus::LineComment;
1339                     return Some((FullCodeCharKind::InComment, item));
1340                 }
1341             },
1342         };
1343         Some((char_kind, item))
1344     }
1345 }
1346
1347 /// An iterator over the lines of a string, paired with the char kind at the
1348 /// end of the line.
1349 pub(crate) struct LineClasses<'a> {
1350     base: iter::Peekable<CharClasses<std::str::Chars<'a>>>,
1351     kind: FullCodeCharKind,
1352 }
1353
1354 impl<'a> LineClasses<'a> {
1355     pub(crate) fn new(s: &'a str) -> Self {
1356         LineClasses {
1357             base: CharClasses::new(s.chars()).peekable(),
1358             kind: FullCodeCharKind::Normal,
1359         }
1360     }
1361 }
1362
1363 impl<'a> Iterator for LineClasses<'a> {
1364     type Item = (FullCodeCharKind, String);
1365
1366     fn next(&mut self) -> Option<Self::Item> {
1367         self.base.peek()?;
1368
1369         let mut line = String::new();
1370
1371         let start_kind = match self.base.peek() {
1372             Some((kind, _)) => *kind,
1373             None => unreachable!(),
1374         };
1375
1376         while let Some((kind, c)) = self.base.next() {
1377             // needed to set the kind of the ending character on the last line
1378             self.kind = kind;
1379             if c == '\n' {
1380                 self.kind = match (start_kind, kind) {
1381                     (FullCodeCharKind::Normal, FullCodeCharKind::InString) => {
1382                         FullCodeCharKind::StartString
1383                     }
1384                     (FullCodeCharKind::InString, FullCodeCharKind::Normal) => {
1385                         FullCodeCharKind::EndString
1386                     }
1387                     (FullCodeCharKind::InComment, FullCodeCharKind::InStringCommented) => {
1388                         FullCodeCharKind::StartStringCommented
1389                     }
1390                     (FullCodeCharKind::InStringCommented, FullCodeCharKind::InComment) => {
1391                         FullCodeCharKind::EndStringCommented
1392                     }
1393                     _ => kind,
1394                 };
1395                 break;
1396             }
1397             line.push(c);
1398         }
1399
1400         // Workaround for CRLF newline.
1401         if line.ends_with('\r') {
1402             line.pop();
1403         }
1404
1405         Some((self.kind, line))
1406     }
1407 }
1408
1409 /// Iterator over functional and commented parts of a string. Any part of a string is either
1410 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
1411 /// comments is functional code. Line comments contain their ending newlines.
1412 struct UngroupedCommentCodeSlices<'a> {
1413     slice: &'a str,
1414     iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
1415 }
1416
1417 impl<'a> UngroupedCommentCodeSlices<'a> {
1418     fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
1419         UngroupedCommentCodeSlices {
1420             slice: code,
1421             iter: CharClasses::new(code.char_indices()).peekable(),
1422         }
1423     }
1424 }
1425
1426 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
1427     type Item = (CodeCharKind, usize, &'a str);
1428
1429     fn next(&mut self) -> Option<Self::Item> {
1430         let (kind, (start_idx, _)) = self.iter.next()?;
1431         match kind {
1432             FullCodeCharKind::Normal | FullCodeCharKind::InString => {
1433                 // Consume all the Normal code
1434                 while let Some(&(char_kind, _)) = self.iter.peek() {
1435                     if char_kind.is_comment() {
1436                         break;
1437                     }
1438                     let _ = self.iter.next();
1439                 }
1440             }
1441             FullCodeCharKind::StartComment => {
1442                 // Consume the whole comment
1443                 loop {
1444                     match self.iter.next() {
1445                         Some((kind, ..)) if kind.inside_comment() => continue,
1446                         _ => break,
1447                     }
1448                 }
1449             }
1450             _ => panic!(),
1451         }
1452         let slice = match self.iter.peek() {
1453             Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
1454             None => &self.slice[start_idx..],
1455         };
1456         Some((
1457             if kind.is_comment() {
1458                 CodeCharKind::Comment
1459             } else {
1460                 CodeCharKind::Normal
1461             },
1462             start_idx,
1463             slice,
1464         ))
1465     }
1466 }
1467
1468 /// Iterator over an alternating sequence of functional and commented parts of
1469 /// a string. The first item is always a, possibly zero length, subslice of
1470 /// functional text. Line style comments contain their ending newlines.
1471 pub(crate) struct CommentCodeSlices<'a> {
1472     slice: &'a str,
1473     last_slice_kind: CodeCharKind,
1474     last_slice_end: usize,
1475 }
1476
1477 impl<'a> CommentCodeSlices<'a> {
1478     pub(crate) fn new(slice: &'a str) -> CommentCodeSlices<'a> {
1479         CommentCodeSlices {
1480             slice,
1481             last_slice_kind: CodeCharKind::Comment,
1482             last_slice_end: 0,
1483         }
1484     }
1485 }
1486
1487 impl<'a> Iterator for CommentCodeSlices<'a> {
1488     type Item = (CodeCharKind, usize, &'a str);
1489
1490     fn next(&mut self) -> Option<Self::Item> {
1491         if self.last_slice_end == self.slice.len() {
1492             return None;
1493         }
1494
1495         let mut sub_slice_end = self.last_slice_end;
1496         let mut first_whitespace = None;
1497         let subslice = &self.slice[self.last_slice_end..];
1498         let mut iter = CharClasses::new(subslice.char_indices());
1499
1500         for (kind, (i, c)) in &mut iter {
1501             let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal
1502                 && &subslice[..2] == "//"
1503                 && [' ', '\t'].contains(&c);
1504
1505             if is_comment_connector && first_whitespace.is_none() {
1506                 first_whitespace = Some(i);
1507             }
1508
1509             if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
1510                 let last_index = match first_whitespace {
1511                     Some(j) => j,
1512                     None => i,
1513                 };
1514                 sub_slice_end = self.last_slice_end + last_index;
1515                 break;
1516             }
1517
1518             if !is_comment_connector {
1519                 first_whitespace = None;
1520             }
1521         }
1522
1523         if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
1524             // This was the last subslice.
1525             sub_slice_end = match first_whitespace {
1526                 Some(i) => self.last_slice_end + i,
1527                 None => self.slice.len(),
1528             };
1529         }
1530
1531         let kind = match self.last_slice_kind {
1532             CodeCharKind::Comment => CodeCharKind::Normal,
1533             CodeCharKind::Normal => CodeCharKind::Comment,
1534         };
1535         let res = (
1536             kind,
1537             self.last_slice_end,
1538             &self.slice[self.last_slice_end..sub_slice_end],
1539         );
1540         self.last_slice_end = sub_slice_end;
1541         self.last_slice_kind = kind;
1542
1543         Some(res)
1544     }
1545 }
1546
1547 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
1548 /// (if it fits in the width/offset, else return `None`), else return `new`
1549 pub(crate) fn recover_comment_removed(
1550     new: String,
1551     span: Span,
1552     context: &RewriteContext<'_>,
1553 ) -> Option<String> {
1554     let snippet = context.snippet(span);
1555     if snippet != new && changed_comment_content(snippet, &new) {
1556         // We missed some comments. Warn and keep the original text.
1557         if context.config.error_on_unformatted() {
1558             context.report.append(
1559                 context.parse_sess.span_to_filename(span),
1560                 vec![FormattingError::from_span(
1561                     span,
1562                     &context.parse_sess,
1563                     ErrorKind::LostComment,
1564                 )],
1565             );
1566         }
1567         Some(snippet.to_owned())
1568     } else {
1569         Some(new)
1570     }
1571 }
1572
1573 pub(crate) fn filter_normal_code(code: &str) -> String {
1574     let mut buffer = String::with_capacity(code.len());
1575     LineClasses::new(code).for_each(|(kind, line)| match kind {
1576         FullCodeCharKind::Normal
1577         | FullCodeCharKind::StartString
1578         | FullCodeCharKind::InString
1579         | FullCodeCharKind::EndString => {
1580             buffer.push_str(&line);
1581             buffer.push('\n');
1582         }
1583         _ => (),
1584     });
1585     if !code.ends_with('\n') && buffer.ends_with('\n') {
1586         buffer.pop();
1587     }
1588     buffer
1589 }
1590
1591 /// Returns `true` if the two strings of code have the same payload of comments.
1592 /// The payload of comments is everything in the string except:
1593 /// - actual code (not comments),
1594 /// - comment start/end marks,
1595 /// - whitespace,
1596 /// - '*' at the beginning of lines in block comments.
1597 fn changed_comment_content(orig: &str, new: &str) -> bool {
1598     // Cannot write this as a fn since we cannot return types containing closures.
1599     let code_comment_content = |code| {
1600         let slices = UngroupedCommentCodeSlices::new(code);
1601         slices
1602             .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
1603             .flat_map(|(_, _, s)| CommentReducer::new(s))
1604     };
1605     let res = code_comment_content(orig).ne(code_comment_content(new));
1606     debug!(
1607         "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
1608         res,
1609         orig,
1610         new,
1611         code_comment_content(orig).collect::<String>(),
1612         code_comment_content(new).collect::<String>()
1613     );
1614     res
1615 }
1616
1617 /// Iterator over the 'payload' characters of a comment.
1618 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
1619 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
1620 /// for example).
1621 struct CommentReducer<'a> {
1622     is_block: bool,
1623     at_start_line: bool,
1624     iter: std::str::Chars<'a>,
1625 }
1626
1627 impl<'a> CommentReducer<'a> {
1628     fn new(comment: &'a str) -> CommentReducer<'a> {
1629         let is_block = comment.starts_with("/*");
1630         let comment = remove_comment_header(comment);
1631         CommentReducer {
1632             is_block,
1633             // There are no supplementary '*' on the first line.
1634             at_start_line: false,
1635             iter: comment.chars(),
1636         }
1637     }
1638 }
1639
1640 impl<'a> Iterator for CommentReducer<'a> {
1641     type Item = char;
1642
1643     fn next(&mut self) -> Option<Self::Item> {
1644         loop {
1645             let mut c = self.iter.next()?;
1646             if self.is_block && self.at_start_line {
1647                 while c.is_whitespace() {
1648                     c = self.iter.next()?;
1649                 }
1650                 // Ignore leading '*'.
1651                 if c == '*' {
1652                     c = self.iter.next()?;
1653                 }
1654             } else if c == '\n' {
1655                 self.at_start_line = true;
1656             }
1657             if !c.is_whitespace() {
1658                 return Some(c);
1659             }
1660         }
1661     }
1662 }
1663
1664 fn remove_comment_header(comment: &str) -> &str {
1665     if comment.starts_with("///") || comment.starts_with("//!") {
1666         &comment[3..]
1667     } else if comment.starts_with("//") {
1668         &comment[2..]
1669     } else if (comment.starts_with("/**") && !comment.starts_with("/**/"))
1670         || comment.starts_with("/*!")
1671     {
1672         &comment[3..comment.len() - 2]
1673     } else {
1674         assert!(
1675             comment.starts_with("/*"),
1676             format!("string '{}' is not a comment", comment)
1677         );
1678         &comment[2..comment.len() - 2]
1679     }
1680 }
1681
1682 #[cfg(test)]
1683 mod test {
1684     use super::*;
1685     use crate::shape::{Indent, Shape};
1686
1687     #[test]
1688     fn char_classes() {
1689         let mut iter = CharClasses::new("//\n\n".chars());
1690
1691         assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
1692         assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
1693         assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
1694         assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
1695         assert_eq!(None, iter.next());
1696     }
1697
1698     #[test]
1699     fn comment_code_slices() {
1700         let input = "code(); /* test */ 1 + 1";
1701         let mut iter = CommentCodeSlices::new(input);
1702
1703         assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
1704         assert_eq!(
1705             (CodeCharKind::Comment, 8, "/* test */"),
1706             iter.next().unwrap()
1707         );
1708         assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
1709         assert_eq!(None, iter.next());
1710     }
1711
1712     #[test]
1713     fn comment_code_slices_two() {
1714         let input = "// comment\n    test();";
1715         let mut iter = CommentCodeSlices::new(input);
1716
1717         assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
1718         assert_eq!(
1719             (CodeCharKind::Comment, 0, "// comment\n"),
1720             iter.next().unwrap()
1721         );
1722         assert_eq!(
1723             (CodeCharKind::Normal, 11, "    test();"),
1724             iter.next().unwrap()
1725         );
1726         assert_eq!(None, iter.next());
1727     }
1728
1729     #[test]
1730     fn comment_code_slices_three() {
1731         let input = "1 // comment\n    // comment2\n\n";
1732         let mut iter = CommentCodeSlices::new(input);
1733
1734         assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
1735         assert_eq!(
1736             (CodeCharKind::Comment, 2, "// comment\n    // comment2\n"),
1737             iter.next().unwrap()
1738         );
1739         assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
1740         assert_eq!(None, iter.next());
1741     }
1742
1743     #[test]
1744     #[rustfmt::skip]
1745     fn format_doc_comments() {
1746         let mut wrap_normalize_config: crate::config::Config = Default::default();
1747         wrap_normalize_config.set().wrap_comments(true);
1748         wrap_normalize_config.set().normalize_comments(true);
1749
1750         let mut wrap_config: crate::config::Config = Default::default();
1751         wrap_config.set().wrap_comments(true);
1752
1753         let comment = rewrite_comment(" //test",
1754                                       true,
1755                                       Shape::legacy(100, Indent::new(0, 100)),
1756                                       &wrap_normalize_config).unwrap();
1757         assert_eq!("/* test */", comment);
1758
1759         let comment = rewrite_comment("// comment on a",
1760                                       false,
1761                                       Shape::legacy(10, Indent::empty()),
1762                                       &wrap_normalize_config).unwrap();
1763         assert_eq!("// comment\n// on a", comment);
1764
1765         let comment = rewrite_comment("//  A multi line comment\n             // between args.",
1766                                       false,
1767                                       Shape::legacy(60, Indent::new(0, 12)),
1768                                       &wrap_normalize_config).unwrap();
1769         assert_eq!("//  A multi line comment\n            // between args.", comment);
1770
1771         let input = "// comment";
1772         let expected =
1773             "/* comment */";
1774         let comment = rewrite_comment(input,
1775                                       true,
1776                                       Shape::legacy(9, Indent::new(0, 69)),
1777                                       &wrap_normalize_config).unwrap();
1778         assert_eq!(expected, comment);
1779
1780         let comment = rewrite_comment("/*   trimmed    */",
1781                                       true,
1782                                       Shape::legacy(100, Indent::new(0, 100)),
1783                                       &wrap_normalize_config).unwrap();
1784         assert_eq!("/* trimmed */", comment);
1785
1786         // Check that different comment style are properly recognised.
1787         let comment = rewrite_comment(r#"/// test1
1788                                          /// test2
1789                                          /*
1790                                           * test3
1791                                           */"#,
1792                                       false,
1793                                       Shape::legacy(100, Indent::new(0, 0)),
1794                                       &wrap_normalize_config).unwrap();
1795         assert_eq!("/// test1\n/// test2\n// test3", comment);
1796
1797         // Check that the blank line marks the end of a commented paragraph.
1798         let comment = rewrite_comment(r#"// test1
1799
1800                                          // test2"#,
1801                                       false,
1802                                       Shape::legacy(100, Indent::new(0, 0)),
1803                                       &wrap_normalize_config).unwrap();
1804         assert_eq!("// test1\n\n// test2", comment);
1805
1806         // Check that the blank line marks the end of a custom-commented paragraph.
1807         let comment = rewrite_comment(r#"//@ test1
1808
1809                                          //@ test2"#,
1810                                       false,
1811                                       Shape::legacy(100, Indent::new(0, 0)),
1812                                       &wrap_normalize_config).unwrap();
1813         assert_eq!("//@ test1\n\n//@ test2", comment);
1814
1815         // Check that bare lines are just indented but otherwise left unchanged.
1816         let comment = rewrite_comment(r#"// test1
1817                                          /*
1818                                            a bare line!
1819
1820                                                 another bare line!
1821                                           */"#,
1822                                       false,
1823                                       Shape::legacy(100, Indent::new(0, 0)),
1824                                       &wrap_config).unwrap();
1825         assert_eq!("// test1\n/*\n a bare line!\n\n      another bare line!\n*/", comment);
1826     }
1827
1828     // This is probably intended to be a non-test fn, but it is not used.
1829     // We should keep this around unless it helps us test stuff to remove it.
1830     fn uncommented(text: &str) -> String {
1831         CharClasses::new(text.chars())
1832             .filter_map(|(s, c)| match s {
1833                 FullCodeCharKind::Normal | FullCodeCharKind::InString => Some(c),
1834                 _ => None,
1835             })
1836             .collect()
1837     }
1838
1839     #[test]
1840     fn test_uncommented() {
1841         assert_eq!(&uncommented("abc/*...*/"), "abc");
1842         assert_eq!(
1843             &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
1844             "..ac\n"
1845         );
1846         assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
1847     }
1848
1849     #[test]
1850     fn test_contains_comment() {
1851         assert_eq!(contains_comment("abc"), false);
1852         assert_eq!(contains_comment("abc // qsdf"), true);
1853         assert_eq!(contains_comment("abc /* kqsdf"), true);
1854         assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
1855     }
1856
1857     #[test]
1858     fn test_find_uncommented() {
1859         fn check(haystack: &str, needle: &str, expected: Option<usize>) {
1860             assert_eq!(expected, haystack.find_uncommented(needle));
1861         }
1862
1863         check("/*/ */test", "test", Some(6));
1864         check("//test\ntest", "test", Some(7));
1865         check("/* comment only */", "whatever", None);
1866         check(
1867             "/* comment */ some text /* more commentary */ result",
1868             "result",
1869             Some(46),
1870         );
1871         check("sup // sup", "p", Some(2));
1872         check("sup", "x", None);
1873         check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
1874         check("/*sup yo? \n sup*/ sup", "p", Some(20));
1875         check("hel/*lohello*/lo", "hello", None);
1876         check("acb", "ab", None);
1877         check(",/*A*/ ", ",", Some(0));
1878         check("abc", "abc", Some(0));
1879         check("/* abc */", "abc", None);
1880         check("/**/abc/* */", "abc", Some(4));
1881         check("\"/* abc */\"", "abc", Some(4));
1882         check("\"/* abc", "abc", Some(4));
1883     }
1884
1885     #[test]
1886     fn test_filter_normal_code() {
1887         let s = r#"
1888 fn main() {
1889     println!("hello, world");
1890 }
1891 "#;
1892         assert_eq!(s, filter_normal_code(s));
1893         let s_with_comment = r#"
1894 fn main() {
1895     // hello, world
1896     println!("hello, world");
1897 }
1898 "#;
1899         assert_eq!(s, filter_normal_code(s_with_comment));
1900     }
1901 }