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