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.
15 use string::{StringFormat, rewrite_string};
16 use utils::make_indent;
18 pub fn rewrite_comment(orig: &str, block_style: bool, width: usize, offset: usize) -> String {
21 // Edge case: block comments. Let's not trim their lines (for now).
22 let (opener, closer, line_start) = if block_style {
28 let max_chars = width.checked_sub(closer.len() + opener.len()).unwrap_or(1);
30 let fmt = StringFormat {
33 line_start: line_start,
36 offset: offset + opener.len() - line_start.len(),
40 let indent_str = make_indent(offset);
41 let line_breaks = s.chars().filter(|&c| c == '\n').count();
43 let (_, mut s) = s.lines()
45 .map(|(i, mut line)| {
48 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
49 line = &line[..(line.len() - 2)];
54 .map(left_trim_comment_line)
62 .fold((true, opener.to_owned()), |(first, mut acc), line| {
65 acc.push_str(&indent_str);
66 acc.push_str(line_start);
69 if line.len() > max_chars {
70 acc.push_str(&rewrite_string(line, &fmt));
73 acc.pop(); // Remove space if this is an empty comment.
87 fn left_trim_comment_line(line: &str) -> &str {
88 if line.starts_with("/* ") || line.starts_with("// ") {
90 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") {
92 } else if line.starts_with("*") {
99 pub trait FindUncommented {
100 fn find_uncommented(&self, pat: &str) -> Option<usize>;
103 impl FindUncommented for str {
104 fn find_uncommented(&self, pat: &str) -> Option<usize> {
105 let mut needle_iter = pat.chars();
106 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
107 match needle_iter.next() {
109 return Some(i - pat.len());
111 Some(c) => match kind {
112 CodeCharKind::Normal if b == c => {}
114 needle_iter = pat.chars();
120 // Handle case where the pattern is a suffix of the search string
121 match needle_iter.next() {
123 None => Some(self.len() - pat.len()),
128 // Returns the first byte position after the first comment. The given string
129 // is expected to be prefixed by a comment, including delimiters.
130 // Good: "/* /* inner */ outer */ code();"
131 // Bad: "code(); // hello\n world!"
132 pub fn find_comment_end(s: &str) -> Option<usize> {
133 let mut iter = CharClasses::new(s.char_indices());
134 for (kind, (i, _c)) in &mut iter {
135 if kind == CodeCharKind::Normal {
140 // Handle case where the comment ends at the end of s.
141 if iter.status == CharClassesStatus::Normal {
148 /// Returns true if text contains any comment.
149 pub fn contains_comment(text: &str) -> bool {
150 CharClasses::new(text.chars()).any(|(kind, _)| kind == CodeCharKind::Comment)
153 pub fn uncommented(text: &str) -> String {
154 CharClasses::new(text.chars())
155 .filter_map(|(s, c)| {
157 CodeCharKind::Normal => Some(c),
158 CodeCharKind::Comment => None,
164 struct CharClasses<T>
168 base: iter::Peekable<T>,
169 status: CharClassesStatus,
173 fn get_char(&self) -> char;
176 impl RichChar for char {
177 fn get_char(&self) -> char {
182 impl RichChar for (usize, char) {
183 fn get_char(&self) -> char {
188 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
189 enum CharClassesStatus {
195 // The u32 is the nesting deepness of the comment
197 // Status when the '/' has been consumed, but not yet the '*', deepness is the new deepness
198 // (after the comment opening).
199 BlockCommentOpening(u32),
200 // Status when the '*' has been consumed, but not yet the '/', deepness is the new deepness
201 // (after the comment closing).
202 BlockCommentClosing(u32),
206 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
212 impl<T> CharClasses<T> where T: Iterator, T::Item: RichChar {
213 fn new(base: T) -> CharClasses<T> {
214 CharClasses { base: base.peekable(), status: CharClassesStatus::Normal }
218 impl<T> Iterator for CharClasses<T> where T: Iterator, T::Item: RichChar {
219 type Item = (CodeCharKind, T::Item);
221 fn next(&mut self) -> Option<(CodeCharKind, T::Item)> {
222 let item = try_opt!(self.base.next());
223 let chr = item.get_char();
224 self.status = match self.status {
225 CharClassesStatus::LitString => match chr {
226 '"' => CharClassesStatus::Normal,
227 '\\' => CharClassesStatus::LitStringEscape,
228 _ => CharClassesStatus::LitString,
230 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
231 CharClassesStatus::LitChar => match chr {
232 '\\' => CharClassesStatus::LitCharEscape,
233 '\'' => CharClassesStatus::Normal,
234 _ => CharClassesStatus::LitChar,
236 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
237 CharClassesStatus::Normal => {
239 '"' => CharClassesStatus::LitString,
240 '\'' => CharClassesStatus::LitChar,
241 '/' => match self.base.peek() {
242 Some(next) if next.get_char() == '*' => {
243 self.status = CharClassesStatus::BlockCommentOpening(1);
244 return Some((CodeCharKind::Comment, item));
246 Some(next) if next.get_char() == '/' => {
247 self.status = CharClassesStatus::LineComment;
248 return Some((CodeCharKind::Comment, item));
250 _ => CharClassesStatus::Normal,
252 _ => CharClassesStatus::Normal,
255 CharClassesStatus::BlockComment(deepness) => {
257 // This is the closing '/'
258 assert_eq!(chr, '/');
259 self.status = CharClassesStatus::Normal;
260 return Some((CodeCharKind::Comment, item));
262 self.status = match self.base.peek() {
263 Some(next) if next.get_char() == '/' && chr == '*' =>
264 CharClassesStatus::BlockCommentClosing(deepness - 1),
265 Some(next) if next.get_char() == '*' && chr == '/' =>
266 CharClassesStatus::BlockCommentOpening(deepness + 1),
267 _ => CharClassesStatus::BlockComment(deepness),
269 return Some((CodeCharKind::Comment, item));
271 CharClassesStatus::BlockCommentOpening(deepness) => {
272 assert_eq!(chr, '*');
273 self.status = CharClassesStatus::BlockComment(deepness);
274 return Some((CodeCharKind::Comment, item));
276 CharClassesStatus::BlockCommentClosing(deepness) => {
277 assert_eq!(chr, '/');
278 self.status = if deepness == 0 {
279 CharClassesStatus::Normal
281 CharClassesStatus::BlockComment(deepness)
283 return Some((CodeCharKind::Comment, item));
285 CharClassesStatus::LineComment => {
286 self.status = match chr {
287 '\n' => CharClassesStatus::Normal,
288 _ => CharClassesStatus::LineComment,
290 return Some((CodeCharKind::Comment, item));
293 Some((CodeCharKind::Normal, item))
299 use super::{CharClasses, CodeCharKind, contains_comment, rewrite_comment, FindUncommented};
302 fn format_comments() {
303 assert_eq!("/* test */", rewrite_comment(" //test", true, 100, 100));
304 assert_eq!("// comment\n// on a", rewrite_comment("// comment on a", false, 10, 0));
306 assert_eq!("// A multi line comment\n // between args.",
307 rewrite_comment("// A multi line comment\n // between args.",
312 let input = "// comment";
313 let expected = "/* com\n \
316 assert_eq!(expected, rewrite_comment(input, true, 9, 69));
318 assert_eq!("/* trimmed */", rewrite_comment("/* trimmed */", true, 100, 100));
321 // This is probably intended to be a non-test fn, but it is not used. I'm
322 // keeping it around unless it helps us test stuff.
323 fn uncommented(text: &str) -> String {
324 CharClasses::new(text.chars()).filter_map(|(s, c)| match s {
325 CodeCharKind::Normal => Some(c),
326 CodeCharKind::Comment => None
331 fn test_uncommented() {
332 assert_eq!(&uncommented("abc/*...*/"), "abc");
333 assert_eq!(&uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"), "..ac\n");
334 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
338 fn test_contains_comment() {
339 assert_eq!(contains_comment("abc"), false);
340 assert_eq!(contains_comment("abc // qsdf"), true);
341 assert_eq!(contains_comment("abc /* kqsdf"), true);
342 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
346 fn test_find_uncommented() {
347 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
348 println!("haystack {:?}, needle: {:?}", haystack, needle);
349 assert_eq!(expected, haystack.find_uncommented(needle));
352 check("/*/ */test", "test", Some(6));
353 check("//test\ntest", "test", Some(7));
354 check("/* comment only */", "whatever", None);
355 check("/* comment */ some text /* more commentary */ result", "result", Some(46));
356 check("sup // sup", "p", Some(2));
357 check("sup", "x", None);
358 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
359 check("/*sup yo? \n sup*/ sup", "p", Some(20));
360 check("hel/*lohello*/lo", "hello", None);
361 check("acb", "ab", None);
362 check(",/*A*/ ", ",", Some(0));
363 check("abc", "abc", Some(0));
364 check("/* abc */", "abc", None);
365 check("/**/abc/* */", "abc", Some(4));
366 check("\"/* abc */\"", "abc", Some(4));
367 check("\"/* abc", "abc", Some(4));