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