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