]> git.lizzy.rs Git - rust.git/blob - src/comment.rs
Format if-else expressions
[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 string::{StringFormat, rewrite_string};
14 use utils::make_indent;
15
16 pub fn rewrite_comment(orig: &str, block_style: bool, width: usize, offset: usize) -> String {
17     let s = orig.trim();
18
19     // Edge case: block comments. Let's not trim their lines (for now).
20     let (opener, closer, line_start) = if block_style {
21         ("/* ", " */", " * ")
22     } else {
23         ("// ", "", "// ")
24     };
25
26     let max_chars = width.checked_sub(closer.len()).unwrap_or(1)
27                          .checked_sub(opener.len()).unwrap_or(1);
28
29     let fmt = StringFormat {
30         opener: "",
31         closer: "",
32         line_start: line_start,
33         line_end: "",
34         width: max_chars,
35         offset: offset + opener.len() - line_start.len(),
36         trim_end: true,
37     };
38
39     let indent_str = make_indent(offset);
40     let line_breaks = s.chars().filter(|&c| c == '\n').count();
41
42     let (_, mut s) = s.lines().enumerate()
43         .map(|(i, mut line)| {
44             line = line.trim();
45
46             // Drop old closer.
47             if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
48                 line = &line[..(line.len() - 2)];
49             }
50
51             line.trim_right()
52         })
53         .map(left_trim_comment_line)
54         .map(|line| {
55             if line_breaks == 0 {
56                 line.trim_left()
57             } else {
58                 line
59             }
60         })
61         .fold((true, opener.to_owned()), |(first, mut acc), line| {
62             if !first {
63                 acc.push('\n');
64                 acc.push_str(&indent_str);
65                 acc.push_str(line_start);
66             }
67
68             if line.len() > max_chars {
69                 acc.push_str(&rewrite_string(line, &fmt));
70             } else {
71                 acc.push_str(line);
72             }
73
74             (false, acc)
75         });
76
77     s.push_str(closer);
78
79     s
80 }
81
82 fn left_trim_comment_line<'a>(line: &'a str) -> &'a str {
83     if line.starts_with("/* ") || line.starts_with("// ") {
84         &line[3..]
85     } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") {
86         &line[2..]
87     } else if line.starts_with("*") {
88         &line[1..]
89     } else {
90         line
91     }
92 }
93
94 #[test]
95 fn format_comments() {
96     assert_eq!("/* test */", rewrite_comment(" //test", true, 100, 100));
97     assert_eq!("// comment\n// on a", rewrite_comment("// comment on a", false, 10, 0));
98
99     assert_eq!("//  A multi line comment\n            // between args.",
100                rewrite_comment("//  A multi line comment\n             // between args.",
101                                false,
102                                60,
103                                12));
104
105     let input = "// comment";
106     let expected_output = "/* com\n                                                                      \
107                            * men\n                                                                      \
108                            * t */";
109     assert_eq!(expected_output, rewrite_comment(input, true, 9, 69));
110
111     assert_eq!("/* trimmed */", rewrite_comment("/*   trimmed    */", true, 100, 100));
112 }
113
114
115 pub trait FindUncommented {
116     fn find_uncommented(&self, pat: &str) -> Option<usize>;
117 }
118
119 impl FindUncommented for str {
120     fn find_uncommented(&self, pat: &str) -> Option<usize> {
121         let mut needle_iter = pat.chars();
122         let mut possible_comment = false;
123
124         for (i, b) in self.char_indices() {
125             match needle_iter.next() {
126                 Some(c) => {
127                     if b != c {
128                         needle_iter = pat.chars();
129                     }
130                 },
131                 None => return Some(i - pat.len())
132             }
133
134             if possible_comment && (b == '/' || b == '*') {
135                 return find_comment_end(&self[(i-1)..])
136                     .and_then(|end| {
137                         self[(end + i - 1)..].find_uncommented(pat)
138                                              .map(|idx| idx + end + i - 1)
139                     });
140             }
141
142             possible_comment = b == '/';
143         }
144
145         // Handle case where the pattern is a suffix of the search string
146         match needle_iter.next() {
147             Some(_) => None,
148             None => Some(self.len() - pat.len())
149         }
150     }
151 }
152
153 #[test]
154 fn test_find_uncommented() {
155     fn check(haystack: &str, needle: &str, expected: Option<usize>) {
156         println!("haystack {:?}, needle: {:?}", haystack, needle);
157         assert_eq!(expected, haystack.find_uncommented(needle));
158     }
159
160     check("/*/ */test", "test", Some(6));
161     check("//test\ntest", "test", Some(7));
162     check("/* comment only */", "whatever", None);
163     check("/* comment */ some text /* more commentary */ result", "result", Some(46));
164     check("sup // sup", "p", Some(2));
165     check("sup", "x", None);
166     check("π? /**/ π is nice!", "π is nice", Some(9));
167     check("/*sup yo? \n sup*/ sup", "p", Some(20));
168     check("hel/*lohello*/lo", "hello", None);
169     check("acb", "ab", None);
170     check(",/*A*/ ", ",", Some(0));
171 }
172
173 // Returns the first byte position after the first comment. The given string
174 // is expected to be prefixed by a comment, including delimiters.
175 // Good: "/* /* inner */ outer */ code();"
176 // Bad:  "code(); // hello\n world!"
177 pub fn find_comment_end(s: &str) -> Option<usize> {
178     if s.starts_with("//") {
179         s.find('\n').map(|idx| idx + 1)
180     } else {
181         // Block comment
182         let mut levels = 0;
183         let mut prev_char = 'a';
184
185         for (i, mut c) in s.char_indices() {
186             if c == '*' && prev_char == '/' {
187                 levels += 1;
188                 c = 'a'; // Invalidate prev_char
189             } else if c == '/' && prev_char == '*' {
190                 levels -= 1;
191
192                 if levels == 0 {
193                     return Some(i + 1);
194                 }
195                 c = 'a';
196             }
197
198             prev_char = c;
199         }
200
201         None
202     }
203 }
204
205 #[test]
206 fn comment_end() {
207     assert_eq!(Some(6), find_comment_end("// hi\n"));
208     assert_eq!(Some(9), find_comment_end("/* sup */ "));
209     assert_eq!(Some(9), find_comment_end("/*/**/ */ "));
210     assert_eq!(Some(6), find_comment_end("/*/ */ weird!"));
211     assert_eq!(None, find_comment_end("/* hi /* test */"));
212     assert_eq!(None, find_comment_end("// hi /* test */"));
213     assert_eq!(Some(9), find_comment_end("// hi /*\n."));
214 }