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));
84 fn left_trim_comment_line(line: &str) -> &str {
85 if line.starts_with("/* ") || line.starts_with("// ") {
87 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") {
89 } else if line.starts_with("*") {
96 pub trait FindUncommented {
97 fn find_uncommented(&self, pat: &str) -> Option<usize>;
100 impl FindUncommented for str {
101 fn find_uncommented(&self, pat: &str) -> Option<usize> {
102 let mut needle_iter = pat.chars();
103 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
104 match needle_iter.next() {
106 return Some(i - pat.len());
108 Some(c) => match kind {
109 CodeCharKind::Normal if b == c => {}
111 needle_iter = pat.chars();
117 // Handle case where the pattern is a suffix of the search string
118 match needle_iter.next() {
120 None => Some(self.len() - pat.len()),
125 // Returns the first byte position after the first comment. The given string
126 // is expected to be prefixed by a comment, including delimiters.
127 // Good: "/* /* inner */ outer */ code();"
128 // Bad: "code(); // hello\n world!"
129 pub fn find_comment_end(s: &str) -> Option<usize> {
130 let mut iter = CharClasses::new(s.char_indices());
131 for (kind, (i, _c)) in &mut iter {
132 if kind == CodeCharKind::Normal {
137 // Handle case where the comment ends at the end of s.
138 if iter.status == CharClassesStatus::Normal {
147 assert_eq!(Some(6), find_comment_end("// hi\n"));
148 assert_eq!(Some(9), find_comment_end("/* sup */ "));
149 assert_eq!(Some(9), find_comment_end("/*/**/ */ "));
150 assert_eq!(Some(6), find_comment_end("/*/ */ weird!"));
151 assert_eq!(None, find_comment_end("/* hi /* test */"));
152 assert_eq!(None, find_comment_end("// hi /* test */"));
153 assert_eq!(Some(9), find_comment_end("// hi /*\n."));
157 /// Returns true if text contains any comment.
158 pub fn contains_comment(text: &str) -> bool {
159 CharClasses::new(text.chars()).any(|(kind, _)| kind == CodeCharKind::Comment )
163 struct CharClasses<T>
167 base: iter::Peekable<T>,
168 status: CharClassesStatus,
172 fn get_char(&self) -> char;
175 impl RichChar for char {
176 fn get_char(&self) -> char {
181 impl RichChar for (usize, char) {
182 fn get_char(&self) -> char {
187 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
188 enum CharClassesStatus {
194 // The u32 is the nesting deepness of the comment
196 // Status when the '/' has been consumed, but not yet the '*', deepness is the new deepness
197 // (after the comment opening).
198 BlockCommentOpening(u32),
199 // Status when the '*' has been consumed, but not yet the '/', deepness is the new deepness
200 // (after the comment closing).
201 BlockCommentClosing(u32),
205 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
211 impl<T> CharClasses<T> where T: Iterator, T::Item: RichChar {
212 fn new(base: T) -> CharClasses<T> {
213 CharClasses { base: base.peekable(), status: CharClassesStatus::Normal }
217 impl<T> Iterator for CharClasses<T> where T: Iterator, T::Item: RichChar {
218 type Item = (CodeCharKind, T::Item);
220 fn next(&mut self) -> Option<(CodeCharKind, T::Item)> {
221 let item = try_opt!(self.base.next());
222 let chr = item.get_char();
223 self.status = match self.status {
224 CharClassesStatus::LitString => match chr {
225 '"' => CharClassesStatus::Normal,
226 '\\' => CharClassesStatus::LitStringEscape,
227 _ => CharClassesStatus::LitString,
229 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
230 CharClassesStatus::LitChar => match chr {
231 '\\' => CharClassesStatus::LitCharEscape,
232 '\'' => CharClassesStatus::Normal,
233 _ => CharClassesStatus::LitChar,
235 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
236 CharClassesStatus::Normal => {
238 '"' => CharClassesStatus::LitString,
239 '\'' => CharClassesStatus::LitChar,
240 '/' => match self.base.peek() {
241 Some(next) if next.get_char() == '*' => {
242 self.status = CharClassesStatus::BlockCommentOpening(1);
243 return Some((CodeCharKind::Comment, item));
245 Some(next) if next.get_char() == '/' => {
246 self.status = CharClassesStatus::LineComment;
247 return Some((CodeCharKind::Comment, item));
249 _ => CharClassesStatus::Normal,
251 _ => CharClassesStatus::Normal,
254 CharClassesStatus::BlockComment(deepness) => {
256 // This is the closing '/'
257 assert_eq!(chr, '/');
258 self.status = CharClassesStatus::Normal;
259 return Some((CodeCharKind::Comment, item));
261 self.status = match self.base.peek() {
262 Some(next) if next.get_char() == '/' && chr == '*' =>
263 CharClassesStatus::BlockCommentClosing(deepness - 1),
264 Some(next) if next.get_char() == '*' && chr == '/' =>
265 CharClassesStatus::BlockCommentOpening(deepness + 1),
266 _ => CharClassesStatus::BlockComment(deepness),
268 return Some((CodeCharKind::Comment, item));
270 CharClassesStatus::BlockCommentOpening(deepness) => {
271 assert_eq!(chr, '*');
272 self.status = CharClassesStatus::BlockComment(deepness);
273 return Some((CodeCharKind::Comment, item));
275 CharClassesStatus::BlockCommentClosing(deepness) => {
276 assert_eq!(chr, '/');
277 self.status = if deepness == 0 {
278 CharClassesStatus::Normal
280 CharClassesStatus::BlockComment(deepness)
282 return Some((CodeCharKind::Comment, item));
284 CharClassesStatus::LineComment => {
285 self.status = match chr {
286 '\n' => CharClassesStatus::Normal,
287 _ => CharClassesStatus::LineComment,
289 return Some((CodeCharKind::Comment, item));
292 Some((CodeCharKind::Normal, item))
298 use super::{CharClasses, CodeCharKind, contains_comment, rewrite_comment, FindUncommented};
301 fn format_comments() {
302 assert_eq!("/* test */", rewrite_comment(" //test", true, 100, 100));
303 assert_eq!("// comment\n// on a", rewrite_comment("// comment on a", false, 10, 0));
305 assert_eq!("// A multi line comment\n // between args.",
306 rewrite_comment("// A multi line comment\n // between args.",
311 let input = "// comment";
312 let expected = "/* com\n \
315 assert_eq!(expected, rewrite_comment(input, true, 9, 69));
317 assert_eq!("/* trimmed */", rewrite_comment("/* trimmed */", true, 100, 100));
320 // This is probably intended to be a non-test fn, but it is not used. I'm
321 // keeping it around unless it helps us test stuff.
322 fn uncommented(text: &str) -> String {
323 CharClasses::new(text.chars()).filter_map(|(s, c)| match s {
324 CodeCharKind::Normal => Some(c),
325 CodeCharKind::Comment => None
330 fn test_uncommented() {
331 assert_eq!(&uncommented("abc/*...*/"), "abc");
332 assert_eq!(&uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"), "..ac\n");
333 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
337 fn test_contains_comment() {
338 assert_eq!(contains_comment("abc"), false);
339 assert_eq!(contains_comment("abc // qsdf"), true);
340 assert_eq!(contains_comment("abc /* kqsdf"), true);
341 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
345 fn test_find_uncommented() {
346 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
347 println!("haystack {:?}, needle: {:?}", haystack, needle);
348 assert_eq!(expected, haystack.find_uncommented(needle));
351 check("/*/ */test", "test", Some(6));
352 check("//test\ntest", "test", Some(7));
353 check("/* comment only */", "whatever", None);
354 check("/* comment */ some text /* more commentary */ result", "result", Some(46));
355 check("sup // sup", "p", Some(2));
356 check("sup", "x", None);
357 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
358 check("/*sup yo? \n sup*/ sup", "p", Some(20));
359 check("hel/*lohello*/lo", "hello", None);
360 check("acb", "ab", None);
361 check(",/*A*/ ", ",", Some(0));
362 check("abc", "abc", Some(0));
363 check("/* abc */", "abc", None);
364 check("/**/abc/* */", "abc", Some(4));
365 check("\"/* abc */\"", "abc", Some(4));
366 check("\"/* abc", "abc", Some(4));