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()),
63 |(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 {
149 /// Returns true if text contains any comment.
150 pub fn contains_comment(text: &str) -> bool {
151 CharClasses::new(text.chars()).any(|(kind, _)| kind == CodeCharKind::Comment)
154 struct CharClasses<T>
158 base: iter::Peekable<T>,
159 status: CharClassesStatus,
163 fn get_char(&self) -> char;
166 impl RichChar for char {
167 fn get_char(&self) -> char {
172 impl RichChar for (usize, char) {
173 fn get_char(&self) -> char {
178 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
179 enum CharClassesStatus {
185 // The u32 is the nesting deepness of the comment
187 // Status when the '/' has been consumed, but not yet the '*', deepness is the new deepness
188 // (after the comment opening).
189 BlockCommentOpening(u32),
190 // Status when the '*' has been consumed, but not yet the '/', deepness is the new deepness
191 // (after the comment closing).
192 BlockCommentClosing(u32),
196 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
202 impl<T> CharClasses<T> where T: Iterator, T::Item: RichChar {
203 fn new(base: T) -> CharClasses<T> {
204 CharClasses { base: base.peekable(), status: CharClassesStatus::Normal }
208 impl<T> Iterator for CharClasses<T> where T: Iterator, T::Item: RichChar {
209 type Item = (CodeCharKind, T::Item);
211 fn next(&mut self) -> Option<(CodeCharKind, T::Item)> {
212 let item = try_opt!(self.base.next());
213 let chr = item.get_char();
214 self.status = match self.status {
215 CharClassesStatus::LitString => match chr {
216 '"' => CharClassesStatus::Normal,
217 '\\' => CharClassesStatus::LitStringEscape,
218 _ => CharClassesStatus::LitString,
220 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
221 CharClassesStatus::LitChar => match chr {
222 '\\' => CharClassesStatus::LitCharEscape,
223 '\'' => CharClassesStatus::Normal,
224 _ => CharClassesStatus::LitChar,
226 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
227 CharClassesStatus::Normal => {
229 '"' => CharClassesStatus::LitString,
230 '\'' => CharClassesStatus::LitChar,
231 '/' => match self.base.peek() {
232 Some(next) if next.get_char() == '*' => {
233 self.status = CharClassesStatus::BlockCommentOpening(1);
234 return Some((CodeCharKind::Comment, item));
236 Some(next) if next.get_char() == '/' => {
237 self.status = CharClassesStatus::LineComment;
238 return Some((CodeCharKind::Comment, item));
240 _ => CharClassesStatus::Normal,
242 _ => CharClassesStatus::Normal,
245 CharClassesStatus::BlockComment(deepness) => {
247 // This is the closing '/'
248 assert_eq!(chr, '/');
249 self.status = CharClassesStatus::Normal;
250 return Some((CodeCharKind::Comment, item));
252 self.status = match self.base.peek() {
253 Some(next) if next.get_char() == '/' && chr == '*' =>
254 CharClassesStatus::BlockCommentClosing(deepness - 1),
255 Some(next) if next.get_char() == '*' && chr == '/' =>
256 CharClassesStatus::BlockCommentOpening(deepness + 1),
257 _ => CharClassesStatus::BlockComment(deepness),
259 return Some((CodeCharKind::Comment, item));
261 CharClassesStatus::BlockCommentOpening(deepness) => {
262 assert_eq!(chr, '*');
263 self.status = CharClassesStatus::BlockComment(deepness);
264 return Some((CodeCharKind::Comment, item));
266 CharClassesStatus::BlockCommentClosing(deepness) => {
267 assert_eq!(chr, '/');
268 self.status = if deepness == 0 {
269 CharClassesStatus::Normal
271 CharClassesStatus::BlockComment(deepness)
273 return Some((CodeCharKind::Comment, item));
275 CharClassesStatus::LineComment => {
276 self.status = match chr {
277 '\n' => CharClassesStatus::Normal,
278 _ => CharClassesStatus::LineComment,
280 return Some((CodeCharKind::Comment, item));
283 Some((CodeCharKind::Normal, item))
289 use super::{CharClasses, CodeCharKind, contains_comment, rewrite_comment, FindUncommented};
291 // TODO(#217): prevent string literal from going over the limit.
293 fn format_comments() {
294 assert_eq!("/* test */", rewrite_comment(" //test", true, 100, 100));
295 assert_eq!("// comment\n// on a", rewrite_comment("// comment on a", false, 10, 0));
297 assert_eq!("// A multi line comment\n // between args.",
298 rewrite_comment("// A multi line comment\n // between args.",
303 let input = "// comment";
304 let expected = "/* com\n \
307 assert_eq!(expected, rewrite_comment(input, true, 9, 69));
309 assert_eq!("/* trimmed */", rewrite_comment("/* trimmed */", true, 100, 100));
312 // This is probably intended to be a non-test fn, but it is not used. I'm
313 // keeping it around unless it helps us test stuff.
314 fn uncommented(text: &str) -> String {
315 CharClasses::new(text.chars())
316 .filter_map(|(s, c)| {
318 CodeCharKind::Normal => Some(c),
319 CodeCharKind::Comment => None,
326 fn test_uncommented() {
327 assert_eq!(&uncommented("abc/*...*/"), "abc");
328 assert_eq!(&uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"), "..ac\n");
329 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
333 fn test_contains_comment() {
334 assert_eq!(contains_comment("abc"), false);
335 assert_eq!(contains_comment("abc // qsdf"), true);
336 assert_eq!(contains_comment("abc /* kqsdf"), true);
337 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
341 fn test_find_uncommented() {
342 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
343 println!("haystack {:?}, needle: {:?}", haystack, needle);
344 assert_eq!(expected, haystack.find_uncommented(needle));
347 check("/*/ */test", "test", Some(6));
348 check("//test\ntest", "test", Some(7));
349 check("/* comment only */", "whatever", None);
350 check("/* comment */ some text /* more commentary */ result", "result", Some(46));
351 check("sup // sup", "p", Some(2));
352 check("sup", "x", None);
353 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
354 check("/*sup yo? \n sup*/ sup", "p", Some(20));
355 check("hel/*lohello*/lo", "hello", None);
356 check("acb", "ab", None);
357 check(",/*A*/ ", ",", Some(0));
358 check("abc", "abc", Some(0));
359 check("/* abc */", "abc", None);
360 check("/**/abc/* */", "abc", Some(4));
361 check("\"/* abc */\"", "abc", Some(4));
362 check("\"/* abc", "abc", Some(4));