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