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