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.
13 use string::{StringFormat, rewrite_string};
14 use utils::make_indent;
16 pub fn rewrite_comment(orig: &str, block_style: bool, width: usize, offset: usize) -> String {
19 // Edge case: block comments. Let's not trim their lines (for now).
20 let (opener, closer, line_start) = if block_style {
26 let max_chars = width.checked_sub(closer.len()).unwrap_or(1)
27 .checked_sub(opener.len()).unwrap_or(1);
29 let fmt = StringFormat {
32 line_start: line_start,
35 offset: offset + opener.len() - line_start.len(),
39 let indent_str = make_indent(offset);
40 let line_breaks = s.chars().filter(|&c| c == '\n').count();
42 let (_, mut s) = s.lines().enumerate()
43 .map(|(i, mut line)| {
47 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
48 line = &line[..(line.len() - 2)];
53 .map(left_trim_comment_line)
61 .fold((true, opener.to_owned()), |(first, mut acc), line| {
64 acc.push_str(&indent_str);
65 acc.push_str(line_start);
68 if line.len() > max_chars {
69 acc.push_str(&rewrite_string(line, &fmt));
82 fn left_trim_comment_line<'a>(line: &'a str) -> &'a str {
83 if line.starts_with("/* ") || line.starts_with("// ") {
85 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") {
87 } else if line.starts_with("*") {
95 fn format_comments() {
96 assert_eq!("/* test */", rewrite_comment(" //test", true, 100, 100));
97 assert_eq!("// comment\n// on a", rewrite_comment("// comment on a", false, 10, 0));
99 assert_eq!("// A multi line comment\n // between args.",
100 rewrite_comment("// A multi line comment\n // between args.",
105 let input = "// comment";
106 let expected_output = "/* com\n \
109 assert_eq!(expected_output, rewrite_comment(input, true, 9, 69));
111 assert_eq!("/* trimmed */", rewrite_comment("/* trimmed */", true, 100, 100));
115 pub trait FindUncommented {
116 fn find_uncommented(&self, pat: &str) -> Option<usize>;
119 impl FindUncommented for str {
120 fn find_uncommented(&self, pat: &str) -> Option<usize> {
121 let mut needle_iter = pat.chars();
122 let mut possible_comment = false;
124 for (i, b) in self.char_indices() {
125 match needle_iter.next() {
128 needle_iter = pat.chars();
131 None => return Some(i - pat.len())
134 if possible_comment && (b == '/' || b == '*') {
135 return find_comment_end(&self[(i-1)..])
137 self[(end + i - 1)..].find_uncommented(pat)
138 .map(|idx| idx + end + i - 1)
142 possible_comment = b == '/';
145 // Handle case where the pattern is a suffix of the search string
146 match needle_iter.next() {
148 None => Some(self.len() - pat.len())
154 fn test_find_uncommented() {
155 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
156 println!("haystack {:?}, needle: {:?}", haystack, needle);
157 assert_eq!(expected, haystack.find_uncommented(needle));
160 check("/*/ */test", "test", Some(6));
161 check("//test\ntest", "test", Some(7));
162 check("/* comment only */", "whatever", None);
163 check("/* comment */ some text /* more commentary */ result", "result", Some(46));
164 check("sup // sup", "p", Some(2));
165 check("sup", "x", None);
166 check("π? /**/ π is nice!", "π is nice", Some(9));
167 check("/*sup yo? \n sup*/ sup", "p", Some(20));
168 check("hel/*lohello*/lo", "hello", None);
169 check("acb", "ab", None);
170 check(",/*A*/ ", ",", Some(0));
173 // Returns the first byte position after the first comment. The given string
174 // is expected to be prefixed by a comment, including delimiters.
175 // Good: "/* /* inner */ outer */ code();"
176 // Bad: "code(); // hello\n world!"
177 pub fn find_comment_end(s: &str) -> Option<usize> {
178 if s.starts_with("//") {
179 s.find('\n').map(|idx| idx + 1)
183 let mut prev_char = 'a';
185 for (i, mut c) in s.char_indices() {
186 if c == '*' && prev_char == '/' {
188 c = 'a'; // Invalidate prev_char
189 } else if c == '/' && prev_char == '*' {
207 assert_eq!(Some(6), find_comment_end("// hi\n"));
208 assert_eq!(Some(9), find_comment_end("/* sup */ "));
209 assert_eq!(Some(9), find_comment_end("/*/**/ */ "));
210 assert_eq!(Some(6), find_comment_end("/*/ */ weird!"));
211 assert_eq!(None, find_comment_end("/* hi /* test */"));
212 assert_eq!(None, find_comment_end("// hi /* test */"));
213 assert_eq!(Some(9), find_comment_end("// hi /*\n."));