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