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> {
215 CharClasses { base: base.peekable(), status: CharClassesStatus::Normal }
219 impl<T> Iterator for CharClasses<T> where T: Iterator, T::Item: RichChar {
220 type Item = (CodeCharKind, T::Item);
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,
231 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
232 CharClassesStatus::LitChar => match chr {
233 '\\' => CharClassesStatus::LitCharEscape,
234 '\'' => CharClassesStatus::Normal,
235 _ => CharClassesStatus::LitChar,
237 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
238 CharClassesStatus::Normal => {
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));
247 Some(next) if next.get_char() == '/' => {
248 self.status = CharClassesStatus::LineComment;
249 return Some((CodeCharKind::Comment, item));
251 _ => CharClassesStatus::Normal,
253 _ => CharClassesStatus::Normal,
256 CharClassesStatus::BlockComment(deepness) => {
258 // This is the closing '/'
259 assert_eq!(chr, '/');
260 self.status = CharClassesStatus::Normal;
261 return Some((CodeCharKind::Comment, item));
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),
270 return Some((CodeCharKind::Comment, item));
272 CharClassesStatus::BlockCommentOpening(deepness) => {
273 assert_eq!(chr, '*');
274 self.status = CharClassesStatus::BlockComment(deepness);
275 return Some((CodeCharKind::Comment, item));
277 CharClassesStatus::BlockCommentClosing(deepness) => {
278 assert_eq!(chr, '/');
279 self.status = if deepness == 0 {
280 CharClassesStatus::Normal
282 CharClassesStatus::BlockComment(deepness)
284 return Some((CodeCharKind::Comment, item));
286 CharClassesStatus::LineComment => {
287 self.status = match chr {
288 '\n' => CharClassesStatus::Normal,
289 _ => CharClassesStatus::LineComment,
291 return Some((CodeCharKind::Comment, item));
294 Some((CodeCharKind::Normal, item))
300 use super::{CharClasses, CodeCharKind, contains_comment, rewrite_comment, FindUncommented};
305 fn format_comments() {
306 let config = Default::default();
307 assert_eq!("/* test */", rewrite_comment(" //test", true, 100, Indent::new(0, 100),
309 assert_eq!("// comment\n// on a", rewrite_comment("// comment on a", false, 10,
310 Indent::empty(), &config).unwrap());
312 assert_eq!("// A multi line comment\n // between args.",
313 rewrite_comment("// A multi line comment\n // between args.",
319 let input = "// comment";
324 assert_eq!(expected, rewrite_comment(input, true, 9, Indent::new(0, 69), &config).unwrap());
326 assert_eq!("/* trimmed */", rewrite_comment("/* trimmed */", true, 100,
327 Indent::new(0, 100), &config).unwrap());
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)| {
336 CodeCharKind::Normal => Some(c),
337 CodeCharKind::Comment => None,
344 fn test_uncommented() {
345 assert_eq!(&uncommented("abc/*...*/"), "abc");
346 assert_eq!(&uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
348 assert_eq!(&uncommented("abc \" /* */\" qsdf"),
349 "abc \" /* */\" qsdf");
353 fn test_contains_comment() {
354 assert_eq!(contains_comment("abc"), false);
355 assert_eq!(contains_comment("abc // qsdf"), true);
356 assert_eq!(contains_comment("abc /* kqsdf"), true);
357 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
361 fn test_find_uncommented() {
362 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
363 println!("haystack {:?}, needle: {:?}", haystack, needle);
364 assert_eq!(expected, haystack.find_uncommented(needle));
367 check("/*/ */test", "test", Some(6));
368 check("//test\ntest", "test", Some(7));
369 check("/* comment only */", "whatever", None);
370 check("/* comment */ some text /* more commentary */ result",
373 check("sup // sup", "p", Some(2));
374 check("sup", "x", None);
375 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
376 check("/*sup yo? \n sup*/ sup", "p", Some(20));
377 check("hel/*lohello*/lo", "hello", None);
378 check("acb", "ab", None);
379 check(",/*A*/ ", ",", Some(0));
380 check("abc", "abc", Some(0));
381 check("/* abc */", "abc", None);
382 check("/**/abc/* */", "abc", Some(4));
383 check("\"/* abc */\"", "abc", Some(4));
384 check("\"/* abc", "abc", Some(4));