]> git.lizzy.rs Git - rust.git/blob - src/comment.rs
Merge pull request #370 from marcusklaas/match-arm-delining
[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 {
31         ("// ", "", "// ")
32     };
33
34     let max_chars = width.checked_sub(closer.len() + opener.len()).unwrap_or(1);
35
36     let fmt = StringFormat {
37         opener: "",
38         closer: "",
39         line_start: line_start,
40         line_end: "",
41         width: max_chars,
42         offset: offset + (opener.len() - line_start.len()),
43         trim_end: true,
44         config: config,
45     };
46
47     let indent_str = offset.to_string(config);
48     let line_breaks = s.chars().filter(|&c| c == '\n').count();
49
50     let lines = s.lines()
51                  .enumerate()
52                  .map(|(i, mut line)| {
53                      line = line.trim();
54                      // Drop old closer.
55                      if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
56                          line = &line[..(line.len() - 2)];
57                      }
58
59                      line.trim_right()
60                  })
61                  .map(left_trim_comment_line)
62                  .map(|line| {
63                      if line_breaks == 0 {
64                          line.trim_left()
65                      } else {
66                          line
67                      }
68                  });
69
70     let mut result = opener.to_owned();
71     let mut first = true;
72
73     for line in lines {
74         if !first {
75             result.push('\n');
76             result.push_str(&indent_str);
77             result.push_str(line_start);
78         }
79
80         if line.len() > max_chars {
81             let rewrite = try_opt!(rewrite_string(line, &fmt));
82             result.push_str(&rewrite);
83         } else {
84             if line.len() == 0 {
85                 result.pop(); // Remove space if this is an empty comment.
86             } else {
87                 result.push_str(line);
88             }
89         }
90
91         first = false;
92     }
93
94     result.push_str(closer);
95
96     Some(result)
97 }
98
99 fn left_trim_comment_line(line: &str) -> &str {
100     if line.starts_with("/* ") || line.starts_with("// ") {
101         &line[3..]
102     } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") {
103         &line[2..]
104     } else if line.starts_with("*") {
105         &line[1..]
106     } else {
107         line
108     }
109 }
110
111 pub trait FindUncommented {
112     fn find_uncommented(&self, pat: &str) -> Option<usize>;
113 }
114
115 impl FindUncommented for str {
116     fn find_uncommented(&self, pat: &str) -> Option<usize> {
117         let mut needle_iter = pat.chars();
118         for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
119             match needle_iter.next() {
120                 None => {
121                     return Some(i - pat.len());
122                 }
123                 Some(c) => match kind {
124                     CodeCharKind::Normal if b == c => {}
125                     _ => {
126                         needle_iter = pat.chars();
127                     }
128                 },
129             }
130         }
131
132         // Handle case where the pattern is a suffix of the search string
133         match needle_iter.next() {
134             Some(_) => None,
135             None => Some(self.len() - pat.len()),
136         }
137     }
138 }
139
140 // Returns the first byte position after the first comment. The given string
141 // is expected to be prefixed by a comment, including delimiters.
142 // Good: "/* /* inner */ outer */ code();"
143 // Bad:  "code(); // hello\n world!"
144 pub fn find_comment_end(s: &str) -> Option<usize> {
145     let mut iter = CharClasses::new(s.char_indices());
146     for (kind, (i, _c)) in &mut iter {
147         if kind == CodeCharKind::Normal {
148             return Some(i);
149         }
150     }
151
152     // Handle case where the comment ends at the end of s.
153     if iter.status == CharClassesStatus::Normal {
154         Some(s.len())
155     } else {
156         None
157     }
158 }
159
160 /// Returns true if text contains any comment.
161 pub fn contains_comment(text: &str) -> bool {
162     CharClasses::new(text.chars()).any(|(kind, _)| kind == CodeCharKind::Comment)
163 }
164
165 struct CharClasses<T>
166     where T: Iterator,
167           T::Item: RichChar
168 {
169     base: iter::Peekable<T>,
170     status: CharClassesStatus,
171 }
172
173 trait RichChar {
174     fn get_char(&self) -> char;
175 }
176
177 impl RichChar for char {
178     fn get_char(&self) -> char {
179         *self
180     }
181 }
182
183 impl RichChar for (usize, char) {
184     fn get_char(&self) -> char {
185         self.1
186     }
187 }
188
189 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
190 enum CharClassesStatus {
191     Normal,
192     LitString,
193     LitStringEscape,
194     LitChar,
195     LitCharEscape,
196     // The u32 is the nesting deepness of the comment
197     BlockComment(u32),
198     // Status when the '/' has been consumed, but not yet the '*', deepness is the new deepness
199     // (after the comment opening).
200     BlockCommentOpening(u32),
201     // Status when the '*' has been consumed, but not yet the '/', deepness is the new deepness
202     // (after the comment closing).
203     BlockCommentClosing(u32),
204     LineComment,
205 }
206
207 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
208 enum CodeCharKind {
209     Normal,
210     Comment,
211 }
212
213 impl<T> CharClasses<T> where T: Iterator, T::Item: RichChar {
214     fn new(base: T) -> CharClasses<T> {
215         CharClasses {
216             base: base.peekable(),
217             status: CharClassesStatus::Normal,
218         }
219     }
220 }
221
222 impl<T> Iterator for CharClasses<T> where T: Iterator, T::Item: RichChar {
223     type Item = (CodeCharKind, T::Item);
224
225     fn next(&mut self) -> Option<(CodeCharKind, T::Item)> {
226         let item = try_opt!(self.base.next());
227         let chr = item.get_char();
228         self.status = match self.status {
229             CharClassesStatus::LitString => match chr {
230                 '"' => CharClassesStatus::Normal,
231                 '\\' => CharClassesStatus::LitStringEscape,
232                 _ => CharClassesStatus::LitString,
233             },
234             CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
235             CharClassesStatus::LitChar => match chr {
236                 '\\' => CharClassesStatus::LitCharEscape,
237                 '\'' => CharClassesStatus::Normal,
238                 _ => CharClassesStatus::LitChar,
239             },
240             CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
241             CharClassesStatus::Normal => {
242                 match chr {
243                     '"' => CharClassesStatus::LitString,
244                     '\'' => CharClassesStatus::LitChar,
245                     '/' => match self.base.peek() {
246                         Some(next) if next.get_char() == '*' => {
247                             self.status = CharClassesStatus::BlockCommentOpening(1);
248                             return Some((CodeCharKind::Comment, item));
249                         }
250                         Some(next) if next.get_char() == '/' => {
251                             self.status = CharClassesStatus::LineComment;
252                             return Some((CodeCharKind::Comment, item));
253                         }
254                         _ => CharClassesStatus::Normal,
255                     },
256                     _ => CharClassesStatus::Normal,
257                 }
258             }
259             CharClassesStatus::BlockComment(deepness) => {
260                 if deepness == 0 {
261                     // This is the closing '/'
262                     assert_eq!(chr, '/');
263                     self.status = CharClassesStatus::Normal;
264                     return Some((CodeCharKind::Comment, item));
265                 }
266                 self.status = match self.base.peek() {
267                     Some(next) if next.get_char() == '/' && chr == '*' =>
268                         CharClassesStatus::BlockCommentClosing(deepness - 1),
269                     Some(next) if next.get_char() == '*' && chr == '/' =>
270                         CharClassesStatus::BlockCommentOpening(deepness + 1),
271                     _ => CharClassesStatus::BlockComment(deepness),
272                 };
273                 return Some((CodeCharKind::Comment, item));
274             }
275             CharClassesStatus::BlockCommentOpening(deepness) => {
276                 assert_eq!(chr, '*');
277                 self.status = CharClassesStatus::BlockComment(deepness);
278                 return Some((CodeCharKind::Comment, item));
279             }
280             CharClassesStatus::BlockCommentClosing(deepness) => {
281                 assert_eq!(chr, '/');
282                 self.status = if deepness == 0 {
283                     CharClassesStatus::Normal
284                 } else {
285                     CharClassesStatus::BlockComment(deepness)
286                 };
287                 return Some((CodeCharKind::Comment, item));
288             }
289             CharClassesStatus::LineComment => {
290                 self.status = match chr {
291                     '\n' => CharClassesStatus::Normal,
292                     _ => CharClassesStatus::LineComment,
293                 };
294                 return Some((CodeCharKind::Comment, item));
295             }
296         };
297         Some((CodeCharKind::Normal, item))
298     }
299 }
300
301 #[cfg(test)]
302 mod test {
303     use super::{CharClasses, CodeCharKind, contains_comment, rewrite_comment, FindUncommented};
304     use Indent;
305
306     #[test]
307     #[rustfmt_skip]
308     fn format_comments() {
309         let config = Default::default();
310         assert_eq!("/* test */", rewrite_comment(" //test", true, 100, Indent::new(0, 100),
311                                                  &config).unwrap());
312         assert_eq!("// comment\n// on a", rewrite_comment("// comment on a", false, 10,
313                                                           Indent::empty(), &config).unwrap());
314
315         assert_eq!("//  A multi line comment\n            // between args.",
316                    rewrite_comment("//  A multi line comment\n             // between args.",
317                                    false,
318                                    60,
319                                    Indent::new(0, 12),
320                                    &config).unwrap());
321
322         let input = "// comment";
323         let expected =
324             "/* com\n                                                                      \
325              * men\n                                                                      \
326              * t */";
327         assert_eq!(expected, rewrite_comment(input, true, 9, Indent::new(0, 69), &config).unwrap());
328
329         assert_eq!("/* trimmed */", rewrite_comment("/*   trimmed    */", true, 100,
330                                                     Indent::new(0, 100), &config).unwrap());
331     }
332
333     // This is probably intended to be a non-test fn, but it is not used. I'm
334     // keeping it around unless it helps us test stuff.
335     fn uncommented(text: &str) -> String {
336         CharClasses::new(text.chars())
337             .filter_map(|(s, c)| {
338                 match s {
339                     CodeCharKind::Normal => Some(c),
340                     CodeCharKind::Comment => None,
341                 }
342             })
343             .collect()
344     }
345
346     #[test]
347     fn test_uncommented() {
348         assert_eq!(&uncommented("abc/*...*/"), "abc");
349         assert_eq!(&uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
350                    "..ac\n");
351         assert_eq!(&uncommented("abc \" /* */\" qsdf"),
352                    "abc \" /* */\" qsdf");
353     }
354
355     #[test]
356     fn test_contains_comment() {
357         assert_eq!(contains_comment("abc"), false);
358         assert_eq!(contains_comment("abc // qsdf"), true);
359         assert_eq!(contains_comment("abc /* kqsdf"), true);
360         assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
361     }
362
363     #[test]
364     fn test_find_uncommented() {
365         fn check(haystack: &str, needle: &str, expected: Option<usize>) {
366             println!("haystack {:?}, needle: {:?}", haystack, needle);
367             assert_eq!(expected, haystack.find_uncommented(needle));
368         }
369
370         check("/*/ */test", "test", Some(6));
371         check("//test\ntest", "test", Some(7));
372         check("/* comment only */", "whatever", None);
373         check("/* comment */ some text /* more commentary */ result",
374               "result",
375               Some(46));
376         check("sup // sup", "p", Some(2));
377         check("sup", "x", None);
378         check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
379         check("/*sup yo? \n sup*/ sup", "p", Some(20));
380         check("hel/*lohello*/lo", "hello", None);
381         check("acb", "ab", None);
382         check(",/*A*/ ", ",", Some(0));
383         check("abc", "abc", Some(0));
384         check("/* abc */", "abc", None);
385         check("/**/abc/* */", "abc", Some(4));
386         check("\"/* abc */\"", "abc", Some(4));
387         check("\"/* abc", "abc", Some(4));
388     }
389 }