]> git.lizzy.rs Git - rust.git/blob - src/comment.rs
Check whether '\\'' is char literal or lifetime
[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, iter, borrow::Cow};
14
15 use itertools::{multipeek, MultiPeek};
16 use syntax::codemap::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
24 fn is_custom_comment(comment: &str) -> bool {
25     if !comment.starts_with("//") {
26         false
27     } else if let Some(c) = comment.chars().nth(2) {
28         !c.is_alphanumeric() && !c.is_whitespace()
29     } else {
30         false
31     }
32 }
33
34 #[derive(Copy, Clone, PartialEq, Eq)]
35 pub enum CommentStyle<'a> {
36     DoubleSlash,
37     TripleSlash,
38     Doc,
39     SingleBullet,
40     DoubleBullet,
41     Exclamation,
42     Custom(&'a str),
43 }
44
45 fn custom_opener(s: &str) -> &str {
46     s.lines().next().map_or("", |first_line| {
47         first_line
48             .find(' ')
49             .map_or(first_line, |space_index| &first_line[0..space_index + 1])
50     })
51 }
52
53 impl<'a> CommentStyle<'a> {
54     pub fn is_doc_comment(&self) -> bool {
55         match *self {
56             CommentStyle::TripleSlash | CommentStyle::Doc => true,
57             _ => false,
58         }
59     }
60
61     pub fn opener(&self) -> &'a str {
62         match *self {
63             CommentStyle::DoubleSlash => "// ",
64             CommentStyle::TripleSlash => "/// ",
65             CommentStyle::Doc => "//! ",
66             CommentStyle::SingleBullet => "/* ",
67             CommentStyle::DoubleBullet => "/** ",
68             CommentStyle::Exclamation => "/*! ",
69             CommentStyle::Custom(opener) => opener,
70         }
71     }
72
73     pub fn closer(&self) -> &'a str {
74         match *self {
75             CommentStyle::DoubleSlash
76             | CommentStyle::TripleSlash
77             | CommentStyle::Custom(..)
78             | CommentStyle::Doc => "",
79             CommentStyle::DoubleBullet => " **/",
80             CommentStyle::SingleBullet | CommentStyle::Exclamation => " */",
81         }
82     }
83
84     pub fn line_start(&self) -> &'a str {
85         match *self {
86             CommentStyle::DoubleSlash => "// ",
87             CommentStyle::TripleSlash => "/// ",
88             CommentStyle::Doc => "//! ",
89             CommentStyle::SingleBullet | CommentStyle::Exclamation => " * ",
90             CommentStyle::DoubleBullet => " ** ",
91             CommentStyle::Custom(opener) => opener,
92         }
93     }
94
95     pub fn to_str_tuplet(&self) -> (&'a str, &'a str, &'a str) {
96         (self.opener(), self.closer(), self.line_start())
97     }
98
99     pub fn line_with_same_comment_style(&self, line: &str, normalize_comments: bool) -> bool {
100         match *self {
101             CommentStyle::DoubleSlash | CommentStyle::TripleSlash | CommentStyle::Doc => {
102                 line.trim_left().starts_with(self.line_start().trim_left())
103                     || comment_style(line, normalize_comments) == *self
104             }
105             CommentStyle::DoubleBullet | CommentStyle::SingleBullet | CommentStyle::Exclamation => {
106                 line.trim_left().starts_with(self.closer().trim_left())
107                     || line.trim_left().starts_with(self.line_start().trim_left())
108                     || comment_style(line, normalize_comments) == *self
109             }
110             CommentStyle::Custom(opener) => line.trim_left().starts_with(opener.trim_right()),
111         }
112     }
113 }
114
115 fn comment_style(orig: &str, normalize_comments: bool) -> CommentStyle {
116     if !normalize_comments {
117         if orig.starts_with("/**") && !orig.starts_with("/**/") {
118             CommentStyle::DoubleBullet
119         } else if orig.starts_with("/*!") {
120             CommentStyle::Exclamation
121         } else if orig.starts_with("/*") {
122             CommentStyle::SingleBullet
123         } else if orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/') {
124             CommentStyle::TripleSlash
125         } else if orig.starts_with("//!") {
126             CommentStyle::Doc
127         } else if is_custom_comment(orig) {
128             CommentStyle::Custom(custom_opener(orig))
129         } else {
130             CommentStyle::DoubleSlash
131         }
132     } else if (orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/'))
133         || (orig.starts_with("/**") && !orig.starts_with("/**/"))
134     {
135         CommentStyle::TripleSlash
136     } else if orig.starts_with("//!") || orig.starts_with("/*!") {
137         CommentStyle::Doc
138     } else if is_custom_comment(orig) {
139         CommentStyle::Custom(custom_opener(orig))
140     } else {
141         CommentStyle::DoubleSlash
142     }
143 }
144
145 /// Combine `prev_str` and `next_str` into a single `String`. `span` may contain
146 /// comments between two strings. If there are such comments, then that will be
147 /// recovered. If `allow_extend` is true and there is no comment between the two
148 /// strings, then they will be put on a single line as long as doing so does not
149 /// exceed max width.
150 pub fn combine_strs_with_missing_comments(
151     context: &RewriteContext,
152     prev_str: &str,
153     next_str: &str,
154     span: Span,
155     shape: Shape,
156     allow_extend: bool,
157 ) -> Option<String> {
158     let mut result =
159         String::with_capacity(prev_str.len() + next_str.len() + shape.indent.width() + 128);
160     result.push_str(prev_str);
161     let mut allow_one_line = !prev_str.contains('\n') && !next_str.contains('\n');
162     let first_sep = if prev_str.is_empty() || next_str.is_empty() {
163         ""
164     } else {
165         " "
166     };
167     let mut one_line_width =
168         last_line_width(prev_str) + first_line_width(next_str) + first_sep.len();
169
170     let config = context.config;
171     let indent = shape.indent;
172     let missing_comment = rewrite_missing_comment(span, shape, context)?;
173
174     if missing_comment.is_empty() {
175         if allow_extend && prev_str.len() + first_sep.len() + next_str.len() <= shape.width {
176             result.push_str(first_sep);
177         } else if !prev_str.is_empty() {
178             result.push_str(&indent.to_string_with_newline(config))
179         }
180         result.push_str(next_str);
181         return Some(result);
182     }
183
184     // We have a missing comment between the first expression and the second expression.
185
186     // Peek the the original source code and find out whether there is a newline between the first
187     // expression and the second expression or the missing comment. We will preserve the original
188     // layout whenever possible.
189     let original_snippet = context.snippet(span);
190     let prefer_same_line = if let Some(pos) = original_snippet.chars().position(|c| c == '/') {
191         !original_snippet[..pos].contains('\n')
192     } else {
193         !original_snippet.contains('\n')
194     };
195
196     one_line_width -= first_sep.len();
197     let first_sep = if prev_str.is_empty() || missing_comment.is_empty() {
198         Cow::from("")
199     } else {
200         let one_line_width = last_line_width(prev_str) + first_line_width(&missing_comment) + 1;
201         if prefer_same_line && one_line_width <= shape.width {
202             Cow::from(" ")
203         } else {
204             indent.to_string_with_newline(config)
205         }
206     };
207     result.push_str(&first_sep);
208     result.push_str(&missing_comment);
209
210     let second_sep = if missing_comment.is_empty() || next_str.is_empty() {
211         Cow::from("")
212     } else if missing_comment.starts_with("//") {
213         indent.to_string_with_newline(config)
214     } else {
215         one_line_width += missing_comment.len() + first_sep.len() + 1;
216         allow_one_line &= !missing_comment.starts_with("//") && !missing_comment.contains('\n');
217         if prefer_same_line && allow_one_line && one_line_width <= shape.width {
218             Cow::from(" ")
219         } else {
220             indent.to_string_with_newline(config)
221         }
222     };
223     result.push_str(&second_sep);
224     result.push_str(next_str);
225
226     Some(result)
227 }
228
229 pub fn rewrite_doc_comment(orig: &str, shape: Shape, config: &Config) -> Option<String> {
230     _rewrite_comment(orig, false, shape, config, true)
231 }
232
233 pub fn rewrite_comment(
234     orig: &str,
235     block_style: bool,
236     shape: Shape,
237     config: &Config,
238 ) -> Option<String> {
239     _rewrite_comment(orig, block_style, shape, config, false)
240 }
241
242 fn _rewrite_comment(
243     orig: &str,
244     block_style: bool,
245     shape: Shape,
246     config: &Config,
247     is_doc_comment: bool,
248 ) -> Option<String> {
249     // If there are lines without a starting sigil, we won't format them correctly
250     // so in that case we won't even re-align (if !config.normalize_comments()) and
251     // we should stop now.
252     let num_bare_lines = orig.lines()
253         .map(|line| line.trim())
254         .filter(|l| !(l.starts_with('*') || l.starts_with("//") || l.starts_with("/*")))
255         .count();
256     if num_bare_lines > 0 && !config.normalize_comments() {
257         return Some(orig.to_owned());
258     }
259     if !config.normalize_comments() && !config.wrap_comments() {
260         return light_rewrite_comment(orig, shape.indent, config, is_doc_comment);
261     }
262
263     identify_comment(orig, block_style, shape, config, is_doc_comment)
264 }
265
266 fn identify_comment(
267     orig: &str,
268     block_style: bool,
269     shape: Shape,
270     config: &Config,
271     is_doc_comment: bool,
272 ) -> Option<String> {
273     let style = comment_style(orig, false);
274     let first_group = orig.lines()
275         .take_while(|l| style.line_with_same_comment_style(l, false))
276         .collect::<Vec<_>>()
277         .join("\n");
278     let rest = orig.lines()
279         .skip(first_group.lines().count())
280         .collect::<Vec<_>>()
281         .join("\n");
282
283     let first_group_str = rewrite_comment_inner(
284         &first_group,
285         block_style,
286         style,
287         shape,
288         config,
289         is_doc_comment || style.is_doc_comment(),
290     )?;
291     if rest.is_empty() {
292         Some(first_group_str)
293     } else {
294         identify_comment(&rest, block_style, shape, config, is_doc_comment).map(|rest_str| {
295             format!(
296                 "{}\n{}{}",
297                 first_group_str,
298                 shape.indent.to_string(config),
299                 rest_str
300             )
301         })
302     }
303 }
304
305 fn rewrite_comment_inner(
306     orig: &str,
307     block_style: bool,
308     style: CommentStyle,
309     shape: Shape,
310     config: &Config,
311     is_doc_comment: bool,
312 ) -> Option<String> {
313     let (opener, closer, line_start) = if block_style {
314         CommentStyle::SingleBullet.to_str_tuplet()
315     } else {
316         comment_style(orig, config.normalize_comments()).to_str_tuplet()
317     };
318
319     let max_chars = shape
320         .width
321         .checked_sub(closer.len() + opener.len())
322         .unwrap_or(1);
323     let indent_str = shape.indent.to_string_with_newline(config);
324     let fmt_indent = shape.indent + (opener.len() - line_start.len());
325     let mut fmt = StringFormat {
326         opener: "",
327         closer: "",
328         line_start,
329         line_end: "",
330         shape: Shape::legacy(max_chars, fmt_indent),
331         trim_end: true,
332         config,
333     };
334
335     let line_breaks = count_newlines(orig.trim_right());
336     let lines = orig.lines()
337         .enumerate()
338         .map(|(i, mut line)| {
339             line = trim_right_unless_two_whitespaces(line.trim_left(), is_doc_comment);
340             // Drop old closer.
341             if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
342                 line = line[..(line.len() - 2)].trim_right();
343             }
344
345             line
346         })
347         .map(|s| left_trim_comment_line(s, &style))
348         .map(|(line, has_leading_whitespace)| {
349             if orig.starts_with("/*") && line_breaks == 0 {
350                 (
351                     line.trim_left(),
352                     has_leading_whitespace || config.normalize_comments(),
353                 )
354             } else {
355                 (line, has_leading_whitespace || config.normalize_comments())
356             }
357         });
358
359     let mut result = String::with_capacity(orig.len() * 2);
360     result.push_str(opener);
361     let mut code_block_buffer = String::with_capacity(128);
362     let mut is_prev_line_multi_line = false;
363     let mut inside_code_block = false;
364     let comment_line_separator = format!("{}{}", indent_str, line_start);
365     let join_code_block_with_comment_line_separator = |s: &str| {
366         let mut result = String::with_capacity(s.len() + 128);
367         let mut iter = s.lines().peekable();
368         while let Some(line) = iter.next() {
369             result.push_str(line);
370             result.push_str(match iter.peek() {
371                 Some(next_line) if next_line.is_empty() => comment_line_separator.trim_right(),
372                 Some(..) => &comment_line_separator,
373                 None => "",
374             });
375         }
376         result
377     };
378
379     for (i, (line, has_leading_whitespace)) in lines.enumerate() {
380         let is_last = i == count_newlines(orig);
381
382         if inside_code_block {
383             if line.starts_with("```") {
384                 inside_code_block = false;
385                 result.push_str(&comment_line_separator);
386                 let code_block = ::format_code_block(&code_block_buffer, config)
387                     .unwrap_or_else(|| code_block_buffer.to_owned());
388                 result.push_str(&join_code_block_with_comment_line_separator(&code_block));
389                 code_block_buffer.clear();
390                 result.push_str(&comment_line_separator);
391                 result.push_str(line);
392             } else {
393                 code_block_buffer.push_str(line);
394                 code_block_buffer.push('\n');
395             }
396
397             continue;
398         } else {
399             inside_code_block = line.starts_with("```rust");
400
401             if result == opener {
402                 let force_leading_whitespace = opener == "/* " && count_newlines(orig) == 0;
403                 if !has_leading_whitespace && !force_leading_whitespace && result.ends_with(' ') {
404                     result.pop();
405                 }
406                 if line.is_empty() {
407                     continue;
408                 }
409             } else if is_prev_line_multi_line && !line.is_empty() {
410                 result.push(' ')
411             } else if is_last && !closer.is_empty() && line.is_empty() {
412                 result.push_str(&indent_str);
413             } else {
414                 result.push_str(&comment_line_separator);
415                 if !has_leading_whitespace && result.ends_with(' ') {
416                     result.pop();
417                 }
418             }
419         }
420
421         if config.wrap_comments() && line.len() > fmt.shape.width && !has_url(line) {
422             match rewrite_string(line, &fmt, Some(max_chars)) {
423                 Some(ref s) => {
424                     is_prev_line_multi_line = s.contains('\n');
425                     result.push_str(s);
426                 }
427                 None if is_prev_line_multi_line => {
428                     // We failed to put the current `line` next to the previous `line`.
429                     // Remove the trailing space, then start rewrite on the next line.
430                     result.pop();
431                     result.push_str(&comment_line_separator);
432                     fmt.shape = Shape::legacy(max_chars, fmt_indent);
433                     match rewrite_string(line, &fmt, Some(max_chars)) {
434                         Some(ref s) => {
435                             is_prev_line_multi_line = s.contains('\n');
436                             result.push_str(s);
437                         }
438                         None => {
439                             is_prev_line_multi_line = false;
440                             result.push_str(line);
441                         }
442                     }
443                 }
444                 None => {
445                     is_prev_line_multi_line = false;
446                     result.push_str(line);
447                 }
448             }
449
450             fmt.shape = if is_prev_line_multi_line {
451                 // 1 = " "
452                 let offset = 1 + last_line_width(&result) - line_start.len();
453                 Shape {
454                     width: max_chars.checked_sub(offset).unwrap_or(0),
455                     indent: fmt_indent,
456                     offset: fmt.shape.offset + offset,
457                 }
458             } else {
459                 Shape::legacy(max_chars, fmt_indent)
460             };
461         } else {
462             if line.is_empty() && result.ends_with(' ') && !is_last {
463                 // Remove space if this is an empty comment or a doc comment.
464                 result.pop();
465             }
466             result.push_str(line);
467             fmt.shape = Shape::legacy(max_chars, fmt_indent);
468             is_prev_line_multi_line = false;
469         }
470     }
471
472     result.push_str(closer);
473     if result.ends_with(opener) && opener.ends_with(' ') {
474         // Trailing space.
475         result.pop();
476     }
477
478     Some(result)
479 }
480
481 /// Returns true if the given string MAY include URLs or alike.
482 fn has_url(s: &str) -> bool {
483     // This function may return false positive, but should get its job done in most cases.
484     s.contains("https://") || s.contains("http://") || s.contains("ftp://") || s.contains("file://")
485 }
486
487 /// Given the span, rewrite the missing comment inside it if available.
488 /// Note that the given span must only include comments (or leading/trailing whitespaces).
489 pub fn rewrite_missing_comment(
490     span: Span,
491     shape: Shape,
492     context: &RewriteContext,
493 ) -> Option<String> {
494     let missing_snippet = context.snippet(span);
495     let trimmed_snippet = missing_snippet.trim();
496     if !trimmed_snippet.is_empty() {
497         rewrite_comment(trimmed_snippet, false, shape, context.config)
498     } else {
499         Some(String::new())
500     }
501 }
502
503 /// Recover the missing comments in the specified span, if available.
504 /// The layout of the comments will be preserved as long as it does not break the code
505 /// and its total width does not exceed the max width.
506 pub fn recover_missing_comment_in_span(
507     span: Span,
508     shape: Shape,
509     context: &RewriteContext,
510     used_width: usize,
511 ) -> Option<String> {
512     let missing_comment = rewrite_missing_comment(span, shape, context)?;
513     if missing_comment.is_empty() {
514         Some(String::new())
515     } else {
516         let missing_snippet = context.snippet(span);
517         let pos = missing_snippet.chars().position(|c| c == '/').unwrap_or(0);
518         // 1 = ` `
519         let total_width = missing_comment.len() + used_width + 1;
520         let force_new_line_before_comment =
521             missing_snippet[..pos].contains('\n') || total_width > context.config.max_width();
522         let sep = if force_new_line_before_comment {
523             shape.indent.to_string_with_newline(context.config)
524         } else {
525             Cow::from(" ")
526         };
527         Some(format!("{}{}", sep, missing_comment))
528     }
529 }
530
531 /// Trim trailing whitespaces unless they consist of two or more whitespaces.
532 fn trim_right_unless_two_whitespaces(s: &str, is_doc_comment: bool) -> &str {
533     if is_doc_comment && s.ends_with("  ") {
534         s
535     } else {
536         s.trim_right()
537     }
538 }
539
540 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
541 fn light_rewrite_comment(
542     orig: &str,
543     offset: Indent,
544     config: &Config,
545     is_doc_comment: bool,
546 ) -> Option<String> {
547     let lines: Vec<&str> = orig.lines()
548         .map(|l| {
549             // This is basically just l.trim(), but in the case that a line starts
550             // with `*` we want to leave one space before it, so it aligns with the
551             // `*` in `/*`.
552             let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
553             let left_trimmed = if let Some(fnw) = first_non_whitespace {
554                 if l.as_bytes()[fnw] == b'*' && fnw > 0 {
555                     &l[fnw - 1..]
556                 } else {
557                     &l[fnw..]
558                 }
559             } else {
560                 ""
561             };
562             // Preserve markdown's double-space line break syntax in doc comment.
563             trim_right_unless_two_whitespaces(left_trimmed, is_doc_comment)
564         })
565         .collect();
566     Some(lines.join(&format!("\n{}", offset.to_string(config))))
567 }
568
569 /// Trims comment characters and possibly a single space from the left of a string.
570 /// Does not trim all whitespace. If a single space is trimmed from the left of the string,
571 /// this function returns true.
572 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle) -> (&'a str, bool) {
573     if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ")
574         || line.starts_with("/** ")
575     {
576         (&line[4..], true)
577     } else if let CommentStyle::Custom(opener) = *style {
578         if line.starts_with(opener) {
579             (&line[opener.len()..], true)
580         } else {
581             (&line[opener.trim_right().len()..], false)
582         }
583     } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!")
584         || line.starts_with("///") || line.starts_with("** ")
585         || line.starts_with("/*!")
586         || (line.starts_with("/**") && !line.starts_with("/**/"))
587     {
588         (&line[3..], line.chars().nth(2).unwrap() == ' ')
589     } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//")
590         || line.starts_with("**")
591     {
592         (&line[2..], line.chars().nth(1).unwrap() == ' ')
593     } else if line.starts_with('*') {
594         (&line[1..], false)
595     } else {
596         (line, line.starts_with(' '))
597     }
598 }
599
600 pub trait FindUncommented {
601     fn find_uncommented(&self, pat: &str) -> Option<usize>;
602 }
603
604 impl FindUncommented for str {
605     fn find_uncommented(&self, pat: &str) -> Option<usize> {
606         let mut needle_iter = pat.chars();
607         for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
608             match needle_iter.next() {
609                 None => {
610                     return Some(i - pat.len());
611                 }
612                 Some(c) => match kind {
613                     FullCodeCharKind::Normal | FullCodeCharKind::InString if b == c => {}
614                     _ => {
615                         needle_iter = pat.chars();
616                     }
617                 },
618             }
619         }
620
621         // Handle case where the pattern is a suffix of the search string
622         match needle_iter.next() {
623             Some(_) => None,
624             None => Some(self.len() - pat.len()),
625         }
626     }
627 }
628
629 // Returns the first byte position after the first comment. The given string
630 // is expected to be prefixed by a comment, including delimiters.
631 // Good: "/* /* inner */ outer */ code();"
632 // Bad:  "code(); // hello\n world!"
633 pub fn find_comment_end(s: &str) -> Option<usize> {
634     let mut iter = CharClasses::new(s.char_indices());
635     for (kind, (i, _c)) in &mut iter {
636         if kind == FullCodeCharKind::Normal || kind == FullCodeCharKind::InString {
637             return Some(i);
638         }
639     }
640
641     // Handle case where the comment ends at the end of s.
642     if iter.status == CharClassesStatus::Normal {
643         Some(s.len())
644     } else {
645         None
646     }
647 }
648
649 /// Returns true if text contains any comment.
650 pub fn contains_comment(text: &str) -> bool {
651     CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
652 }
653
654 /// Remove trailing spaces from the specified snippet. We do not remove spaces
655 /// inside strings or comments.
656 pub fn remove_trailing_white_spaces(text: &str) -> String {
657     let mut buffer = String::with_capacity(text.len());
658     let mut space_buffer = String::with_capacity(128);
659     for (char_kind, c) in CharClasses::new(text.chars()) {
660         match c {
661             '\n' => {
662                 if char_kind == FullCodeCharKind::InString {
663                     buffer.push_str(&space_buffer);
664                 }
665                 space_buffer.clear();
666                 buffer.push('\n');
667             }
668             _ if c.is_whitespace() => {
669                 space_buffer.push(c);
670             }
671             _ => {
672                 if !space_buffer.is_empty() {
673                     buffer.push_str(&space_buffer);
674                     space_buffer.clear();
675                 }
676                 buffer.push(c);
677             }
678         }
679     }
680     buffer
681 }
682
683 pub struct CharClasses<T>
684 where
685     T: Iterator,
686     T::Item: RichChar,
687 {
688     base: MultiPeek<T>,
689     status: CharClassesStatus,
690 }
691
692 pub trait RichChar {
693     fn get_char(&self) -> char;
694 }
695
696 impl RichChar for char {
697     fn get_char(&self) -> char {
698         *self
699     }
700 }
701
702 impl RichChar for (usize, char) {
703     fn get_char(&self) -> char {
704         self.1
705     }
706 }
707
708 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
709 enum CharClassesStatus {
710     Normal,
711     LitString,
712     LitStringEscape,
713     LitChar,
714     LitCharEscape,
715     // The u32 is the nesting deepness of the comment
716     BlockComment(u32),
717     // Status when the '/' has been consumed, but not yet the '*', deepness is
718     // the new deepness (after the comment opening).
719     BlockCommentOpening(u32),
720     // Status when the '*' has been consumed, but not yet the '/', deepness is
721     // the new deepness (after the comment closing).
722     BlockCommentClosing(u32),
723     LineComment,
724 }
725
726 /// Distinguish between functional part of code and comments
727 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
728 pub enum CodeCharKind {
729     Normal,
730     Comment,
731 }
732
733 /// Distinguish between functional part of code and comments,
734 /// describing opening and closing of comments for ease when chunking
735 /// code from tagged characters
736 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
737 pub enum FullCodeCharKind {
738     Normal,
739     /// The first character of a comment, there is only one for a comment (always '/')
740     StartComment,
741     /// Any character inside a comment including the second character of comment
742     /// marks ("//", "/*")
743     InComment,
744     /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
745     EndComment,
746     /// Inside a string.
747     InString,
748 }
749
750 impl FullCodeCharKind {
751     pub fn is_comment(&self) -> bool {
752         match *self {
753             FullCodeCharKind::StartComment
754             | FullCodeCharKind::InComment
755             | FullCodeCharKind::EndComment => true,
756             _ => false,
757         }
758     }
759
760     pub fn is_string(&self) -> bool {
761         *self == FullCodeCharKind::InString
762     }
763
764     fn to_codecharkind(&self) -> CodeCharKind {
765         if self.is_comment() {
766             CodeCharKind::Comment
767         } else {
768             CodeCharKind::Normal
769         }
770     }
771 }
772
773 impl<T> CharClasses<T>
774 where
775     T: Iterator,
776     T::Item: RichChar,
777 {
778     pub fn new(base: T) -> CharClasses<T> {
779         CharClasses {
780             base: multipeek(base),
781             status: CharClassesStatus::Normal,
782         }
783     }
784 }
785
786 impl<T> Iterator for CharClasses<T>
787 where
788     T: Iterator,
789     T::Item: RichChar,
790 {
791     type Item = (FullCodeCharKind, T::Item);
792
793     fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
794         let item = self.base.next()?;
795         let chr = item.get_char();
796         let mut char_kind = FullCodeCharKind::Normal;
797         self.status = match self.status {
798             CharClassesStatus::LitString => match chr {
799                 '"' => CharClassesStatus::Normal,
800                 '\\' => {
801                     char_kind = FullCodeCharKind::InString;
802                     CharClassesStatus::LitStringEscape
803                 }
804                 _ => {
805                     char_kind = FullCodeCharKind::InString;
806                     CharClassesStatus::LitString
807                 }
808             },
809             CharClassesStatus::LitStringEscape => {
810                 char_kind = FullCodeCharKind::InString;
811                 CharClassesStatus::LitString
812             }
813             CharClassesStatus::LitChar => match chr {
814                 '\\' => CharClassesStatus::LitCharEscape,
815                 '\'' => CharClassesStatus::Normal,
816                 _ => CharClassesStatus::LitChar,
817             },
818             CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
819             CharClassesStatus::Normal => match chr {
820                 '"' => {
821                     char_kind = FullCodeCharKind::InString;
822                     CharClassesStatus::LitString
823                 }
824                 '\'' => {
825                     // HACK: Work around mut borrow.
826                     match self.base.peek() {
827                         Some(next) if next.get_char() == '\\' => {
828                             self.status = CharClassesStatus::LitChar;
829                             return Some((char_kind, item));
830                         }
831                         _ => (),
832                     }
833
834                     match self.base.peek() {
835                         Some(next) if next.get_char() == '\'' => CharClassesStatus::LitChar,
836                         _ => CharClassesStatus::Normal,
837                     }
838                 }
839                 '/' => match self.base.peek() {
840                     Some(next) if next.get_char() == '*' => {
841                         self.status = CharClassesStatus::BlockCommentOpening(1);
842                         return Some((FullCodeCharKind::StartComment, item));
843                     }
844                     Some(next) if next.get_char() == '/' => {
845                         self.status = CharClassesStatus::LineComment;
846                         return Some((FullCodeCharKind::StartComment, item));
847                     }
848                     _ => CharClassesStatus::Normal,
849                 },
850                 _ => CharClassesStatus::Normal,
851             },
852             CharClassesStatus::BlockComment(deepness) => {
853                 assert_ne!(deepness, 0);
854                 self.status = match self.base.peek() {
855                     Some(next) if next.get_char() == '/' && chr == '*' => {
856                         CharClassesStatus::BlockCommentClosing(deepness - 1)
857                     }
858                     Some(next) if next.get_char() == '*' && chr == '/' => {
859                         CharClassesStatus::BlockCommentOpening(deepness + 1)
860                     }
861                     _ => CharClassesStatus::BlockComment(deepness),
862                 };
863                 return Some((FullCodeCharKind::InComment, item));
864             }
865             CharClassesStatus::BlockCommentOpening(deepness) => {
866                 assert_eq!(chr, '*');
867                 self.status = CharClassesStatus::BlockComment(deepness);
868                 return Some((FullCodeCharKind::InComment, item));
869             }
870             CharClassesStatus::BlockCommentClosing(deepness) => {
871                 assert_eq!(chr, '/');
872                 if deepness == 0 {
873                     self.status = CharClassesStatus::Normal;
874                     return Some((FullCodeCharKind::EndComment, item));
875                 } else {
876                     self.status = CharClassesStatus::BlockComment(deepness);
877                     return Some((FullCodeCharKind::InComment, item));
878                 }
879             }
880             CharClassesStatus::LineComment => match chr {
881                 '\n' => {
882                     self.status = CharClassesStatus::Normal;
883                     return Some((FullCodeCharKind::EndComment, item));
884                 }
885                 _ => {
886                     self.status = CharClassesStatus::LineComment;
887                     return Some((FullCodeCharKind::InComment, item));
888                 }
889             },
890         };
891         Some((char_kind, item))
892     }
893 }
894
895 /// Iterator over functional and commented parts of a string. Any part of a string is either
896 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
897 /// comments is functional code. Line comments contain their ending newlines.
898 struct UngroupedCommentCodeSlices<'a> {
899     slice: &'a str,
900     iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
901 }
902
903 impl<'a> UngroupedCommentCodeSlices<'a> {
904     fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
905         UngroupedCommentCodeSlices {
906             slice: code,
907             iter: CharClasses::new(code.char_indices()).peekable(),
908         }
909     }
910 }
911
912 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
913     type Item = (CodeCharKind, usize, &'a str);
914
915     fn next(&mut self) -> Option<Self::Item> {
916         let (kind, (start_idx, _)) = self.iter.next()?;
917         match kind {
918             FullCodeCharKind::Normal | FullCodeCharKind::InString => {
919                 // Consume all the Normal code
920                 while let Some(&(char_kind, _)) = self.iter.peek() {
921                     if char_kind.is_comment() {
922                         break;
923                     }
924                     let _ = self.iter.next();
925                 }
926             }
927             FullCodeCharKind::StartComment => {
928                 // Consume the whole comment
929                 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
930             }
931             _ => panic!(),
932         }
933         let slice = match self.iter.peek() {
934             Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
935             None => &self.slice[start_idx..],
936         };
937         Some((
938             if kind.is_comment() {
939                 CodeCharKind::Comment
940             } else {
941                 CodeCharKind::Normal
942             },
943             start_idx,
944             slice,
945         ))
946     }
947 }
948
949 /// Iterator over an alternating sequence of functional and commented parts of
950 /// a string. The first item is always a, possibly zero length, subslice of
951 /// functional text. Line style comments contain their ending newlines.
952 pub struct CommentCodeSlices<'a> {
953     slice: &'a str,
954     last_slice_kind: CodeCharKind,
955     last_slice_end: usize,
956 }
957
958 impl<'a> CommentCodeSlices<'a> {
959     pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
960         CommentCodeSlices {
961             slice,
962             last_slice_kind: CodeCharKind::Comment,
963             last_slice_end: 0,
964         }
965     }
966 }
967
968 impl<'a> Iterator for CommentCodeSlices<'a> {
969     type Item = (CodeCharKind, usize, &'a str);
970
971     fn next(&mut self) -> Option<Self::Item> {
972         if self.last_slice_end == self.slice.len() {
973             return None;
974         }
975
976         let mut sub_slice_end = self.last_slice_end;
977         let mut first_whitespace = None;
978         let subslice = &self.slice[self.last_slice_end..];
979         let mut iter = CharClasses::new(subslice.char_indices());
980
981         for (kind, (i, c)) in &mut iter {
982             let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal
983                 && &subslice[..2] == "//"
984                 && [' ', '\t'].contains(&c);
985
986             if is_comment_connector && first_whitespace.is_none() {
987                 first_whitespace = Some(i);
988             }
989
990             if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
991                 let last_index = match first_whitespace {
992                     Some(j) => j,
993                     None => i,
994                 };
995                 sub_slice_end = self.last_slice_end + last_index;
996                 break;
997             }
998
999             if !is_comment_connector {
1000                 first_whitespace = None;
1001             }
1002         }
1003
1004         if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
1005             // This was the last subslice.
1006             sub_slice_end = match first_whitespace {
1007                 Some(i) => self.last_slice_end + i,
1008                 None => self.slice.len(),
1009             };
1010         }
1011
1012         let kind = match self.last_slice_kind {
1013             CodeCharKind::Comment => CodeCharKind::Normal,
1014             CodeCharKind::Normal => CodeCharKind::Comment,
1015         };
1016         let res = (
1017             kind,
1018             self.last_slice_end,
1019             &self.slice[self.last_slice_end..sub_slice_end],
1020         );
1021         self.last_slice_end = sub_slice_end;
1022         self.last_slice_kind = kind;
1023
1024         Some(res)
1025     }
1026 }
1027
1028 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
1029 /// (if it fits in the width/offset, else return None), else return `new`
1030 pub fn recover_comment_removed(
1031     new: String,
1032     span: Span,
1033     context: &RewriteContext,
1034 ) -> Option<String> {
1035     let snippet = context.snippet(span);
1036     if snippet != new && changed_comment_content(snippet, &new) {
1037         // We missed some comments. Keep the original text.
1038         Some(snippet.to_owned())
1039     } else {
1040         Some(new)
1041     }
1042 }
1043
1044 /// Return true if the two strings of code have the same payload of comments.
1045 /// The payload of comments is everything in the string except:
1046 ///     - actual code (not comments)
1047 ///     - comment start/end marks
1048 ///     - whitespace
1049 ///     - '*' at the beginning of lines in block comments
1050 fn changed_comment_content(orig: &str, new: &str) -> bool {
1051     // Cannot write this as a fn since we cannot return types containing closures
1052     let code_comment_content = |code| {
1053         let slices = UngroupedCommentCodeSlices::new(code);
1054         slices
1055             .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
1056             .flat_map(|(_, _, s)| CommentReducer::new(s))
1057     };
1058     let res = code_comment_content(orig).ne(code_comment_content(new));
1059     debug!(
1060         "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
1061         res,
1062         orig,
1063         new,
1064         code_comment_content(orig).collect::<String>(),
1065         code_comment_content(new).collect::<String>()
1066     );
1067     res
1068 }
1069
1070 /// Iterator over the 'payload' characters of a comment.
1071 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
1072 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
1073 /// for example).
1074 struct CommentReducer<'a> {
1075     is_block: bool,
1076     at_start_line: bool,
1077     iter: std::str::Chars<'a>,
1078 }
1079
1080 impl<'a> CommentReducer<'a> {
1081     fn new(comment: &'a str) -> CommentReducer<'a> {
1082         let is_block = comment.starts_with("/*");
1083         let comment = remove_comment_header(comment);
1084         CommentReducer {
1085             is_block,
1086             at_start_line: false, // There are no supplementary '*' on the first line
1087             iter: comment.chars(),
1088         }
1089     }
1090 }
1091
1092 impl<'a> Iterator for CommentReducer<'a> {
1093     type Item = char;
1094     fn next(&mut self) -> Option<Self::Item> {
1095         loop {
1096             let mut c = self.iter.next()?;
1097             if self.is_block && self.at_start_line {
1098                 while c.is_whitespace() {
1099                     c = self.iter.next()?;
1100                 }
1101                 // Ignore leading '*'
1102                 if c == '*' {
1103                     c = self.iter.next()?;
1104                 }
1105             } else if c == '\n' {
1106                 self.at_start_line = true;
1107             }
1108             if !c.is_whitespace() {
1109                 return Some(c);
1110             }
1111         }
1112     }
1113 }
1114
1115 fn remove_comment_header(comment: &str) -> &str {
1116     if comment.starts_with("///") || comment.starts_with("//!") {
1117         &comment[3..]
1118     } else if comment.starts_with("//") {
1119         &comment[2..]
1120     } else if (comment.starts_with("/**") && !comment.starts_with("/**/"))
1121         || comment.starts_with("/*!")
1122     {
1123         &comment[3..comment.len() - 2]
1124     } else {
1125         assert!(
1126             comment.starts_with("/*"),
1127             format!("string '{}' is not a comment", comment)
1128         );
1129         &comment[2..comment.len() - 2]
1130     }
1131 }
1132
1133 #[cfg(test)]
1134 mod test {
1135     use super::{contains_comment, rewrite_comment, CharClasses, CodeCharKind, CommentCodeSlices,
1136                 FindUncommented, FullCodeCharKind};
1137     use shape::{Indent, Shape};
1138
1139     #[test]
1140     fn char_classes() {
1141         let mut iter = CharClasses::new("//\n\n".chars());
1142
1143         assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
1144         assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
1145         assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
1146         assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
1147         assert_eq!(None, iter.next());
1148     }
1149
1150     #[test]
1151     fn comment_code_slices() {
1152         let input = "code(); /* test */ 1 + 1";
1153         let mut iter = CommentCodeSlices::new(input);
1154
1155         assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
1156         assert_eq!(
1157             (CodeCharKind::Comment, 8, "/* test */"),
1158             iter.next().unwrap()
1159         );
1160         assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
1161         assert_eq!(None, iter.next());
1162     }
1163
1164     #[test]
1165     fn comment_code_slices_two() {
1166         let input = "// comment\n    test();";
1167         let mut iter = CommentCodeSlices::new(input);
1168
1169         assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
1170         assert_eq!(
1171             (CodeCharKind::Comment, 0, "// comment\n"),
1172             iter.next().unwrap()
1173         );
1174         assert_eq!(
1175             (CodeCharKind::Normal, 11, "    test();"),
1176             iter.next().unwrap()
1177         );
1178         assert_eq!(None, iter.next());
1179     }
1180
1181     #[test]
1182     fn comment_code_slices_three() {
1183         let input = "1 // comment\n    // comment2\n\n";
1184         let mut iter = CommentCodeSlices::new(input);
1185
1186         assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
1187         assert_eq!(
1188             (CodeCharKind::Comment, 2, "// comment\n    // comment2\n"),
1189             iter.next().unwrap()
1190         );
1191         assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
1192         assert_eq!(None, iter.next());
1193     }
1194
1195     #[test]
1196     #[cfg_attr(rustfmt, rustfmt_skip)]
1197     fn format_comments() {
1198         let mut config: ::config::Config = Default::default();
1199         config.set().wrap_comments(true);
1200         config.set().normalize_comments(true);
1201
1202         let comment = rewrite_comment(" //test",
1203                                       true,
1204                                       Shape::legacy(100, Indent::new(0, 100)),
1205                                       &config).unwrap();
1206         assert_eq!("/* test */", comment);
1207
1208         let comment = rewrite_comment("// comment on a",
1209                                       false,
1210                                       Shape::legacy(10, Indent::empty()),
1211                                       &config).unwrap();
1212         assert_eq!("// comment\n// on a", comment);
1213
1214         let comment = rewrite_comment("//  A multi line comment\n             // between args.",
1215                                       false,
1216                                       Shape::legacy(60, Indent::new(0, 12)),
1217                                       &config).unwrap();
1218         assert_eq!("//  A multi line comment\n            // between args.", comment);
1219
1220         let input = "// comment";
1221         let expected =
1222             "/* comment */";
1223         let comment = rewrite_comment(input,
1224                                       true,
1225                                       Shape::legacy(9, Indent::new(0, 69)),
1226                                       &config).unwrap();
1227         assert_eq!(expected, comment);
1228
1229         let comment = rewrite_comment("/*   trimmed    */",
1230                                       true,
1231                                       Shape::legacy(100, Indent::new(0, 100)),
1232                                       &config).unwrap();
1233         assert_eq!("/* trimmed */", comment);
1234     }
1235
1236     // This is probably intended to be a non-test fn, but it is not used. I'm
1237     // keeping it around unless it helps us test stuff.
1238     fn uncommented(text: &str) -> String {
1239         CharClasses::new(text.chars())
1240             .filter_map(|(s, c)| match s {
1241                 FullCodeCharKind::Normal | FullCodeCharKind::InString => Some(c),
1242                 _ => None,
1243             })
1244             .collect()
1245     }
1246
1247     #[test]
1248     fn test_uncommented() {
1249         assert_eq!(&uncommented("abc/*...*/"), "abc");
1250         assert_eq!(
1251             &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
1252             "..ac\n"
1253         );
1254         assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
1255     }
1256
1257     #[test]
1258     fn test_contains_comment() {
1259         assert_eq!(contains_comment("abc"), false);
1260         assert_eq!(contains_comment("abc // qsdf"), true);
1261         assert_eq!(contains_comment("abc /* kqsdf"), true);
1262         assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
1263     }
1264
1265     #[test]
1266     fn test_find_uncommented() {
1267         fn check(haystack: &str, needle: &str, expected: Option<usize>) {
1268             assert_eq!(expected, haystack.find_uncommented(needle));
1269         }
1270
1271         check("/*/ */test", "test", Some(6));
1272         check("//test\ntest", "test", Some(7));
1273         check("/* comment only */", "whatever", None);
1274         check(
1275             "/* comment */ some text /* more commentary */ result",
1276             "result",
1277             Some(46),
1278         );
1279         check("sup // sup", "p", Some(2));
1280         check("sup", "x", None);
1281         check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
1282         check("/*sup yo? \n sup*/ sup", "p", Some(20));
1283         check("hel/*lohello*/lo", "hello", None);
1284         check("acb", "ab", None);
1285         check(",/*A*/ ", ",", Some(0));
1286         check("abc", "abc", Some(0));
1287         check("/* abc */", "abc", None);
1288         check("/**/abc/* */", "abc", Some(4));
1289         check("\"/* abc */\"", "abc", Some(4));
1290         check("\"/* abc", "abc", Some(4));
1291     }
1292 }