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