]> git.lizzy.rs Git - rust.git/blob - src/comment.rs
Merge pull request #309 from marcusklaas/array-literals
[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()),
63                             |(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 /// Returns true if text contains any comment.
150 pub fn contains_comment(text: &str) -> bool {
151     CharClasses::new(text.chars()).any(|(kind, _)| kind == CodeCharKind::Comment)
152 }
153
154 struct CharClasses<T>
155     where T: Iterator,
156           T::Item: RichChar
157 {
158     base: iter::Peekable<T>,
159     status: CharClassesStatus,
160 }
161
162 trait RichChar {
163     fn get_char(&self) -> char;
164 }
165
166 impl RichChar for char {
167     fn get_char(&self) -> char {
168         *self
169     }
170 }
171
172 impl RichChar for (usize, char) {
173     fn get_char(&self) -> char {
174         self.1
175     }
176 }
177
178 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
179 enum CharClassesStatus {
180     Normal,
181     LitString,
182     LitStringEscape,
183     LitChar,
184     LitCharEscape,
185     // The u32 is the nesting deepness of the comment
186     BlockComment(u32),
187     // Status when the '/' has been consumed, but not yet the '*', deepness is the new deepness
188     // (after the comment opening).
189     BlockCommentOpening(u32),
190     // Status when the '*' has been consumed, but not yet the '/', deepness is the new deepness
191     // (after the comment closing).
192     BlockCommentClosing(u32),
193     LineComment,
194 }
195
196 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
197 enum CodeCharKind {
198     Normal,
199     Comment,
200 }
201
202 impl<T> CharClasses<T> where T: Iterator, T::Item: RichChar {
203     fn new(base: T) -> CharClasses<T> {
204         CharClasses { base: base.peekable(), status: CharClassesStatus::Normal }
205     }
206 }
207
208 impl<T> Iterator for CharClasses<T> where T: Iterator, T::Item: RichChar {
209     type Item = (CodeCharKind, T::Item);
210
211     fn next(&mut self) -> Option<(CodeCharKind, T::Item)> {
212         let item = try_opt!(self.base.next());
213         let chr = item.get_char();
214         self.status = match self.status {
215             CharClassesStatus::LitString => match chr {
216                 '"' => CharClassesStatus::Normal,
217                 '\\' => CharClassesStatus::LitStringEscape,
218                 _ => CharClassesStatus::LitString,
219             },
220             CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
221             CharClassesStatus::LitChar => match chr {
222                 '\\' => CharClassesStatus::LitCharEscape,
223                 '\'' => CharClassesStatus::Normal,
224                 _ => CharClassesStatus::LitChar,
225             },
226             CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
227             CharClassesStatus::Normal => {
228                 match chr {
229                     '"' => CharClassesStatus::LitString,
230                     '\'' => CharClassesStatus::LitChar,
231                     '/' => match self.base.peek() {
232                         Some(next) if next.get_char() == '*' => {
233                             self.status = CharClassesStatus::BlockCommentOpening(1);
234                             return Some((CodeCharKind::Comment, item));
235                         }
236                         Some(next) if next.get_char() == '/' => {
237                             self.status = CharClassesStatus::LineComment;
238                             return Some((CodeCharKind::Comment, item));
239                         }
240                         _ => CharClassesStatus::Normal,
241                     },
242                     _ => CharClassesStatus::Normal,
243                 }
244             }
245             CharClassesStatus::BlockComment(deepness) => {
246                 if deepness == 0 {
247                     // This is the closing '/'
248                     assert_eq!(chr, '/');
249                     self.status = CharClassesStatus::Normal;
250                     return Some((CodeCharKind::Comment, item));
251                 }
252                 self.status = match self.base.peek() {
253                     Some(next) if next.get_char() == '/' && chr == '*' =>
254                         CharClassesStatus::BlockCommentClosing(deepness - 1),
255                     Some(next) if next.get_char() == '*' && chr == '/' =>
256                         CharClassesStatus::BlockCommentOpening(deepness + 1),
257                     _ => CharClassesStatus::BlockComment(deepness),
258                 };
259                 return Some((CodeCharKind::Comment, item));
260             }
261             CharClassesStatus::BlockCommentOpening(deepness) => {
262                 assert_eq!(chr, '*');
263                 self.status = CharClassesStatus::BlockComment(deepness);
264                 return Some((CodeCharKind::Comment, item));
265             }
266             CharClassesStatus::BlockCommentClosing(deepness) => {
267                 assert_eq!(chr, '/');
268                 self.status = if deepness == 0 {
269                     CharClassesStatus::Normal
270                 } else {
271                     CharClassesStatus::BlockComment(deepness)
272                 };
273                 return Some((CodeCharKind::Comment, item));
274             }
275             CharClassesStatus::LineComment => {
276                 self.status = match chr {
277                     '\n' => CharClassesStatus::Normal,
278                     _ => CharClassesStatus::LineComment,
279                 };
280                 return Some((CodeCharKind::Comment, item));
281             }
282         };
283         Some((CodeCharKind::Normal, item))
284     }
285 }
286
287 #[cfg(test)]
288 mod test {
289     use super::{CharClasses, CodeCharKind, contains_comment, rewrite_comment, FindUncommented};
290
291     #[test]
292     fn format_comments() {
293         assert_eq!("/* test */", rewrite_comment(" //test", true, 100, 100));
294         assert_eq!("// comment\n// on a", rewrite_comment("// comment on a", false, 10, 0));
295
296         assert_eq!("//  A multi line comment\n            // between args.",
297                    rewrite_comment("//  A multi line comment\n             // between args.",
298                                    false,
299                                    60,
300                                    12));
301
302         let input = "// comment";
303         let expected = "/* com\n                                                                      \
304                         * men\n                                                                      \
305                         * t */";
306         assert_eq!(expected, rewrite_comment(input, true, 9, 69));
307
308         assert_eq!("/* trimmed */", rewrite_comment("/*   trimmed    */", true, 100, 100));
309     }
310
311     // This is probably intended to be a non-test fn, but it is not used. I'm
312     // keeping it around unless it helps us test stuff.
313     fn uncommented(text: &str) -> String {
314         CharClasses::new(text.chars())
315             .filter_map(|(s, c)| {
316                 match s {
317                     CodeCharKind::Normal => Some(c),
318                     CodeCharKind::Comment => None,
319                 }
320             })
321             .collect()
322     }
323
324     #[test]
325     fn test_uncommented() {
326         assert_eq!(&uncommented("abc/*...*/"), "abc");
327         assert_eq!(&uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"), "..ac\n");
328         assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
329     }
330
331     #[test]
332     fn test_contains_comment() {
333         assert_eq!(contains_comment("abc"), false);
334         assert_eq!(contains_comment("abc // qsdf"), true);
335         assert_eq!(contains_comment("abc /* kqsdf"), true);
336         assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
337     }
338
339     #[test]
340     fn test_find_uncommented() {
341         fn check(haystack: &str, needle: &str, expected: Option<usize>) {
342             println!("haystack {:?}, needle: {:?}", haystack, needle);
343             assert_eq!(expected, haystack.find_uncommented(needle));
344         }
345
346         check("/*/ */test", "test", Some(6));
347         check("//test\ntest", "test", Some(7));
348         check("/* comment only */", "whatever", None);
349         check("/* comment */ some text /* more commentary */ result", "result", Some(46));
350         check("sup // sup", "p", Some(2));
351         check("sup", "x", None);
352         check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
353         check("/*sup yo? \n sup*/ sup", "p", Some(20));
354         check("hel/*lohello*/lo", "hello", None);
355         check("acb", "ab", None);
356         check(",/*A*/ ", ",", Some(0));
357         check("abc", "abc", Some(0));
358         check("/* abc */", "abc", None);
359         check("/**/abc/* */", "abc", Some(4));
360         check("\"/* abc */\"", "abc", Some(4));
361         check("\"/* abc", "abc", Some(4));
362     }
363 }