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