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