]> git.lizzy.rs Git - rust.git/blob - src/comment.rs
Revert "Revert "Change config option from format_doc_comments to format_code_in_doc_c...
[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 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 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 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 fn is_doc_comment(&self) -> bool {
70         match *self {
71             CommentStyle::TripleSlash | CommentStyle::Doc => true,
72             _ => false,
73         }
74     }
75
76     pub 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 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 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 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 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 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 fn rewrite_doc_comment(orig: &str, shape: Shape, config: &Config) -> Option<String> {
243     identify_comment(orig, false, shape, config, true)
244 }
245
246 pub 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 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     if !trimmed_snippet.is_empty() {
863         rewrite_comment(trimmed_snippet, false, shape, context.config)
864     } else {
865         Some(String::new())
866     }
867 }
868
869 /// Recover the missing comments in the specified span, if available.
870 /// The layout of the comments will be preserved as long as it does not break the code
871 /// and its total width does not exceed the max width.
872 pub fn recover_missing_comment_in_span(
873     span: Span,
874     shape: Shape,
875     context: &RewriteContext<'_>,
876     used_width: usize,
877 ) -> Option<String> {
878     let missing_comment = rewrite_missing_comment(span, shape, context)?;
879     if missing_comment.is_empty() {
880         Some(String::new())
881     } else {
882         let missing_snippet = context.snippet(span);
883         let pos = missing_snippet.find('/').unwrap_or(0);
884         // 1 = ` `
885         let total_width = missing_comment.len() + used_width + 1;
886         let force_new_line_before_comment =
887             missing_snippet[..pos].contains('\n') || total_width > context.config.max_width();
888         let sep = if force_new_line_before_comment {
889             shape.indent.to_string_with_newline(context.config)
890         } else {
891             Cow::from(" ")
892         };
893         Some(format!("{}{}", sep, missing_comment))
894     }
895 }
896
897 /// Trim trailing whitespaces unless they consist of two or more whitespaces.
898 fn trim_end_unless_two_whitespaces(s: &str, is_doc_comment: bool) -> &str {
899     if is_doc_comment && s.ends_with("  ") {
900         s
901     } else {
902         s.trim_end()
903     }
904 }
905
906 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
907 fn light_rewrite_comment(
908     orig: &str,
909     offset: Indent,
910     config: &Config,
911     is_doc_comment: bool,
912 ) -> String {
913     let lines: Vec<&str> = orig
914         .lines()
915         .map(|l| {
916             // This is basically just l.trim(), but in the case that a line starts
917             // with `*` we want to leave one space before it, so it aligns with the
918             // `*` in `/*`.
919             let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
920             let left_trimmed = if let Some(fnw) = first_non_whitespace {
921                 if l.as_bytes()[fnw] == b'*' && fnw > 0 {
922                     &l[fnw - 1..]
923                 } else {
924                     &l[fnw..]
925                 }
926             } else {
927                 ""
928             };
929             // Preserve markdown's double-space line break syntax in doc comment.
930             trim_end_unless_two_whitespaces(left_trimmed, is_doc_comment)
931         })
932         .collect();
933     lines.join(&format!("\n{}", offset.to_string(config)))
934 }
935
936 /// Trims comment characters and possibly a single space from the left of a string.
937 /// Does not trim all whitespace. If a single space is trimmed from the left of the string,
938 /// this function returns true.
939 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle<'_>) -> (&'a str, bool) {
940     if line.starts_with("//! ")
941         || line.starts_with("/// ")
942         || line.starts_with("/*! ")
943         || line.starts_with("/** ")
944     {
945         (&line[4..], true)
946     } else if let CommentStyle::Custom(opener) = *style {
947         if line.starts_with(opener) {
948             (&line[opener.len()..], true)
949         } else {
950             (&line[opener.trim_end().len()..], false)
951         }
952     } else if line.starts_with("/* ")
953         || line.starts_with("// ")
954         || line.starts_with("//!")
955         || line.starts_with("///")
956         || line.starts_with("** ")
957         || line.starts_with("/*!")
958         || (line.starts_with("/**") && !line.starts_with("/**/"))
959     {
960         (&line[3..], line.chars().nth(2).unwrap() == ' ')
961     } else if line.starts_with("/*")
962         || line.starts_with("* ")
963         || line.starts_with("//")
964         || line.starts_with("**")
965     {
966         (&line[2..], line.chars().nth(1).unwrap() == ' ')
967     } else if line.starts_with('*') {
968         (&line[1..], false)
969     } else {
970         (line, line.starts_with(' '))
971     }
972 }
973
974 pub trait FindUncommented {
975     fn find_uncommented(&self, pat: &str) -> Option<usize>;
976 }
977
978 impl FindUncommented for str {
979     fn find_uncommented(&self, pat: &str) -> Option<usize> {
980         let mut needle_iter = pat.chars();
981         for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
982             match needle_iter.next() {
983                 None => {
984                     return Some(i - pat.len());
985                 }
986                 Some(c) => match kind {
987                     FullCodeCharKind::Normal | FullCodeCharKind::InString if b == c => {}
988                     _ => {
989                         needle_iter = pat.chars();
990                     }
991                 },
992             }
993         }
994
995         // Handle case where the pattern is a suffix of the search string
996         match needle_iter.next() {
997             Some(_) => None,
998             None => Some(self.len() - pat.len()),
999         }
1000     }
1001 }
1002
1003 // Returns the first byte position after the first comment. The given string
1004 // is expected to be prefixed by a comment, including delimiters.
1005 // Good: `/* /* inner */ outer */ code();`
1006 // Bad:  `code(); // hello\n world!`
1007 pub fn find_comment_end(s: &str) -> Option<usize> {
1008     let mut iter = CharClasses::new(s.char_indices());
1009     for (kind, (i, _c)) in &mut iter {
1010         if kind == FullCodeCharKind::Normal || kind == FullCodeCharKind::InString {
1011             return Some(i);
1012         }
1013     }
1014
1015     // Handle case where the comment ends at the end of `s`.
1016     if iter.status == CharClassesStatus::Normal {
1017         Some(s.len())
1018     } else {
1019         None
1020     }
1021 }
1022
1023 /// Returns `true` if text contains any comment.
1024 pub fn contains_comment(text: &str) -> bool {
1025     CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
1026 }
1027
1028 pub struct CharClasses<T>
1029 where
1030     T: Iterator,
1031     T::Item: RichChar,
1032 {
1033     base: MultiPeek<T>,
1034     status: CharClassesStatus,
1035 }
1036
1037 pub trait RichChar {
1038     fn get_char(&self) -> char;
1039 }
1040
1041 impl RichChar for char {
1042     fn get_char(&self) -> char {
1043         *self
1044     }
1045 }
1046
1047 impl RichChar for (usize, char) {
1048     fn get_char(&self) -> char {
1049         self.1
1050     }
1051 }
1052
1053 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
1054 enum CharClassesStatus {
1055     Normal,
1056     /// Character is within a string
1057     LitString,
1058     LitStringEscape,
1059     /// Character is within a raw string
1060     LitRawString(u32),
1061     RawStringPrefix(u32),
1062     RawStringSuffix(u32),
1063     LitChar,
1064     LitCharEscape,
1065     /// Character inside a block comment, with the integer indicating the nesting deepness of the
1066     /// comment
1067     BlockComment(u32),
1068     /// Character inside a block-commented string, with the integer indicating the nesting deepness
1069     /// of the comment
1070     StringInBlockComment(u32),
1071     /// Status when the '/' has been consumed, but not yet the '*', deepness is
1072     /// the new deepness (after the comment opening).
1073     BlockCommentOpening(u32),
1074     /// Status when the '*' has been consumed, but not yet the '/', deepness is
1075     /// the new deepness (after the comment closing).
1076     BlockCommentClosing(u32),
1077     /// Character is within a line comment
1078     LineComment,
1079 }
1080
1081 /// Distinguish between functional part of code and comments
1082 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
1083 pub enum CodeCharKind {
1084     Normal,
1085     Comment,
1086 }
1087
1088 /// Distinguish between functional part of code and comments,
1089 /// describing opening and closing of comments for ease when chunking
1090 /// code from tagged characters
1091 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
1092 pub enum FullCodeCharKind {
1093     Normal,
1094     /// The first character of a comment, there is only one for a comment (always '/')
1095     StartComment,
1096     /// Any character inside a comment including the second character of comment
1097     /// marks ("//", "/*")
1098     InComment,
1099     /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
1100     EndComment,
1101     /// Start of a mutlitine string inside a comment
1102     StartStringCommented,
1103     /// End of a mutlitine string inside a comment
1104     EndStringCommented,
1105     /// Inside a commented string
1106     InStringCommented,
1107     /// Start of a mutlitine string
1108     StartString,
1109     /// End of a mutlitine string
1110     EndString,
1111     /// Inside a string.
1112     InString,
1113 }
1114
1115 impl FullCodeCharKind {
1116     pub fn is_comment(self) -> bool {
1117         match self {
1118             FullCodeCharKind::StartComment
1119             | FullCodeCharKind::InComment
1120             | FullCodeCharKind::EndComment
1121             | FullCodeCharKind::StartStringCommented
1122             | FullCodeCharKind::InStringCommented
1123             | FullCodeCharKind::EndStringCommented => true,
1124             _ => false,
1125         }
1126     }
1127
1128     /// Returns true if the character is inside a comment
1129     pub fn inside_comment(self) -> bool {
1130         match self {
1131             FullCodeCharKind::InComment
1132             | FullCodeCharKind::StartStringCommented
1133             | FullCodeCharKind::InStringCommented
1134             | FullCodeCharKind::EndStringCommented => true,
1135             _ => false,
1136         }
1137     }
1138
1139     pub fn is_string(self) -> bool {
1140         self == FullCodeCharKind::InString || self == FullCodeCharKind::StartString
1141     }
1142
1143     /// Returns true if the character is within a commented string
1144     pub fn is_commented_string(self) -> bool {
1145         self == FullCodeCharKind::InStringCommented
1146             || self == FullCodeCharKind::StartStringCommented
1147     }
1148
1149     fn to_codecharkind(self) -> CodeCharKind {
1150         if self.is_comment() {
1151             CodeCharKind::Comment
1152         } else {
1153             CodeCharKind::Normal
1154         }
1155     }
1156 }
1157
1158 impl<T> CharClasses<T>
1159 where
1160     T: Iterator,
1161     T::Item: RichChar,
1162 {
1163     pub fn new(base: T) -> CharClasses<T> {
1164         CharClasses {
1165             base: multipeek(base),
1166             status: CharClassesStatus::Normal,
1167         }
1168     }
1169 }
1170
1171 fn is_raw_string_suffix<T>(iter: &mut MultiPeek<T>, count: u32) -> bool
1172 where
1173     T: Iterator,
1174     T::Item: RichChar,
1175 {
1176     for _ in 0..count {
1177         match iter.peek() {
1178             Some(c) if c.get_char() == '#' => continue,
1179             _ => return false,
1180         }
1181     }
1182     true
1183 }
1184
1185 impl<T> Iterator for CharClasses<T>
1186 where
1187     T: Iterator,
1188     T::Item: RichChar,
1189 {
1190     type Item = (FullCodeCharKind, T::Item);
1191
1192     fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
1193         let item = self.base.next()?;
1194         let chr = item.get_char();
1195         let mut char_kind = FullCodeCharKind::Normal;
1196         self.status = match self.status {
1197             CharClassesStatus::LitRawString(sharps) => {
1198                 char_kind = FullCodeCharKind::InString;
1199                 match chr {
1200                     '"' => {
1201                         if sharps == 0 {
1202                             char_kind = FullCodeCharKind::Normal;
1203                             CharClassesStatus::Normal
1204                         } else if is_raw_string_suffix(&mut self.base, sharps) {
1205                             CharClassesStatus::RawStringSuffix(sharps)
1206                         } else {
1207                             CharClassesStatus::LitRawString(sharps)
1208                         }
1209                     }
1210                     _ => CharClassesStatus::LitRawString(sharps),
1211                 }
1212             }
1213             CharClassesStatus::RawStringPrefix(sharps) => {
1214                 char_kind = FullCodeCharKind::InString;
1215                 match chr {
1216                     '#' => CharClassesStatus::RawStringPrefix(sharps + 1),
1217                     '"' => CharClassesStatus::LitRawString(sharps),
1218                     _ => CharClassesStatus::Normal, // Unreachable.
1219                 }
1220             }
1221             CharClassesStatus::RawStringSuffix(sharps) => {
1222                 match chr {
1223                     '#' => {
1224                         if sharps == 1 {
1225                             CharClassesStatus::Normal
1226                         } else {
1227                             char_kind = FullCodeCharKind::InString;
1228                             CharClassesStatus::RawStringSuffix(sharps - 1)
1229                         }
1230                     }
1231                     _ => CharClassesStatus::Normal, // Unreachable
1232                 }
1233             }
1234             CharClassesStatus::LitString => {
1235                 char_kind = FullCodeCharKind::InString;
1236                 match chr {
1237                     '"' => CharClassesStatus::Normal,
1238                     '\\' => CharClassesStatus::LitStringEscape,
1239                     _ => CharClassesStatus::LitString,
1240                 }
1241             }
1242             CharClassesStatus::LitStringEscape => {
1243                 char_kind = FullCodeCharKind::InString;
1244                 CharClassesStatus::LitString
1245             }
1246             CharClassesStatus::LitChar => match chr {
1247                 '\\' => CharClassesStatus::LitCharEscape,
1248                 '\'' => CharClassesStatus::Normal,
1249                 _ => CharClassesStatus::LitChar,
1250             },
1251             CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
1252             CharClassesStatus::Normal => match chr {
1253                 'r' => match self.base.peek().map(RichChar::get_char) {
1254                     Some('#') | Some('"') => {
1255                         char_kind = FullCodeCharKind::InString;
1256                         CharClassesStatus::RawStringPrefix(0)
1257                     }
1258                     _ => CharClassesStatus::Normal,
1259                 },
1260                 '"' => {
1261                     char_kind = FullCodeCharKind::InString;
1262                     CharClassesStatus::LitString
1263                 }
1264                 '\'' => {
1265                     // HACK: Work around mut borrow.
1266                     match self.base.peek() {
1267                         Some(next) if next.get_char() == '\\' => {
1268                             self.status = CharClassesStatus::LitChar;
1269                             return Some((char_kind, item));
1270                         }
1271                         _ => (),
1272                     }
1273
1274                     match self.base.peek() {
1275                         Some(next) if next.get_char() == '\'' => CharClassesStatus::LitChar,
1276                         _ => CharClassesStatus::Normal,
1277                     }
1278                 }
1279                 '/' => match self.base.peek() {
1280                     Some(next) if next.get_char() == '*' => {
1281                         self.status = CharClassesStatus::BlockCommentOpening(1);
1282                         return Some((FullCodeCharKind::StartComment, item));
1283                     }
1284                     Some(next) if next.get_char() == '/' => {
1285                         self.status = CharClassesStatus::LineComment;
1286                         return Some((FullCodeCharKind::StartComment, item));
1287                     }
1288                     _ => CharClassesStatus::Normal,
1289                 },
1290                 _ => CharClassesStatus::Normal,
1291             },
1292             CharClassesStatus::StringInBlockComment(deepness) => {
1293                 char_kind = FullCodeCharKind::InStringCommented;
1294                 if chr == '"' {
1295                     CharClassesStatus::BlockComment(deepness)
1296                 } else {
1297                     CharClassesStatus::StringInBlockComment(deepness)
1298                 }
1299             }
1300             CharClassesStatus::BlockComment(deepness) => {
1301                 assert_ne!(deepness, 0);
1302                 char_kind = FullCodeCharKind::InComment;
1303                 match self.base.peek() {
1304                     Some(next) if next.get_char() == '/' && chr == '*' => {
1305                         CharClassesStatus::BlockCommentClosing(deepness - 1)
1306                     }
1307                     Some(next) if next.get_char() == '*' && chr == '/' => {
1308                         CharClassesStatus::BlockCommentOpening(deepness + 1)
1309                     }
1310                     _ if chr == '"' => CharClassesStatus::StringInBlockComment(deepness),
1311                     _ => self.status,
1312                 }
1313             }
1314             CharClassesStatus::BlockCommentOpening(deepness) => {
1315                 assert_eq!(chr, '*');
1316                 self.status = CharClassesStatus::BlockComment(deepness);
1317                 return Some((FullCodeCharKind::InComment, item));
1318             }
1319             CharClassesStatus::BlockCommentClosing(deepness) => {
1320                 assert_eq!(chr, '/');
1321                 if deepness == 0 {
1322                     self.status = CharClassesStatus::Normal;
1323                     return Some((FullCodeCharKind::EndComment, item));
1324                 } else {
1325                     self.status = CharClassesStatus::BlockComment(deepness);
1326                     return Some((FullCodeCharKind::InComment, item));
1327                 }
1328             }
1329             CharClassesStatus::LineComment => match chr {
1330                 '\n' => {
1331                     self.status = CharClassesStatus::Normal;
1332                     return Some((FullCodeCharKind::EndComment, item));
1333                 }
1334                 _ => {
1335                     self.status = CharClassesStatus::LineComment;
1336                     return Some((FullCodeCharKind::InComment, item));
1337                 }
1338             },
1339         };
1340         Some((char_kind, item))
1341     }
1342 }
1343
1344 /// An iterator over the lines of a string, paired with the char kind at the
1345 /// end of the line.
1346 pub struct LineClasses<'a> {
1347     base: iter::Peekable<CharClasses<std::str::Chars<'a>>>,
1348     kind: FullCodeCharKind,
1349 }
1350
1351 impl<'a> LineClasses<'a> {
1352     pub fn new(s: &'a str) -> Self {
1353         LineClasses {
1354             base: CharClasses::new(s.chars()).peekable(),
1355             kind: FullCodeCharKind::Normal,
1356         }
1357     }
1358 }
1359
1360 impl<'a> Iterator for LineClasses<'a> {
1361     type Item = (FullCodeCharKind, String);
1362
1363     fn next(&mut self) -> Option<Self::Item> {
1364         self.base.peek()?;
1365
1366         let mut line = String::new();
1367
1368         let start_kind = match self.base.peek() {
1369             Some((kind, _)) => *kind,
1370             None => unreachable!(),
1371         };
1372
1373         while let Some((kind, c)) = self.base.next() {
1374             // needed to set the kind of the ending character on the last line
1375             self.kind = kind;
1376             if c == '\n' {
1377                 self.kind = match (start_kind, kind) {
1378                     (FullCodeCharKind::Normal, FullCodeCharKind::InString) => {
1379                         FullCodeCharKind::StartString
1380                     }
1381                     (FullCodeCharKind::InString, FullCodeCharKind::Normal) => {
1382                         FullCodeCharKind::EndString
1383                     }
1384                     (FullCodeCharKind::InComment, FullCodeCharKind::InStringCommented) => {
1385                         FullCodeCharKind::StartStringCommented
1386                     }
1387                     (FullCodeCharKind::InStringCommented, FullCodeCharKind::InComment) => {
1388                         FullCodeCharKind::EndStringCommented
1389                     }
1390                     _ => kind,
1391                 };
1392                 break;
1393             }
1394             line.push(c);
1395         }
1396
1397         // Workaround for CRLF newline.
1398         if line.ends_with('\r') {
1399             line.pop();
1400         }
1401
1402         Some((self.kind, line))
1403     }
1404 }
1405
1406 /// Iterator over functional and commented parts of a string. Any part of a string is either
1407 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
1408 /// comments is functional code. Line comments contain their ending newlines.
1409 struct UngroupedCommentCodeSlices<'a> {
1410     slice: &'a str,
1411     iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
1412 }
1413
1414 impl<'a> UngroupedCommentCodeSlices<'a> {
1415     fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
1416         UngroupedCommentCodeSlices {
1417             slice: code,
1418             iter: CharClasses::new(code.char_indices()).peekable(),
1419         }
1420     }
1421 }
1422
1423 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
1424     type Item = (CodeCharKind, usize, &'a str);
1425
1426     fn next(&mut self) -> Option<Self::Item> {
1427         let (kind, (start_idx, _)) = self.iter.next()?;
1428         match kind {
1429             FullCodeCharKind::Normal | FullCodeCharKind::InString => {
1430                 // Consume all the Normal code
1431                 while let Some(&(char_kind, _)) = self.iter.peek() {
1432                     if char_kind.is_comment() {
1433                         break;
1434                     }
1435                     let _ = self.iter.next();
1436                 }
1437             }
1438             FullCodeCharKind::StartComment => {
1439                 // Consume the whole comment
1440                 loop {
1441                     match self.iter.next() {
1442                         Some((kind, ..)) if kind.inside_comment() => continue,
1443                         _ => break,
1444                     }
1445                 }
1446             }
1447             _ => panic!(),
1448         }
1449         let slice = match self.iter.peek() {
1450             Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
1451             None => &self.slice[start_idx..],
1452         };
1453         Some((
1454             if kind.is_comment() {
1455                 CodeCharKind::Comment
1456             } else {
1457                 CodeCharKind::Normal
1458             },
1459             start_idx,
1460             slice,
1461         ))
1462     }
1463 }
1464
1465 /// Iterator over an alternating sequence of functional and commented parts of
1466 /// a string. The first item is always a, possibly zero length, subslice of
1467 /// functional text. Line style comments contain their ending newlines.
1468 pub struct CommentCodeSlices<'a> {
1469     slice: &'a str,
1470     last_slice_kind: CodeCharKind,
1471     last_slice_end: usize,
1472 }
1473
1474 impl<'a> CommentCodeSlices<'a> {
1475     pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
1476         CommentCodeSlices {
1477             slice,
1478             last_slice_kind: CodeCharKind::Comment,
1479             last_slice_end: 0,
1480         }
1481     }
1482 }
1483
1484 impl<'a> Iterator for CommentCodeSlices<'a> {
1485     type Item = (CodeCharKind, usize, &'a str);
1486
1487     fn next(&mut self) -> Option<Self::Item> {
1488         if self.last_slice_end == self.slice.len() {
1489             return None;
1490         }
1491
1492         let mut sub_slice_end = self.last_slice_end;
1493         let mut first_whitespace = None;
1494         let subslice = &self.slice[self.last_slice_end..];
1495         let mut iter = CharClasses::new(subslice.char_indices());
1496
1497         for (kind, (i, c)) in &mut iter {
1498             let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal
1499                 && &subslice[..2] == "//"
1500                 && [' ', '\t'].contains(&c);
1501
1502             if is_comment_connector && first_whitespace.is_none() {
1503                 first_whitespace = Some(i);
1504             }
1505
1506             if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
1507                 let last_index = match first_whitespace {
1508                     Some(j) => j,
1509                     None => i,
1510                 };
1511                 sub_slice_end = self.last_slice_end + last_index;
1512                 break;
1513             }
1514
1515             if !is_comment_connector {
1516                 first_whitespace = None;
1517             }
1518         }
1519
1520         if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
1521             // This was the last subslice.
1522             sub_slice_end = match first_whitespace {
1523                 Some(i) => self.last_slice_end + i,
1524                 None => self.slice.len(),
1525             };
1526         }
1527
1528         let kind = match self.last_slice_kind {
1529             CodeCharKind::Comment => CodeCharKind::Normal,
1530             CodeCharKind::Normal => CodeCharKind::Comment,
1531         };
1532         let res = (
1533             kind,
1534             self.last_slice_end,
1535             &self.slice[self.last_slice_end..sub_slice_end],
1536         );
1537         self.last_slice_end = sub_slice_end;
1538         self.last_slice_kind = kind;
1539
1540         Some(res)
1541     }
1542 }
1543
1544 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
1545 /// (if it fits in the width/offset, else return `None`), else return `new`
1546 pub fn recover_comment_removed(
1547     new: String,
1548     span: Span,
1549     context: &RewriteContext<'_>,
1550 ) -> Option<String> {
1551     let snippet = context.snippet(span);
1552     if snippet != new && changed_comment_content(snippet, &new) {
1553         // We missed some comments. Warn and keep the original text.
1554         if context.config.error_on_unformatted() {
1555             context.report.append(
1556                 context.source_map.span_to_filename(span).into(),
1557                 vec![FormattingError::from_span(
1558                     span,
1559                     &context.source_map,
1560                     ErrorKind::LostComment,
1561                 )],
1562             );
1563         }
1564         Some(snippet.to_owned())
1565     } else {
1566         Some(new)
1567     }
1568 }
1569
1570 pub fn filter_normal_code(code: &str) -> String {
1571     let mut buffer = String::with_capacity(code.len());
1572     LineClasses::new(code).for_each(|(kind, line)| match kind {
1573         FullCodeCharKind::Normal
1574         | FullCodeCharKind::StartString
1575         | FullCodeCharKind::InString
1576         | FullCodeCharKind::EndString => {
1577             buffer.push_str(&line);
1578             buffer.push('\n');
1579         }
1580         _ => (),
1581     });
1582     if !code.ends_with('\n') && buffer.ends_with('\n') {
1583         buffer.pop();
1584     }
1585     buffer
1586 }
1587
1588 /// Returns `true` if the two strings of code have the same payload of comments.
1589 /// The payload of comments is everything in the string except:
1590 /// - actual code (not comments),
1591 /// - comment start/end marks,
1592 /// - whitespace,
1593 /// - '*' at the beginning of lines in block comments.
1594 fn changed_comment_content(orig: &str, new: &str) -> bool {
1595     // Cannot write this as a fn since we cannot return types containing closures.
1596     let code_comment_content = |code| {
1597         let slices = UngroupedCommentCodeSlices::new(code);
1598         slices
1599             .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
1600             .flat_map(|(_, _, s)| CommentReducer::new(s))
1601     };
1602     let res = code_comment_content(orig).ne(code_comment_content(new));
1603     debug!(
1604         "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
1605         res,
1606         orig,
1607         new,
1608         code_comment_content(orig).collect::<String>(),
1609         code_comment_content(new).collect::<String>()
1610     );
1611     res
1612 }
1613
1614 /// Iterator over the 'payload' characters of a comment.
1615 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
1616 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
1617 /// for example).
1618 struct CommentReducer<'a> {
1619     is_block: bool,
1620     at_start_line: bool,
1621     iter: std::str::Chars<'a>,
1622 }
1623
1624 impl<'a> CommentReducer<'a> {
1625     fn new(comment: &'a str) -> CommentReducer<'a> {
1626         let is_block = comment.starts_with("/*");
1627         let comment = remove_comment_header(comment);
1628         CommentReducer {
1629             is_block,
1630             // There are no supplementary '*' on the first line.
1631             at_start_line: false,
1632             iter: comment.chars(),
1633         }
1634     }
1635 }
1636
1637 impl<'a> Iterator for CommentReducer<'a> {
1638     type Item = char;
1639
1640     fn next(&mut self) -> Option<Self::Item> {
1641         loop {
1642             let mut c = self.iter.next()?;
1643             if self.is_block && self.at_start_line {
1644                 while c.is_whitespace() {
1645                     c = self.iter.next()?;
1646                 }
1647                 // Ignore leading '*'.
1648                 if c == '*' {
1649                     c = self.iter.next()?;
1650                 }
1651             } else if c == '\n' {
1652                 self.at_start_line = true;
1653             }
1654             if !c.is_whitespace() {
1655                 return Some(c);
1656             }
1657         }
1658     }
1659 }
1660
1661 fn remove_comment_header(comment: &str) -> &str {
1662     if comment.starts_with("///") || comment.starts_with("//!") {
1663         &comment[3..]
1664     } else if comment.starts_with("//") {
1665         &comment[2..]
1666     } else if (comment.starts_with("/**") && !comment.starts_with("/**/"))
1667         || comment.starts_with("/*!")
1668     {
1669         &comment[3..comment.len() - 2]
1670     } else {
1671         assert!(
1672             comment.starts_with("/*"),
1673             format!("string '{}' is not a comment", comment)
1674         );
1675         &comment[2..comment.len() - 2]
1676     }
1677 }
1678
1679 #[cfg(test)]
1680 mod test {
1681     use super::*;
1682     use crate::shape::{Indent, Shape};
1683
1684     #[test]
1685     fn char_classes() {
1686         let mut iter = CharClasses::new("//\n\n".chars());
1687
1688         assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
1689         assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
1690         assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
1691         assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
1692         assert_eq!(None, iter.next());
1693     }
1694
1695     #[test]
1696     fn comment_code_slices() {
1697         let input = "code(); /* test */ 1 + 1";
1698         let mut iter = CommentCodeSlices::new(input);
1699
1700         assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
1701         assert_eq!(
1702             (CodeCharKind::Comment, 8, "/* test */"),
1703             iter.next().unwrap()
1704         );
1705         assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
1706         assert_eq!(None, iter.next());
1707     }
1708
1709     #[test]
1710     fn comment_code_slices_two() {
1711         let input = "// comment\n    test();";
1712         let mut iter = CommentCodeSlices::new(input);
1713
1714         assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
1715         assert_eq!(
1716             (CodeCharKind::Comment, 0, "// comment\n"),
1717             iter.next().unwrap()
1718         );
1719         assert_eq!(
1720             (CodeCharKind::Normal, 11, "    test();"),
1721             iter.next().unwrap()
1722         );
1723         assert_eq!(None, iter.next());
1724     }
1725
1726     #[test]
1727     fn comment_code_slices_three() {
1728         let input = "1 // comment\n    // comment2\n\n";
1729         let mut iter = CommentCodeSlices::new(input);
1730
1731         assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
1732         assert_eq!(
1733             (CodeCharKind::Comment, 2, "// comment\n    // comment2\n"),
1734             iter.next().unwrap()
1735         );
1736         assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
1737         assert_eq!(None, iter.next());
1738     }
1739
1740     #[test]
1741     #[rustfmt::skip]
1742     fn format_doc_comments() {
1743         let mut wrap_normalize_config: crate::config::Config = Default::default();
1744         wrap_normalize_config.set().wrap_comments(true);
1745         wrap_normalize_config.set().normalize_comments(true);
1746
1747         let mut wrap_config: crate::config::Config = Default::default();
1748         wrap_config.set().wrap_comments(true);
1749
1750         let comment = rewrite_comment(" //test",
1751                                       true,
1752                                       Shape::legacy(100, Indent::new(0, 100)),
1753                                       &wrap_normalize_config).unwrap();
1754         assert_eq!("/* test */", comment);
1755
1756         let comment = rewrite_comment("// comment on a",
1757                                       false,
1758                                       Shape::legacy(10, Indent::empty()),
1759                                       &wrap_normalize_config).unwrap();
1760         assert_eq!("// comment\n// on a", comment);
1761
1762         let comment = rewrite_comment("//  A multi line comment\n             // between args.",
1763                                       false,
1764                                       Shape::legacy(60, Indent::new(0, 12)),
1765                                       &wrap_normalize_config).unwrap();
1766         assert_eq!("//  A multi line comment\n            // between args.", comment);
1767
1768         let input = "// comment";
1769         let expected =
1770             "/* comment */";
1771         let comment = rewrite_comment(input,
1772                                       true,
1773                                       Shape::legacy(9, Indent::new(0, 69)),
1774                                       &wrap_normalize_config).unwrap();
1775         assert_eq!(expected, comment);
1776
1777         let comment = rewrite_comment("/*   trimmed    */",
1778                                       true,
1779                                       Shape::legacy(100, Indent::new(0, 100)),
1780                                       &wrap_normalize_config).unwrap();
1781         assert_eq!("/* trimmed */", comment);
1782
1783         // Check that different comment style are properly recognised.
1784         let comment = rewrite_comment(r#"/// test1
1785                                          /// test2
1786                                          /*
1787                                           * test3
1788                                           */"#,
1789                                       false,
1790                                       Shape::legacy(100, Indent::new(0, 0)),
1791                                       &wrap_normalize_config).unwrap();
1792         assert_eq!("/// test1\n/// test2\n// test3", comment);
1793
1794         // Check that the blank line marks the end of a commented paragraph.
1795         let comment = rewrite_comment(r#"// test1
1796
1797                                          // test2"#,
1798                                       false,
1799                                       Shape::legacy(100, Indent::new(0, 0)),
1800                                       &wrap_normalize_config).unwrap();
1801         assert_eq!("// test1\n\n// test2", comment);
1802
1803         // Check that the blank line marks the end of a custom-commented paragraph.
1804         let comment = rewrite_comment(r#"//@ test1
1805
1806                                          //@ test2"#,
1807                                       false,
1808                                       Shape::legacy(100, Indent::new(0, 0)),
1809                                       &wrap_normalize_config).unwrap();
1810         assert_eq!("//@ test1\n\n//@ test2", comment);
1811
1812         // Check that bare lines are just indented but otherwise left unchanged.
1813         let comment = rewrite_comment(r#"// test1
1814                                          /*
1815                                            a bare line!
1816
1817                                                 another bare line!
1818                                           */"#,
1819                                       false,
1820                                       Shape::legacy(100, Indent::new(0, 0)),
1821                                       &wrap_config).unwrap();
1822         assert_eq!("// test1\n/*\n a bare line!\n\n      another bare line!\n*/", comment);
1823     }
1824
1825     // This is probably intended to be a non-test fn, but it is not used.
1826     // We should keep this around unless it helps us test stuff to remove it.
1827     fn uncommented(text: &str) -> String {
1828         CharClasses::new(text.chars())
1829             .filter_map(|(s, c)| match s {
1830                 FullCodeCharKind::Normal | FullCodeCharKind::InString => Some(c),
1831                 _ => None,
1832             })
1833             .collect()
1834     }
1835
1836     #[test]
1837     fn test_uncommented() {
1838         assert_eq!(&uncommented("abc/*...*/"), "abc");
1839         assert_eq!(
1840             &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
1841             "..ac\n"
1842         );
1843         assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
1844     }
1845
1846     #[test]
1847     fn test_contains_comment() {
1848         assert_eq!(contains_comment("abc"), false);
1849         assert_eq!(contains_comment("abc // qsdf"), true);
1850         assert_eq!(contains_comment("abc /* kqsdf"), true);
1851         assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
1852     }
1853
1854     #[test]
1855     fn test_find_uncommented() {
1856         fn check(haystack: &str, needle: &str, expected: Option<usize>) {
1857             assert_eq!(expected, haystack.find_uncommented(needle));
1858         }
1859
1860         check("/*/ */test", "test", Some(6));
1861         check("//test\ntest", "test", Some(7));
1862         check("/* comment only */", "whatever", None);
1863         check(
1864             "/* comment */ some text /* more commentary */ result",
1865             "result",
1866             Some(46),
1867         );
1868         check("sup // sup", "p", Some(2));
1869         check("sup", "x", None);
1870         check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
1871         check("/*sup yo? \n sup*/ sup", "p", Some(20));
1872         check("hel/*lohello*/lo", "hello", None);
1873         check("acb", "ab", None);
1874         check(",/*A*/ ", ",", Some(0));
1875         check("abc", "abc", Some(0));
1876         check("/* abc */", "abc", None);
1877         check("/**/abc/* */", "abc", Some(4));
1878         check("\"/* abc */\"", "abc", Some(4));
1879         check("\"/* abc", "abc", Some(4));
1880     }
1881
1882     #[test]
1883     fn test_filter_normal_code() {
1884         let s = r#"
1885 fn main() {
1886     println!("hello, world");
1887 }
1888 "#;
1889         assert_eq!(s, filter_normal_code(s));
1890         let s_with_comment = r#"
1891 fn main() {
1892     // hello, world
1893     println!("hello, world");
1894 }
1895 "#;
1896         assert_eq!(s, filter_normal_code(s_with_comment));
1897     }
1898 }