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