]> git.lizzy.rs Git - rust.git/blob - src/comment.rs
Blockify multiline match arms
[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 // Format comments.
12
13 use std::iter;
14
15 use Indent;
16 use config::Config;
17 use string::{StringFormat, rewrite_string};
18
19 pub fn rewrite_comment(orig: &str,
20                        block_style: bool,
21                        width: usize,
22                        offset: Indent,
23                        config: &Config)
24                        -> Option<String> {
25     let s = orig.trim();
26
27     // Edge case: block comments. Let's not trim their lines (for now).
28     let (opener, closer, line_start) = if block_style {
29         ("/* ", " */", " * ")
30     } else if orig.starts_with("///") {
31         ("/// ", "", "/// ")
32     } else if orig.starts_with("//!") {
33         ("//! ", "", "//! ")
34     } else {
35         ("// ", "", "// ")
36     };
37
38     let max_chars = width.checked_sub(closer.len() + opener.len()).unwrap_or(1);
39
40     let fmt = StringFormat {
41         opener: "",
42         closer: "",
43         line_start: line_start,
44         line_end: "",
45         width: max_chars,
46         offset: offset + (opener.len() - line_start.len()),
47         trim_end: true,
48         config: config,
49     };
50
51     let indent_str = offset.to_string(config);
52     let line_breaks = s.chars().filter(|&c| c == '\n').count();
53
54     let lines = s.lines()
55                  .enumerate()
56                  .map(|(i, mut line)| {
57                      line = line.trim();
58                      // Drop old closer.
59                      if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
60                          line = &line[..(line.len() - 2)];
61                      }
62
63                      line.trim_right()
64                  })
65                  .map(left_trim_comment_line)
66                  .map(|line| {
67                      if line_breaks == 0 {
68                          line.trim_left()
69                      } else {
70                          line
71                      }
72                  });
73
74     let mut result = opener.to_owned();
75     let mut first = true;
76
77     for line in lines {
78         if !first {
79             result.push('\n');
80             result.push_str(&indent_str);
81             result.push_str(line_start);
82         }
83
84         if config.wrap_comments && line.len() > max_chars {
85             let rewrite = try_opt!(rewrite_string(line, &fmt));
86             result.push_str(&rewrite);
87         } else {
88             if line.len() == 0 {
89                 // Remove space if this is an empty comment or a doc comment.
90                 result.pop();
91             }
92             result.push_str(line);
93         }
94
95         first = false;
96     }
97
98     result.push_str(closer);
99
100     Some(result)
101 }
102
103 fn left_trim_comment_line(line: &str) -> &str {
104     if line.starts_with("//! ") || line.starts_with("/// ") {
105         &line[4..]
106     } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!") ||
107        line.starts_with("///") {
108         &line[3..]
109     } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") {
110         &line[2..]
111     } else if line.starts_with("*") {
112         &line[1..]
113     } else {
114         line
115     }
116 }
117
118 pub trait FindUncommented {
119     fn find_uncommented(&self, pat: &str) -> Option<usize>;
120 }
121
122 impl FindUncommented for str {
123     fn find_uncommented(&self, pat: &str) -> Option<usize> {
124         let mut needle_iter = pat.chars();
125         for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
126             match needle_iter.next() {
127                 None => {
128                     return Some(i - pat.len());
129                 }
130                 Some(c) => {
131                     match kind {
132                         CodeCharKind::Normal if b == c => {}
133                         _ => {
134                             needle_iter = pat.chars();
135                         }
136                     }
137                 }
138             }
139         }
140
141         // Handle case where the pattern is a suffix of the search string
142         match needle_iter.next() {
143             Some(_) => None,
144             None => Some(self.len() - pat.len()),
145         }
146     }
147 }
148
149 // Returns the first byte position after the first comment. The given string
150 // is expected to be prefixed by a comment, including delimiters.
151 // Good: "/* /* inner */ outer */ code();"
152 // Bad:  "code(); // hello\n world!"
153 pub fn find_comment_end(s: &str) -> Option<usize> {
154     let mut iter = CharClasses::new(s.char_indices());
155     for (kind, (i, _c)) in &mut iter {
156         if kind == CodeCharKind::Normal {
157             return Some(i);
158         }
159     }
160
161     // Handle case where the comment ends at the end of s.
162     if iter.status == CharClassesStatus::Normal {
163         Some(s.len())
164     } else {
165         None
166     }
167 }
168
169 /// Returns true if text contains any comment.
170 pub fn contains_comment(text: &str) -> bool {
171     CharClasses::new(text.chars()).any(|(kind, _)| kind == CodeCharKind::Comment)
172 }
173
174 struct CharClasses<T>
175     where T: Iterator,
176           T::Item: RichChar
177 {
178     base: iter::Peekable<T>,
179     status: CharClassesStatus,
180 }
181
182 trait RichChar {
183     fn get_char(&self) -> char;
184 }
185
186 impl RichChar for char {
187     fn get_char(&self) -> char {
188         *self
189     }
190 }
191
192 impl RichChar for (usize, char) {
193     fn get_char(&self) -> char {
194         self.1
195     }
196 }
197
198 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
199 enum CharClassesStatus {
200     Normal,
201     LitString,
202     LitStringEscape,
203     LitChar,
204     LitCharEscape,
205     // The u32 is the nesting deepness of the comment
206     BlockComment(u32),
207     // Status when the '/' has been consumed, but not yet the '*', deepness is
208     // the new deepness (after the comment opening).
209     BlockCommentOpening(u32),
210     // Status when the '*' has been consumed, but not yet the '/', deepness is
211     // the new deepness (after the comment closing).
212     BlockCommentClosing(u32),
213     LineComment,
214 }
215
216 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
217 pub enum CodeCharKind {
218     Normal,
219     Comment,
220 }
221
222 impl<T> CharClasses<T> where T: Iterator, T::Item: RichChar {
223     fn new(base: T) -> CharClasses<T> {
224         CharClasses {
225             base: base.peekable(),
226             status: CharClassesStatus::Normal,
227         }
228     }
229 }
230
231 impl<T> Iterator for CharClasses<T> where T: Iterator, T::Item: RichChar {
232     type Item = (CodeCharKind, T::Item);
233
234     fn next(&mut self) -> Option<(CodeCharKind, T::Item)> {
235         let item = try_opt!(self.base.next());
236         let chr = item.get_char();
237         self.status = match self.status {
238             CharClassesStatus::LitString => {
239                 match chr {
240                     '"' => CharClassesStatus::Normal,
241                     '\\' => CharClassesStatus::LitStringEscape,
242                     _ => CharClassesStatus::LitString,
243                 }
244             }
245             CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
246             CharClassesStatus::LitChar => {
247                 match chr {
248                     '\\' => CharClassesStatus::LitCharEscape,
249                     '\'' => CharClassesStatus::Normal,
250                     _ => CharClassesStatus::LitChar,
251                 }
252             }
253             CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
254             CharClassesStatus::Normal => {
255                 match chr {
256                     '"' => CharClassesStatus::LitString,
257                     '\'' => CharClassesStatus::LitChar,
258                     '/' => {
259                         match self.base.peek() {
260                             Some(next) if next.get_char() == '*' => {
261                                 self.status = CharClassesStatus::BlockCommentOpening(1);
262                                 return Some((CodeCharKind::Comment, item));
263                             }
264                             Some(next) if next.get_char() == '/' => {
265                                 self.status = CharClassesStatus::LineComment;
266                                 return Some((CodeCharKind::Comment, item));
267                             }
268                             _ => CharClassesStatus::Normal,
269                         }
270                     }
271                     _ => CharClassesStatus::Normal,
272                 }
273             }
274             CharClassesStatus::BlockComment(deepness) => {
275                 if deepness == 0 {
276                     // This is the closing '/'
277                     assert_eq!(chr, '/');
278                     self.status = CharClassesStatus::Normal;
279                     return Some((CodeCharKind::Comment, item));
280                 }
281                 self.status = match self.base.peek() {
282                     Some(next) if next.get_char() == '/' && chr == '*' => {
283                         CharClassesStatus::BlockCommentClosing(deepness - 1)
284                     }
285                     Some(next) if next.get_char() == '*' && chr == '/' => {
286                         CharClassesStatus::BlockCommentOpening(deepness + 1)
287                     }
288                     _ => CharClassesStatus::BlockComment(deepness),
289                 };
290                 return Some((CodeCharKind::Comment, item));
291             }
292             CharClassesStatus::BlockCommentOpening(deepness) => {
293                 assert_eq!(chr, '*');
294                 self.status = CharClassesStatus::BlockComment(deepness);
295                 return Some((CodeCharKind::Comment, item));
296             }
297             CharClassesStatus::BlockCommentClosing(deepness) => {
298                 assert_eq!(chr, '/');
299                 self.status = if deepness == 0 {
300                     CharClassesStatus::Normal
301                 } else {
302                     CharClassesStatus::BlockComment(deepness)
303                 };
304                 return Some((CodeCharKind::Comment, item));
305             }
306             CharClassesStatus::LineComment => {
307                 self.status = match chr {
308                     '\n' => CharClassesStatus::Normal,
309                     _ => CharClassesStatus::LineComment,
310                 };
311                 return Some((CodeCharKind::Comment, item));
312             }
313         };
314         Some((CodeCharKind::Normal, item))
315     }
316 }
317
318 /// Iterator over an alternating sequence of functional and commented parts of
319 /// a string. The first item is always a, possibly zero length, subslice of
320 /// functional text. Line style comments contain their ending newlines.
321 pub struct CommentCodeSlices<'a> {
322     slice: &'a str,
323     last_slice_kind: CodeCharKind,
324     last_slice_end: usize,
325 }
326
327 impl<'a> CommentCodeSlices<'a> {
328     pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
329         CommentCodeSlices {
330             slice: slice,
331             last_slice_kind: CodeCharKind::Comment,
332             last_slice_end: 0,
333         }
334     }
335 }
336
337 impl<'a> Iterator for CommentCodeSlices<'a> {
338     type Item = (CodeCharKind, usize, &'a str);
339
340     fn next(&mut self) -> Option<Self::Item> {
341         if self.last_slice_end == self.slice.len() {
342             return None;
343         }
344
345         let mut sub_slice_end = self.last_slice_end;
346         let mut first_whitespace = None;
347         let subslice = &self.slice[self.last_slice_end..];
348         let mut iter = CharClasses::new(subslice.char_indices());
349
350         for (kind, (i, c)) in &mut iter {
351             let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
352                                        &subslice[..2] == "//" &&
353                                        [' ', '\t'].contains(&c);
354
355             if is_comment_connector && first_whitespace.is_none() {
356                 first_whitespace = Some(i);
357             }
358
359             if kind == self.last_slice_kind && !is_comment_connector {
360                 let last_index = match first_whitespace {
361                     Some(j) => j,
362                     None => i,
363                 };
364                 sub_slice_end = self.last_slice_end + last_index;
365                 break;
366             }
367
368             if !is_comment_connector {
369                 first_whitespace = None;
370             }
371         }
372
373         if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
374             // This was the last subslice.
375             sub_slice_end = match first_whitespace {
376                 Some(i) => self.last_slice_end + i,
377                 None => self.slice.len(),
378             };
379         }
380
381         let kind = match self.last_slice_kind {
382             CodeCharKind::Comment => CodeCharKind::Normal,
383             CodeCharKind::Normal => CodeCharKind::Comment,
384         };
385         let res = (kind,
386                    self.last_slice_end,
387                    &self.slice[self.last_slice_end..sub_slice_end]);
388         self.last_slice_end = sub_slice_end;
389         self.last_slice_kind = kind;
390
391         Some(res)
392     }
393 }
394
395 #[cfg(test)]
396 mod test {
397     use super::{CharClasses, CodeCharKind, contains_comment, rewrite_comment, FindUncommented,
398                 CommentCodeSlices};
399     use Indent;
400
401     #[test]
402     fn char_classes() {
403         let mut iter = CharClasses::new("//\n\n".chars());
404
405         assert_eq!((CodeCharKind::Comment, '/'), iter.next().unwrap());
406         assert_eq!((CodeCharKind::Comment, '/'), iter.next().unwrap());
407         assert_eq!((CodeCharKind::Comment, '\n'), iter.next().unwrap());
408         assert_eq!((CodeCharKind::Normal, '\n'), iter.next().unwrap());
409         assert_eq!(None, iter.next());
410     }
411
412     #[test]
413     fn comment_code_slices() {
414         let input = "code(); /* test */ 1 + 1";
415         let mut iter = CommentCodeSlices::new(input);
416
417         assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
418         assert_eq!((CodeCharKind::Comment, 8, "/* test */"),
419                    iter.next().unwrap());
420         assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
421         assert_eq!(None, iter.next());
422     }
423
424     #[test]
425     fn comment_code_slices_two() {
426         let input = "// comment\n    test();";
427         let mut iter = CommentCodeSlices::new(input);
428
429         assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
430         assert_eq!((CodeCharKind::Comment, 0, "// comment\n"),
431                    iter.next().unwrap());
432         assert_eq!((CodeCharKind::Normal, 11, "    test();"),
433                    iter.next().unwrap());
434         assert_eq!(None, iter.next());
435     }
436
437     #[test]
438     fn comment_code_slices_three() {
439         let input = "1 // comment\n    // comment2\n\n";
440         let mut iter = CommentCodeSlices::new(input);
441
442         assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
443         assert_eq!((CodeCharKind::Comment, 2, "// comment\n    // comment2\n"),
444                    iter.next().unwrap());
445         assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
446         assert_eq!(None, iter.next());
447     }
448
449     #[test]
450     #[cfg_attr(rustfmt, rustfmt_skip)]
451     fn format_comments() {
452         let mut config: ::config::Config = Default::default();
453         config.wrap_comments = true;
454         assert_eq!("/* test */", rewrite_comment(" //test", true, 100, Indent::new(0, 100),
455                                                  &config).unwrap());
456         assert_eq!("// comment\n// on a", rewrite_comment("// comment on a", false, 10,
457                                                           Indent::empty(), &config).unwrap());
458
459         assert_eq!("//  A multi line comment\n            // between args.",
460                    rewrite_comment("//  A multi line comment\n             // between args.",
461                                    false,
462                                    60,
463                                    Indent::new(0, 12),
464                                    &config).unwrap());
465
466         let input = "// comment";
467         let expected =
468             "/* com\n                                                                      \
469              * men\n                                                                      \
470              * t */";
471         assert_eq!(expected, rewrite_comment(input, true, 9, Indent::new(0, 69), &config).unwrap());
472
473         assert_eq!("/* trimmed */", rewrite_comment("/*   trimmed    */", true, 100,
474                                                     Indent::new(0, 100), &config).unwrap());
475     }
476
477     // This is probably intended to be a non-test fn, but it is not used. I'm
478     // keeping it around unless it helps us test stuff.
479     fn uncommented(text: &str) -> String {
480         CharClasses::new(text.chars())
481             .filter_map(|(s, c)| {
482                 match s {
483                     CodeCharKind::Normal => Some(c),
484                     CodeCharKind::Comment => None,
485                 }
486             })
487             .collect()
488     }
489
490     #[test]
491     fn test_uncommented() {
492         assert_eq!(&uncommented("abc/*...*/"), "abc");
493         assert_eq!(&uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
494                    "..ac\n");
495         assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
496     }
497
498     #[test]
499     fn test_contains_comment() {
500         assert_eq!(contains_comment("abc"), false);
501         assert_eq!(contains_comment("abc // qsdf"), true);
502         assert_eq!(contains_comment("abc /* kqsdf"), true);
503         assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
504     }
505
506     #[test]
507     fn test_find_uncommented() {
508         fn check(haystack: &str, needle: &str, expected: Option<usize>) {
509             assert_eq!(expected, haystack.find_uncommented(needle));
510         }
511
512         check("/*/ */test", "test", Some(6));
513         check("//test\ntest", "test", Some(7));
514         check("/* comment only */", "whatever", None);
515         check("/* comment */ some text /* more commentary */ result",
516               "result",
517               Some(46));
518         check("sup // sup", "p", Some(2));
519         check("sup", "x", None);
520         check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
521         check("/*sup yo? \n sup*/ sup", "p", Some(20));
522         check("hel/*lohello*/lo", "hello", None);
523         check("acb", "ab", None);
524         check(",/*A*/ ", ",", Some(0));
525         check("abc", "abc", Some(0));
526         check("/* abc */", "abc", None);
527         check("/**/abc/* */", "abc", Some(4));
528         check("\"/* abc */\"", "abc", Some(4));
529         check("\"/* abc", "abc", Some(4));
530     }
531 }