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