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