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