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