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.
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.
17 use string::{StringFormat, rewrite_string};
19 pub fn rewrite_comment(orig: &str,
27 // Edge case: block comments. Let's not trim their lines (for now).
28 let (opener, closer, line_start) = if block_style {
34 let max_chars = width.checked_sub(closer.len() + opener.len()).unwrap_or(1);
36 let fmt = StringFormat {
39 line_start: line_start,
42 offset: offset + (opener.len() - line_start.len()),
47 let indent_str = offset.to_string(config);
48 let line_breaks = s.chars().filter(|&c| c == '\n').count();
52 .map(|(i, mut line)| {
55 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
56 line = &line[..(line.len() - 2)];
61 .map(left_trim_comment_line)
70 let mut result = opener.to_owned();
76 result.push_str(&indent_str);
77 result.push_str(line_start);
80 if line.len() > max_chars {
81 let rewrite = try_opt!(rewrite_string(line, &fmt));
82 result.push_str(&rewrite);
85 result.pop(); // Remove space if this is an empty comment.
87 result.push_str(line);
94 result.push_str(closer);
99 fn left_trim_comment_line(line: &str) -> &str {
100 if line.starts_with("/* ") || line.starts_with("// ") {
102 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") {
104 } else if line.starts_with("*") {
111 pub trait FindUncommented {
112 fn find_uncommented(&self, pat: &str) -> Option<usize>;
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() {
121 return Some(i - pat.len());
123 Some(c) => match kind {
124 CodeCharKind::Normal if b == c => {}
126 needle_iter = pat.chars();
132 // Handle case where the pattern is a suffix of the search string
133 match needle_iter.next() {
135 None => Some(self.len() - pat.len()),
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 {
152 // Handle case where the comment ends at the end of s.
153 if iter.status == CharClassesStatus::Normal {
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)
165 struct CharClasses<T>
169 base: iter::Peekable<T>,
170 status: CharClassesStatus,
174 fn get_char(&self) -> char;
177 impl RichChar for char {
178 fn get_char(&self) -> char {
183 impl RichChar for (usize, char) {
184 fn get_char(&self) -> char {
189 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
190 enum CharClassesStatus {
196 // The u32 is the nesting deepness of the comment
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),
207 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
213 impl<T> CharClasses<T> where T: Iterator, T::Item: RichChar {
214 fn new(base: T) -> CharClasses<T> {
216 base: base.peekable(),
217 status: CharClassesStatus::Normal,
222 impl<T> Iterator for CharClasses<T> where T: Iterator, T::Item: RichChar {
223 type Item = (CodeCharKind, T::Item);
225 fn next(&mut self) -> Option<(CodeCharKind, T::Item)> {
226 let item = try_opt!(self.base.next());
227 let chr = item.get_char();
228 self.status = match self.status {
229 CharClassesStatus::LitString => match chr {
230 '"' => CharClassesStatus::Normal,
231 '\\' => CharClassesStatus::LitStringEscape,
232 _ => CharClassesStatus::LitString,
234 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
235 CharClassesStatus::LitChar => match chr {
236 '\\' => CharClassesStatus::LitCharEscape,
237 '\'' => CharClassesStatus::Normal,
238 _ => CharClassesStatus::LitChar,
240 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
241 CharClassesStatus::Normal => {
243 '"' => CharClassesStatus::LitString,
244 '\'' => CharClassesStatus::LitChar,
245 '/' => match self.base.peek() {
246 Some(next) if next.get_char() == '*' => {
247 self.status = CharClassesStatus::BlockCommentOpening(1);
248 return Some((CodeCharKind::Comment, item));
250 Some(next) if next.get_char() == '/' => {
251 self.status = CharClassesStatus::LineComment;
252 return Some((CodeCharKind::Comment, item));
254 _ => CharClassesStatus::Normal,
256 _ => CharClassesStatus::Normal,
259 CharClassesStatus::BlockComment(deepness) => {
261 // This is the closing '/'
262 assert_eq!(chr, '/');
263 self.status = CharClassesStatus::Normal;
264 return Some((CodeCharKind::Comment, item));
266 self.status = match self.base.peek() {
267 Some(next) if next.get_char() == '/' && chr == '*' =>
268 CharClassesStatus::BlockCommentClosing(deepness - 1),
269 Some(next) if next.get_char() == '*' && chr == '/' =>
270 CharClassesStatus::BlockCommentOpening(deepness + 1),
271 _ => CharClassesStatus::BlockComment(deepness),
273 return Some((CodeCharKind::Comment, item));
275 CharClassesStatus::BlockCommentOpening(deepness) => {
276 assert_eq!(chr, '*');
277 self.status = CharClassesStatus::BlockComment(deepness);
278 return Some((CodeCharKind::Comment, item));
280 CharClassesStatus::BlockCommentClosing(deepness) => {
281 assert_eq!(chr, '/');
282 self.status = if deepness == 0 {
283 CharClassesStatus::Normal
285 CharClassesStatus::BlockComment(deepness)
287 return Some((CodeCharKind::Comment, item));
289 CharClassesStatus::LineComment => {
290 self.status = match chr {
291 '\n' => CharClassesStatus::Normal,
292 _ => CharClassesStatus::LineComment,
294 return Some((CodeCharKind::Comment, item));
297 Some((CodeCharKind::Normal, item))
303 use super::{CharClasses, CodeCharKind, contains_comment, rewrite_comment, FindUncommented};
308 fn format_comments() {
309 let config = Default::default();
310 assert_eq!("/* test */", rewrite_comment(" //test", true, 100, Indent::new(0, 100),
312 assert_eq!("// comment\n// on a", rewrite_comment("// comment on a", false, 10,
313 Indent::empty(), &config).unwrap());
315 assert_eq!("// A multi line comment\n // between args.",
316 rewrite_comment("// A multi line comment\n // between args.",
322 let input = "// comment";
327 assert_eq!(expected, rewrite_comment(input, true, 9, Indent::new(0, 69), &config).unwrap());
329 assert_eq!("/* trimmed */", rewrite_comment("/* trimmed */", true, 100,
330 Indent::new(0, 100), &config).unwrap());
333 // This is probably intended to be a non-test fn, but it is not used. I'm
334 // keeping it around unless it helps us test stuff.
335 fn uncommented(text: &str) -> String {
336 CharClasses::new(text.chars())
337 .filter_map(|(s, c)| {
339 CodeCharKind::Normal => Some(c),
340 CodeCharKind::Comment => None,
347 fn test_uncommented() {
348 assert_eq!(&uncommented("abc/*...*/"), "abc");
349 assert_eq!(&uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
351 assert_eq!(&uncommented("abc \" /* */\" qsdf"),
352 "abc \" /* */\" qsdf");
356 fn test_contains_comment() {
357 assert_eq!(contains_comment("abc"), false);
358 assert_eq!(contains_comment("abc // qsdf"), true);
359 assert_eq!(contains_comment("abc /* kqsdf"), true);
360 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
364 fn test_find_uncommented() {
365 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
366 println!("haystack {:?}, needle: {:?}", haystack, needle);
367 assert_eq!(expected, haystack.find_uncommented(needle));
370 check("/*/ */test", "test", Some(6));
371 check("//test\ntest", "test", Some(7));
372 check("/* comment only */", "whatever", None);
373 check("/* comment */ some text /* more commentary */ result",
376 check("sup // sup", "p", Some(2));
377 check("sup", "x", None);
378 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
379 check("/*sup yo? \n sup*/ sup", "p", Some(20));
380 check("hel/*lohello*/lo", "hello", None);
381 check("acb", "ab", None);
382 check(",/*A*/ ", ",", Some(0));
383 check("abc", "abc", Some(0));
384 check("/* abc */", "abc", None);
385 check("/**/abc/* */", "abc", Some(4));
386 check("\"/* abc */\"", "abc", Some(4));
387 check("\"/* abc", "abc", Some(4));