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