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