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()).unwrap_or(1)
29 .checked_sub(opener.len()).unwrap_or(1);
31 let fmt = StringFormat {
34 line_start: line_start,
37 offset: offset + opener.len() - line_start.len(),
41 let indent_str = make_indent(offset);
42 let line_breaks = s.chars().filter(|&c| c == '\n').count();
44 let (_, mut s) = s.lines().enumerate()
45 .map(|(i, mut line)| {
49 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
50 line = &line[..(line.len() - 2)];
55 .map(left_trim_comment_line)
63 .fold((true, opener.to_owned()), |(first, mut acc), line| {
66 acc.push_str(&indent_str);
67 acc.push_str(line_start);
70 if line.len() > max_chars {
71 acc.push_str(&rewrite_string(line, &fmt));
74 acc.pop(); // Remove space if this is an empty comment.
88 fn left_trim_comment_line(line: &str) -> &str {
89 if line.starts_with("/* ") || line.starts_with("// ") {
91 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") {
93 } else if line.starts_with("*") {
100 pub trait FindUncommented {
101 fn find_uncommented(&self, pat: &str) -> Option<usize>;
104 impl FindUncommented for str {
105 fn find_uncommented(&self, pat: &str) -> Option<usize> {
106 let mut needle_iter = pat.chars();
107 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
108 match needle_iter.next() {
110 return Some(i - pat.len());
112 Some(c) => match kind {
113 CodeCharKind::Normal if b == c => {}
115 needle_iter = pat.chars();
121 // Handle case where the pattern is a suffix of the search string
122 match needle_iter.next() {
124 None => Some(self.len() - pat.len()),
129 // Returns the first byte position after the first comment. The given string
130 // is expected to be prefixed by a comment, including delimiters.
131 // Good: "/* /* inner */ outer */ code();"
132 // Bad: "code(); // hello\n world!"
133 pub fn find_comment_end(s: &str) -> Option<usize> {
134 let mut iter = CharClasses::new(s.char_indices());
135 for (kind, (i, _c)) in &mut iter {
136 if kind == CodeCharKind::Normal {
141 // Handle case where the comment ends at the end of s.
142 if iter.status == CharClassesStatus::Normal {
151 assert_eq!(Some(6), find_comment_end("// hi\n"));
152 assert_eq!(Some(9), find_comment_end("/* sup */ "));
153 assert_eq!(Some(9), find_comment_end("/*/**/ */ "));
154 assert_eq!(Some(6), find_comment_end("/*/ */ weird!"));
155 assert_eq!(None, find_comment_end("/* hi /* test */"));
156 assert_eq!(None, find_comment_end("// hi /* test */"));
157 assert_eq!(Some(9), find_comment_end("// hi /*\n."));
161 /// Returns true if text contains any comment.
162 pub fn contains_comment(text: &str) -> bool {
163 CharClasses::new(text.chars()).any(|(kind, _)| kind == CodeCharKind::Comment )
167 struct CharClasses<T>
171 base: iter::Peekable<T>,
172 status: CharClassesStatus,
176 fn get_char(&self) -> char;
179 impl RichChar for char {
180 fn get_char(&self) -> char {
185 impl RichChar for (usize, char) {
186 fn get_char(&self) -> char {
191 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
192 enum CharClassesStatus {
198 // The u32 is the nesting deepness of the comment
200 // Status when the '/' has been consumed, but not yet the '*', deepness is the new deepness
201 // (after the comment opening).
202 BlockCommentOpening(u32),
203 // Status when the '*' has been consumed, but not yet the '/', deepness is the new deepness
204 // (after the comment closing).
205 BlockCommentClosing(u32),
209 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
215 impl<T> CharClasses<T> where T: Iterator, T::Item: RichChar {
216 fn new(base: T) -> CharClasses<T> {
217 CharClasses { base: base.peekable(), status: CharClassesStatus::Normal }
221 impl<T> Iterator for CharClasses<T> where T: Iterator, T::Item: RichChar {
222 type Item = (CodeCharKind, T::Item);
224 fn next(&mut self) -> Option<(CodeCharKind, T::Item)> {
225 let item = try_opt!(self.base.next());
226 let chr = item.get_char();
227 self.status = match self.status {
228 CharClassesStatus::LitString => match chr {
229 '"' => CharClassesStatus::Normal,
230 '\\' => CharClassesStatus::LitStringEscape,
231 _ => CharClassesStatus::LitString,
233 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
234 CharClassesStatus::LitChar => match chr {
235 '\\' => CharClassesStatus::LitCharEscape,
236 '\'' => CharClassesStatus::Normal,
237 _ => CharClassesStatus::LitChar,
239 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
240 CharClassesStatus::Normal => {
242 '"' => CharClassesStatus::LitString,
243 '\'' => CharClassesStatus::LitChar,
244 '/' => match self.base.peek() {
245 Some(next) if next.get_char() == '*' => {
246 self.status = CharClassesStatus::BlockCommentOpening(1);
247 return Some((CodeCharKind::Comment, item));
249 Some(next) if next.get_char() == '/' => {
250 self.status = CharClassesStatus::LineComment;
251 return Some((CodeCharKind::Comment, item));
253 _ => CharClassesStatus::Normal,
255 _ => CharClassesStatus::Normal,
258 CharClassesStatus::BlockComment(deepness) => {
260 // This is the closing '/'
261 assert_eq!(chr, '/');
262 self.status = CharClassesStatus::Normal;
263 return Some((CodeCharKind::Comment, item));
265 self.status = match self.base.peek() {
266 Some(next) if next.get_char() == '/' && chr == '*' =>
267 CharClassesStatus::BlockCommentClosing(deepness - 1),
268 Some(next) if next.get_char() == '*' && chr == '/' =>
269 CharClassesStatus::BlockCommentOpening(deepness + 1),
270 _ => CharClassesStatus::BlockComment(deepness),
272 return Some((CodeCharKind::Comment, item));
274 CharClassesStatus::BlockCommentOpening(deepness) => {
275 assert_eq!(chr, '*');
276 self.status = CharClassesStatus::BlockComment(deepness);
277 return Some((CodeCharKind::Comment, item));
279 CharClassesStatus::BlockCommentClosing(deepness) => {
280 assert_eq!(chr, '/');
281 self.status = if deepness == 0 {
282 CharClassesStatus::Normal
284 CharClassesStatus::BlockComment(deepness)
286 return Some((CodeCharKind::Comment, item));
288 CharClassesStatus::LineComment => {
289 self.status = match chr {
290 '\n' => CharClassesStatus::Normal,
291 _ => CharClassesStatus::LineComment,
293 return Some((CodeCharKind::Comment, item));
296 Some((CodeCharKind::Normal, item))
302 use super::{CharClasses, CodeCharKind, contains_comment, rewrite_comment, FindUncommented};
305 fn format_comments() {
306 assert_eq!("/* test */", rewrite_comment(" //test", true, 100, 100));
307 assert_eq!("// comment\n// on a", rewrite_comment("// comment on a", false, 10, 0));
309 assert_eq!("// A multi line comment\n // between args.",
310 rewrite_comment("// A multi line comment\n // between args.",
315 let input = "// comment";
316 let expected = "/* com\n \
319 assert_eq!(expected, rewrite_comment(input, true, 9, 69));
321 assert_eq!("/* trimmed */", rewrite_comment("/* trimmed */", true, 100, 100));
324 // This is probably intended to be a non-test fn, but it is not used. I'm
325 // keeping it around unless it helps us test stuff.
326 fn uncommented(text: &str) -> String {
327 CharClasses::new(text.chars()).filter_map(|(s, c)| match s {
328 CodeCharKind::Normal => Some(c),
329 CodeCharKind::Comment => None
334 fn test_uncommented() {
335 assert_eq!(&uncommented("abc/*...*/"), "abc");
336 assert_eq!(&uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"), "..ac\n");
337 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
341 fn test_contains_comment() {
342 assert_eq!(contains_comment("abc"), false);
343 assert_eq!(contains_comment("abc // qsdf"), true);
344 assert_eq!(contains_comment("abc /* kqsdf"), true);
345 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
349 fn test_find_uncommented() {
350 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
351 println!("haystack {:?}, needle: {:?}", haystack, needle);
352 assert_eq!(expected, haystack.find_uncommented(needle));
355 check("/*/ */test", "test", Some(6));
356 check("//test\ntest", "test", Some(7));
357 check("/* comment only */", "whatever", None);
358 check("/* comment */ some text /* more commentary */ result", "result", Some(46));
359 check("sup // sup", "p", Some(2));
360 check("sup", "x", None);
361 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
362 check("/*sup yo? \n sup*/ sup", "p", Some(20));
363 check("hel/*lohello*/lo", "hello", None);
364 check("acb", "ab", None);
365 check(",/*A*/ ", ",", Some(0));
366 check("abc", "abc", Some(0));
367 check("/* abc */", "abc", None);
368 check("/**/abc/* */", "abc", Some(4));
369 check("\"/* abc */\"", "abc", Some(4));
370 check("\"/* abc", "abc", Some(4));