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