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();
50 let (_, mut s) = s.lines()
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)
69 .fold((true, opener.to_owned()),
70 |(first, mut acc), line| {
73 acc.push_str(&indent_str);
74 acc.push_str(line_start);
77 if line.len() > max_chars {
78 acc.push_str(&rewrite_string(line, &fmt));
81 acc.pop(); // Remove space if this is an empty comment.
95 fn left_trim_comment_line(line: &str) -> &str {
96 if line.starts_with("/* ") || line.starts_with("// ") {
98 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") {
100 } else if line.starts_with("*") {
107 pub trait FindUncommented {
108 fn find_uncommented(&self, pat: &str) -> Option<usize>;
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() {
117 return Some(i - pat.len());
119 Some(c) => match kind {
120 CodeCharKind::Normal if b == c => {}
122 needle_iter = pat.chars();
128 // Handle case where the pattern is a suffix of the search string
129 match needle_iter.next() {
131 None => Some(self.len() - pat.len()),
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 {
148 // Handle case where the comment ends at the end of s.
149 if iter.status == CharClassesStatus::Normal {
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)
161 struct CharClasses<T>
165 base: iter::Peekable<T>,
166 status: CharClassesStatus,
170 fn get_char(&self) -> char;
173 impl RichChar for char {
174 fn get_char(&self) -> char {
179 impl RichChar for (usize, char) {
180 fn get_char(&self) -> char {
185 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
186 enum CharClassesStatus {
192 // The u32 is the nesting deepness of the comment
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),
203 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
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 }
215 impl<T> Iterator for CharClasses<T> where T: Iterator, T::Item: RichChar {
216 type Item = (CodeCharKind, T::Item);
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,
227 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
228 CharClassesStatus::LitChar => match chr {
229 '\\' => CharClassesStatus::LitCharEscape,
230 '\'' => CharClassesStatus::Normal,
231 _ => CharClassesStatus::LitChar,
233 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
234 CharClassesStatus::Normal => {
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));
243 Some(next) if next.get_char() == '/' => {
244 self.status = CharClassesStatus::LineComment;
245 return Some((CodeCharKind::Comment, item));
247 _ => CharClassesStatus::Normal,
249 _ => CharClassesStatus::Normal,
252 CharClassesStatus::BlockComment(deepness) => {
254 // This is the closing '/'
255 assert_eq!(chr, '/');
256 self.status = CharClassesStatus::Normal;
257 return Some((CodeCharKind::Comment, item));
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),
266 return Some((CodeCharKind::Comment, item));
268 CharClassesStatus::BlockCommentOpening(deepness) => {
269 assert_eq!(chr, '*');
270 self.status = CharClassesStatus::BlockComment(deepness);
271 return Some((CodeCharKind::Comment, item));
273 CharClassesStatus::BlockCommentClosing(deepness) => {
274 assert_eq!(chr, '/');
275 self.status = if deepness == 0 {
276 CharClassesStatus::Normal
278 CharClassesStatus::BlockComment(deepness)
280 return Some((CodeCharKind::Comment, item));
282 CharClassesStatus::LineComment => {
283 self.status = match chr {
284 '\n' => CharClassesStatus::Normal,
285 _ => CharClassesStatus::LineComment,
287 return Some((CodeCharKind::Comment, item));
290 Some((CodeCharKind::Normal, item))
296 use super::{CharClasses, CodeCharKind, contains_comment, rewrite_comment, FindUncommented};
301 fn format_comments() {
302 let config = Default::default();
303 assert_eq!("/* test */", rewrite_comment(" //test", true, 100, Indent::new(0, 100),
305 assert_eq!("// comment\n// on a", rewrite_comment("// comment on a", false, 10,
306 Indent::empty(), &config));
308 assert_eq!("// A multi line comment\n // between args.",
309 rewrite_comment("// A multi line comment\n // between args.",
315 let input = "// comment";
320 assert_eq!(expected, rewrite_comment(input, true, 9, Indent::new(0, 69), &config));
322 assert_eq!("/* trimmed */", rewrite_comment("/* trimmed */", true, 100,
323 Indent::new(0, 100), &config));
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)| {
332 CodeCharKind::Normal => Some(c),
333 CodeCharKind::Comment => None,
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");
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);
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));
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));