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