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 = if block_style { "/* " } else { "// " };
21 let closer = if block_style { " */" } else { "" };
22 let line_start = if block_style { " * " } else { "// " };
24 let max_chars = width.checked_sub(closer.len()).unwrap_or(1)
25 .checked_sub(opener.len()).unwrap_or(1);
27 let fmt = StringFormat {
30 line_start: line_start,
33 offset: offset + opener.len() - line_start.len(),
37 let indent_str = make_indent(offset);
38 let line_breaks = s.chars().filter(|&c| c == '\n').count();
40 let (_, mut s) = s.lines().enumerate()
41 .map(|(i, mut line)| {
45 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
46 line = &line[..(line.len() - 2)];
51 .map(left_trim_comment_line)
59 .fold((true, opener.to_owned()), |(first, mut acc), line| {
62 acc.push_str(&indent_str);
63 acc.push_str(line_start);
66 if line.len() > max_chars {
67 acc.push_str(&rewrite_string(line, &fmt));
80 fn left_trim_comment_line<'a>(line: &'a str) -> &'a str {
81 if line.starts_with("/* ") || line.starts_with("// ") {
83 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") {
85 } else if line.starts_with("*") {
93 fn format_comments() {
94 assert_eq!("/* test */", rewrite_comment(" //test", true, 100, 100));
95 assert_eq!("// comment\n// on a", rewrite_comment("// comment on a", false, 10, 0));
97 assert_eq!("// A multi line comment\n // between args.",
98 rewrite_comment("// A multi line comment\n // between args.",
103 let input = "// comment";
104 let expected_output = "/* com\n \
107 assert_eq!(expected_output, rewrite_comment(input, true, 9, 69));
109 assert_eq!("/* trimmed */", rewrite_comment("/* trimmed */", true, 100, 100));
113 pub trait FindUncommented {
114 fn find_uncommented(&self, pat: &str) -> Option<usize>;
117 impl FindUncommented for str {
118 fn find_uncommented(&self, pat: &str) -> Option<usize> {
119 let mut needle_iter = pat.chars();
120 let mut possible_comment = false;
122 for (i, b) in self.char_indices() {
123 match needle_iter.next() {
126 needle_iter = pat.chars();
129 None => return Some(i - pat.len())
132 if possible_comment && (b == '/' || b == '*') {
133 return find_comment_end(&self[(i-1)..])
135 self[(end + i - 1)..].find_uncommented(pat)
136 .map(|idx| idx + end + i - 1)
140 possible_comment = b == '/';
143 // Handle case where the pattern is a suffix of the search string
144 match needle_iter.next() {
146 None => Some(self.len() - pat.len())
152 fn test_find_uncommented() {
153 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
154 println!("haystack {:?}, needle: {:?}", haystack, needle);
155 assert_eq!(expected, haystack.find_uncommented(needle));
158 check("/*/ */test", "test", Some(6));
159 check("//test\ntest", "test", Some(7));
160 check("/* comment only */", "whatever", None);
161 check("/* comment */ some text /* more commentary */ result", "result", Some(46));
162 check("sup // sup", "p", Some(2));
163 check("sup", "x", None);
164 check("π? /**/ π is nice!", "π is nice", Some(9));
165 check("/*sup yo? \n sup*/ sup", "p", Some(20));
166 check("hel/*lohello*/lo", "hello", None);
167 check("acb", "ab", None);
168 check(",/*A*/ ", ",", Some(0));
171 // Returns the first byte position after the first comment. The given string
172 // is expected to be prefixed by a comment, including delimiters.
173 // Good: "/* /* inner */ outer */ code();"
174 // Bad: "code(); // hello\n world!"
175 pub fn find_comment_end(s: &str) -> Option<usize> {
176 if s.starts_with("//") {
177 s.find('\n').map(|idx| idx + 1)
181 let mut prev_char = 'a';
183 for (i, mut c) in s.char_indices() {
184 if c == '*' && prev_char == '/' {
186 c = 'a'; // Invalidate prev_char
187 } else if c == '/' && prev_char == '*' {
205 assert_eq!(Some(6), find_comment_end("// hi\n"));
206 assert_eq!(Some(9), find_comment_end("/* sup */ "));
207 assert_eq!(Some(9), find_comment_end("/*/**/ */ "));
208 assert_eq!(Some(6), find_comment_end("/*/ */ weird!"));
209 assert_eq!(None, find_comment_end("/* hi /* test */"));
210 assert_eq!(None, find_comment_end("// hi /* test */"));
211 assert_eq!(Some(9), find_comment_end("// hi /*\n."));