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