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