]> git.lizzy.rs Git - rust.git/blob - src/comment.rs
Merge pull request #1489 from regexident/gitignore
[rust.git] / src / comment.rs
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.
4 //
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.
10
11 // Formatting and tools for comments.
12
13 use std::{self, iter};
14
15 use syntax::codemap::Span;
16
17 use {Indent, Shape};
18 use config::Config;
19 use rewrite::RewriteContext;
20 use string::{StringFormat, rewrite_string};
21 use utils::wrap_str;
22
23 fn is_custom_comment(comment: &str) -> bool {
24     if !comment.starts_with("//") {
25         false
26     } else {
27         if let Some(c) = comment.chars().nth(2) {
28             !c.is_alphanumeric() && !c.is_whitespace()
29         } else {
30             false
31         }
32     }
33 }
34
35 pub fn rewrite_comment(orig: &str,
36                        block_style: bool,
37                        shape: Shape,
38                        config: &Config)
39                        -> Option<String> {
40     // If there are lines without a starting sigil, we won't format them correctly
41     // so in that case we won't even re-align (if !config.normalize_comments) and
42     // we should stop now.
43     let num_bare_lines = orig.lines()
44         .map(|line| line.trim())
45         .filter(|l| !(l.starts_with('*') || l.starts_with("//") || l.starts_with("/*")))
46         .count();
47     if num_bare_lines > 0 && !config.normalize_comments {
48         return Some(orig.to_owned());
49     }
50
51     if !config.normalize_comments && !config.wrap_comments {
52         return light_rewrite_comment(orig, shape.indent, config);
53     }
54
55     let (opener, closer, line_start) =
56         if block_style {
57             ("/* ", " */", " * ")
58         } else if !config.normalize_comments {
59             if orig.starts_with("/**") && !orig.starts_with("/**/") {
60                 ("/** ", " **/", " ** ")
61             } else if orig.starts_with("/*!") {
62                 ("/*! ", " */", " * ")
63             } else if orig.starts_with("/*") {
64                 ("/* ", " */", " * ")
65             } else if orig.starts_with("///") {
66                 ("/// ", "", "/// ")
67             } else if orig.starts_with("//!") {
68                 ("//! ", "", "//! ")
69             } else {
70                 ("// ", "", "// ")
71             }
72         } else if orig.starts_with("///") ||
73                   (orig.starts_with("/**") && !orig.starts_with("/**/")) {
74             ("/// ", "", "/// ")
75         } else if orig.starts_with("//!") || orig.starts_with("/*!") {
76             ("//! ", "", "//! ")
77         } else if is_custom_comment(orig) {
78             if orig.chars().nth(3) == Some(' ') {
79                 (&orig[0..4], "", &orig[0..4])
80             } else {
81                 (&orig[0..3], "", &orig[0..3])
82             }
83         } else {
84             ("// ", "", "// ")
85         };
86
87     let max_chars = shape
88         .width
89         .checked_sub(closer.len() + opener.len())
90         .unwrap_or(1);
91     let indent_str = shape.indent.to_string(config);
92     let fmt = StringFormat {
93         opener: "",
94         closer: "",
95         line_start: line_start,
96         line_end: "",
97         shape: Shape::legacy(max_chars, shape.indent + (opener.len() - line_start.len())),
98         trim_end: true,
99         config: config,
100     };
101
102     let line_breaks = orig.trim_right().chars().filter(|&c| c == '\n').count();
103     let lines = orig.lines()
104         .enumerate()
105         .map(|(i, mut line)| {
106             line = line.trim();
107             // Drop old closer.
108             if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
109                 line = &line[..(line.len() - 2)].trim_right();
110             }
111
112             line
113         })
114         .map(left_trim_comment_line)
115         .map(|line| if orig.starts_with("/*") && line_breaks == 0 {
116                  line.trim_left()
117              } else {
118                  line
119              });
120
121     let mut result = opener.to_owned();
122     for line in lines {
123         if result == opener {
124             if line.is_empty() {
125                 continue;
126             }
127         } else {
128             result.push('\n');
129             result.push_str(&indent_str);
130             result.push_str(line_start);
131         }
132
133         if config.wrap_comments && line.len() > max_chars {
134             let rewrite = rewrite_string(line, &fmt).unwrap_or(line.to_owned());
135             result.push_str(&rewrite);
136         } else {
137             if line.is_empty() {
138                 // Remove space if this is an empty comment or a doc comment.
139                 result.pop();
140             }
141             result.push_str(line);
142         }
143     }
144
145     result.push_str(closer);
146     if result == opener {
147         // Trailing space.
148         result.pop();
149     }
150
151     Some(result)
152 }
153
154 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
155 fn light_rewrite_comment(orig: &str, offset: Indent, config: &Config) -> Option<String> {
156     let lines: Vec<&str> = orig.lines()
157         .map(|l| {
158             // This is basically just l.trim(), but in the case that a line starts
159             // with `*` we want to leave one space before it, so it aligns with the
160             // `*` in `/*`.
161             let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
162             if let Some(fnw) = first_non_whitespace {
163                     if l.as_bytes()[fnw] == '*' as u8 && fnw > 0 {
164                         &l[fnw - 1..]
165                     } else {
166                         &l[fnw..]
167                     }
168                 } else {
169                     ""
170                 }
171                 .trim_right()
172         })
173         .collect();
174     Some(lines.join(&format!("\n{}", offset.to_string(config))))
175 }
176
177 /// Trims comment characters and possibly a single space from the left of a string.
178 /// Does not trim all whitespace.
179 fn left_trim_comment_line(line: &str) -> &str {
180     if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") ||
181        line.starts_with("/** ") {
182         &line[4..]
183     } else if is_custom_comment(line) {
184         if line.len() > 3 && line.chars().nth(3) == Some(' ') {
185             &line[4..]
186         } else {
187             &line[3..]
188         }
189     } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!") ||
190               line.starts_with("///") ||
191               line.starts_with("** ") || line.starts_with("/*!") ||
192               (line.starts_with("/**") && !line.starts_with("/**/")) {
193         &line[3..]
194     } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") ||
195               line.starts_with("**") {
196         &line[2..]
197     } else if line.starts_with('*') {
198         &line[1..]
199     } else {
200         line
201     }
202 }
203
204 pub trait FindUncommented {
205     fn find_uncommented(&self, pat: &str) -> Option<usize>;
206 }
207
208 impl FindUncommented for str {
209     fn find_uncommented(&self, pat: &str) -> Option<usize> {
210         let mut needle_iter = pat.chars();
211         for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
212             match needle_iter.next() {
213                 None => {
214                     return Some(i - pat.len());
215                 }
216                 Some(c) => {
217                     match kind {
218                         FullCodeCharKind::Normal if b == c => {}
219                         _ => {
220                             needle_iter = pat.chars();
221                         }
222                     }
223                 }
224             }
225         }
226
227         // Handle case where the pattern is a suffix of the search string
228         match needle_iter.next() {
229             Some(_) => None,
230             None => Some(self.len() - pat.len()),
231         }
232     }
233 }
234
235 // Returns the first byte position after the first comment. The given string
236 // is expected to be prefixed by a comment, including delimiters.
237 // Good: "/* /* inner */ outer */ code();"
238 // Bad:  "code(); // hello\n world!"
239 pub fn find_comment_end(s: &str) -> Option<usize> {
240     let mut iter = CharClasses::new(s.char_indices());
241     for (kind, (i, _c)) in &mut iter {
242         if kind == FullCodeCharKind::Normal {
243             return Some(i);
244         }
245     }
246
247     // Handle case where the comment ends at the end of s.
248     if iter.status == CharClassesStatus::Normal {
249         Some(s.len())
250     } else {
251         None
252     }
253 }
254
255 /// Returns true if text contains any comment.
256 pub fn contains_comment(text: &str) -> bool {
257     CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
258 }
259
260 struct CharClasses<T>
261     where T: Iterator,
262           T::Item: RichChar
263 {
264     base: iter::Peekable<T>,
265     status: CharClassesStatus,
266 }
267
268 trait RichChar {
269     fn get_char(&self) -> char;
270 }
271
272 impl RichChar for char {
273     fn get_char(&self) -> char {
274         *self
275     }
276 }
277
278 impl RichChar for (usize, char) {
279     fn get_char(&self) -> char {
280         self.1
281     }
282 }
283
284 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
285 enum CharClassesStatus {
286     Normal,
287     LitString,
288     LitStringEscape,
289     LitChar,
290     LitCharEscape,
291     // The u32 is the nesting deepness of the comment
292     BlockComment(u32),
293     // Status when the '/' has been consumed, but not yet the '*', deepness is
294     // the new deepness (after the comment opening).
295     BlockCommentOpening(u32),
296     // Status when the '*' has been consumed, but not yet the '/', deepness is
297     // the new deepness (after the comment closing).
298     BlockCommentClosing(u32),
299     LineComment,
300 }
301
302 /// Distinguish between functional part of code and comments
303 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
304 pub enum CodeCharKind {
305     Normal,
306     Comment,
307 }
308
309 /// Distinguish between functional part of code and comments,
310 /// describing opening and closing of comments for ease when chunking
311 /// code from tagged characters
312 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
313 enum FullCodeCharKind {
314     Normal,
315     /// The first character of a comment, there is only one for a comment (always '/')
316     StartComment,
317     /// Any character inside a comment including the second character of comment
318     /// marks ("//", "/*")
319     InComment,
320     /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
321     EndComment,
322 }
323
324 impl FullCodeCharKind {
325     fn is_comment(&self) -> bool {
326         match *self {
327             FullCodeCharKind::Normal => false,
328             FullCodeCharKind::StartComment |
329             FullCodeCharKind::InComment |
330             FullCodeCharKind::EndComment => true,
331         }
332     }
333
334     fn to_codecharkind(&self) -> CodeCharKind {
335         if self.is_comment() {
336             CodeCharKind::Comment
337         } else {
338             CodeCharKind::Normal
339         }
340     }
341 }
342
343 impl<T> CharClasses<T>
344     where T: Iterator,
345           T::Item: RichChar
346 {
347     fn new(base: T) -> CharClasses<T> {
348         CharClasses {
349             base: base.peekable(),
350             status: CharClassesStatus::Normal,
351         }
352     }
353 }
354
355 impl<T> Iterator for CharClasses<T>
356     where T: Iterator,
357           T::Item: RichChar
358 {
359     type Item = (FullCodeCharKind, T::Item);
360
361     fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
362         let item = try_opt!(self.base.next());
363         let chr = item.get_char();
364         self.status = match self.status {
365             CharClassesStatus::LitString => {
366                 match chr {
367                     '"' => CharClassesStatus::Normal,
368                     '\\' => CharClassesStatus::LitStringEscape,
369                     _ => CharClassesStatus::LitString,
370                 }
371             }
372             CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
373             CharClassesStatus::LitChar => {
374                 match chr {
375                     '\\' => CharClassesStatus::LitCharEscape,
376                     '\'' => CharClassesStatus::Normal,
377                     _ => CharClassesStatus::LitChar,
378                 }
379             }
380             CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
381             CharClassesStatus::Normal => {
382                 match chr {
383                     '"' => CharClassesStatus::LitString,
384                     '\'' => CharClassesStatus::LitChar,
385                     '/' => {
386                         match self.base.peek() {
387                             Some(next) if next.get_char() == '*' => {
388                                 self.status = CharClassesStatus::BlockCommentOpening(1);
389                                 return Some((FullCodeCharKind::StartComment, item));
390                             }
391                             Some(next) if next.get_char() == '/' => {
392                                 self.status = CharClassesStatus::LineComment;
393                                 return Some((FullCodeCharKind::StartComment, item));
394                             }
395                             _ => CharClassesStatus::Normal,
396                         }
397                     }
398                     _ => CharClassesStatus::Normal,
399                 }
400             }
401             CharClassesStatus::BlockComment(deepness) => {
402                 assert!(deepness != 0);
403                 self.status = match self.base.peek() {
404                     Some(next) if next.get_char() == '/' && chr == '*' => {
405                         CharClassesStatus::BlockCommentClosing(deepness - 1)
406                     }
407                     Some(next) if next.get_char() == '*' && chr == '/' => {
408                         CharClassesStatus::BlockCommentOpening(deepness + 1)
409                     }
410                     _ => CharClassesStatus::BlockComment(deepness),
411                 };
412                 return Some((FullCodeCharKind::InComment, item));
413             }
414             CharClassesStatus::BlockCommentOpening(deepness) => {
415                 assert_eq!(chr, '*');
416                 self.status = CharClassesStatus::BlockComment(deepness);
417                 return Some((FullCodeCharKind::InComment, item));
418             }
419             CharClassesStatus::BlockCommentClosing(deepness) => {
420                 assert_eq!(chr, '/');
421                 if deepness == 0 {
422                     self.status = CharClassesStatus::Normal;
423                     return Some((FullCodeCharKind::EndComment, item));
424                 } else {
425                     self.status = CharClassesStatus::BlockComment(deepness);
426                     return Some((FullCodeCharKind::InComment, item));
427                 }
428             }
429             CharClassesStatus::LineComment => {
430                 match chr {
431                     '\n' => {
432                         self.status = CharClassesStatus::Normal;
433                         return Some((FullCodeCharKind::EndComment, item));
434                     }
435                     _ => {
436                         self.status = CharClassesStatus::LineComment;
437                         return Some((FullCodeCharKind::InComment, item));
438                     }
439                 }
440             }
441         };
442         Some((FullCodeCharKind::Normal, item))
443     }
444 }
445
446 /// Iterator over functional and commented parts of a string. Any part of a string is either
447 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
448 /// comments is functional code. Line comments contain their ending newlines.
449 struct UngroupedCommentCodeSlices<'a> {
450     slice: &'a str,
451     iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
452 }
453
454 impl<'a> UngroupedCommentCodeSlices<'a> {
455     fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
456         UngroupedCommentCodeSlices {
457             slice: code,
458             iter: CharClasses::new(code.char_indices()).peekable(),
459         }
460     }
461 }
462
463 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
464     type Item = (CodeCharKind, usize, &'a str);
465
466     fn next(&mut self) -> Option<Self::Item> {
467         let (kind, (start_idx, _)) = try_opt!(self.iter.next());
468         match kind {
469             FullCodeCharKind::Normal => {
470                 // Consume all the Normal code
471                 while let Some(&(FullCodeCharKind::Normal, (_, _))) = self.iter.peek() {
472                     let _ = self.iter.next();
473                 }
474             }
475             FullCodeCharKind::StartComment => {
476                 // Consume the whole comment
477                 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
478             }
479             _ => panic!(),
480         }
481         let slice = match self.iter.peek() {
482             Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
483             None => &self.slice[start_idx..],
484         };
485         Some((if kind.is_comment() {
486                   CodeCharKind::Comment
487               } else {
488                   CodeCharKind::Normal
489               },
490               start_idx,
491               slice))
492     }
493 }
494
495
496
497
498 /// Iterator over an alternating sequence of functional and commented parts of
499 /// a string. The first item is always a, possibly zero length, subslice of
500 /// functional text. Line style comments contain their ending newlines.
501 pub struct CommentCodeSlices<'a> {
502     slice: &'a str,
503     last_slice_kind: CodeCharKind,
504     last_slice_end: usize,
505 }
506
507 impl<'a> CommentCodeSlices<'a> {
508     pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
509         CommentCodeSlices {
510             slice: slice,
511             last_slice_kind: CodeCharKind::Comment,
512             last_slice_end: 0,
513         }
514     }
515 }
516
517 impl<'a> Iterator for CommentCodeSlices<'a> {
518     type Item = (CodeCharKind, usize, &'a str);
519
520     fn next(&mut self) -> Option<Self::Item> {
521         if self.last_slice_end == self.slice.len() {
522             return None;
523         }
524
525         let mut sub_slice_end = self.last_slice_end;
526         let mut first_whitespace = None;
527         let subslice = &self.slice[self.last_slice_end..];
528         let mut iter = CharClasses::new(subslice.char_indices());
529
530         for (kind, (i, c)) in &mut iter {
531             let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
532                                        &subslice[..2] == "//" &&
533                                        [' ', '\t'].contains(&c);
534
535             if is_comment_connector && first_whitespace.is_none() {
536                 first_whitespace = Some(i);
537             }
538
539             if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
540                 let last_index = match first_whitespace {
541                     Some(j) => j,
542                     None => i,
543                 };
544                 sub_slice_end = self.last_slice_end + last_index;
545                 break;
546             }
547
548             if !is_comment_connector {
549                 first_whitespace = None;
550             }
551         }
552
553         if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
554             // This was the last subslice.
555             sub_slice_end = match first_whitespace {
556                 Some(i) => self.last_slice_end + i,
557                 None => self.slice.len(),
558             };
559         }
560
561         let kind = match self.last_slice_kind {
562             CodeCharKind::Comment => CodeCharKind::Normal,
563             CodeCharKind::Normal => CodeCharKind::Comment,
564         };
565         let res = (kind, self.last_slice_end, &self.slice[self.last_slice_end..sub_slice_end]);
566         self.last_slice_end = sub_slice_end;
567         self.last_slice_kind = kind;
568
569         Some(res)
570     }
571 }
572
573 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
574 /// (if it fits in the width/offset, else return None), else return `new`
575 pub fn recover_comment_removed(new: String,
576                                span: Span,
577                                context: &RewriteContext,
578                                shape: Shape)
579                                -> Option<String> {
580     let snippet = context.snippet(span);
581     if changed_comment_content(&snippet, &new) {
582         // We missed some comments
583         // Keep previous formatting if it satisfies the constrains
584         wrap_str(snippet, context.config.max_width, shape)
585     } else {
586         Some(new)
587     }
588 }
589
590 /// Return true if the two strings of code have the same payload of comments.
591 /// The payload of comments is everything in the string except:
592 ///     - actual code (not comments)
593 ///     - comment start/end marks
594 ///     - whitespace
595 ///     - '*' at the beginning of lines in block comments
596 fn changed_comment_content(orig: &str, new: &str) -> bool {
597     // Cannot write this as a fn since we cannot return types containing closures
598     let code_comment_content = |code| {
599         let slices = UngroupedCommentCodeSlices::new(code);
600         slices
601             .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
602             .flat_map(|(_, _, s)| CommentReducer::new(s))
603     };
604     let res = code_comment_content(orig).ne(code_comment_content(new));
605     debug!("comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
606            res,
607            orig,
608            new,
609            code_comment_content(orig).collect::<String>(),
610            code_comment_content(new).collect::<String>());
611     res
612 }
613
614
615 /// Iterator over the 'payload' characters of a comment.
616 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
617 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
618 /// for example).
619 struct CommentReducer<'a> {
620     is_block: bool,
621     at_start_line: bool,
622     iter: std::str::Chars<'a>,
623 }
624
625 impl<'a> CommentReducer<'a> {
626     fn new(comment: &'a str) -> CommentReducer<'a> {
627         let is_block = comment.starts_with("/*");
628         let comment = remove_comment_header(comment);
629         CommentReducer {
630             is_block: is_block,
631             at_start_line: false, // There are no supplementary '*' on the first line
632             iter: comment.chars(),
633         }
634     }
635 }
636
637 impl<'a> Iterator for CommentReducer<'a> {
638     type Item = char;
639     fn next(&mut self) -> Option<Self::Item> {
640         loop {
641             let mut c = try_opt!(self.iter.next());
642             if self.is_block && self.at_start_line {
643                 while c.is_whitespace() {
644                     c = try_opt!(self.iter.next());
645                 }
646                 // Ignore leading '*'
647                 if c == '*' {
648                     c = try_opt!(self.iter.next());
649                 }
650             } else {
651                 if c == '\n' {
652                     self.at_start_line = true;
653                 }
654             }
655             if !c.is_whitespace() {
656                 return Some(c);
657             }
658         }
659     }
660 }
661
662
663 fn remove_comment_header(comment: &str) -> &str {
664     if comment.starts_with("///") || comment.starts_with("//!") {
665         &comment[3..]
666     } else if comment.starts_with("//") {
667         &comment[2..]
668     } else if (comment.starts_with("/**") && !comment.starts_with("/**/")) ||
669               comment.starts_with("/*!") {
670         &comment[3..comment.len() - 2]
671     } else {
672         assert!(comment.starts_with("/*"),
673                 format!("string '{}' is not a comment", comment));
674         &comment[2..comment.len() - 2]
675     }
676 }
677
678 #[cfg(test)]
679 mod test {
680     use super::{CharClasses, CodeCharKind, FullCodeCharKind, contains_comment, rewrite_comment,
681                 FindUncommented, CommentCodeSlices};
682     use {Indent, Shape};
683
684     #[test]
685     fn char_classes() {
686         let mut iter = CharClasses::new("//\n\n".chars());
687
688         assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
689         assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
690         assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
691         assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
692         assert_eq!(None, iter.next());
693     }
694
695     #[test]
696     fn comment_code_slices() {
697         let input = "code(); /* test */ 1 + 1";
698         let mut iter = CommentCodeSlices::new(input);
699
700         assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
701         assert_eq!((CodeCharKind::Comment, 8, "/* test */"),
702                    iter.next().unwrap());
703         assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
704         assert_eq!(None, iter.next());
705     }
706
707     #[test]
708     fn comment_code_slices_two() {
709         let input = "// comment\n    test();";
710         let mut iter = CommentCodeSlices::new(input);
711
712         assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
713         assert_eq!((CodeCharKind::Comment, 0, "// comment\n"),
714                    iter.next().unwrap());
715         assert_eq!((CodeCharKind::Normal, 11, "    test();"),
716                    iter.next().unwrap());
717         assert_eq!(None, iter.next());
718     }
719
720     #[test]
721     fn comment_code_slices_three() {
722         let input = "1 // comment\n    // comment2\n\n";
723         let mut iter = CommentCodeSlices::new(input);
724
725         assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
726         assert_eq!((CodeCharKind::Comment, 2, "// comment\n    // comment2\n"),
727                    iter.next().unwrap());
728         assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
729         assert_eq!(None, iter.next());
730     }
731
732     #[test]
733     #[cfg_attr(rustfmt, rustfmt_skip)]
734     fn format_comments() {
735         let mut config: ::config::Config = Default::default();
736         config.wrap_comments = true;
737         config.normalize_comments = true;
738
739         let comment = rewrite_comment(" //test",
740                                       true,
741                                       Shape::legacy(100, Indent::new(0, 100)),
742                                       &config).unwrap();
743         assert_eq!("/* test */", comment);
744
745         let comment = rewrite_comment("// comment on a",
746                                       false,
747                                       Shape::legacy(10, Indent::empty()),
748                                       &config).unwrap();
749         assert_eq!("// comment\n// on a", comment);
750
751         let comment = rewrite_comment("//  A multi line comment\n             // between args.",
752                                       false,
753                                       Shape::legacy(60, Indent::new(0, 12)),
754                                       &config).unwrap();
755         assert_eq!("//  A multi line comment\n            // between args.", comment);
756
757         let input = "// comment";
758         let expected =
759             "/* comment */";
760         let comment = rewrite_comment(input,
761                                       true,
762                                       Shape::legacy(9, Indent::new(0, 69)),
763                                       &config).unwrap();
764         assert_eq!(expected, comment);
765
766         let comment = rewrite_comment("/*   trimmed    */",
767                                       true,
768                                       Shape::legacy(100, Indent::new(0, 100)),
769                                       &config).unwrap();
770         assert_eq!("/* trimmed */", comment);
771     }
772
773     // This is probably intended to be a non-test fn, but it is not used. I'm
774     // keeping it around unless it helps us test stuff.
775     fn uncommented(text: &str) -> String {
776         CharClasses::new(text.chars())
777             .filter_map(|(s, c)| match s {
778                             FullCodeCharKind::Normal => Some(c),
779                             _ => None,
780                         })
781             .collect()
782     }
783
784     #[test]
785     fn test_uncommented() {
786         assert_eq!(&uncommented("abc/*...*/"), "abc");
787         assert_eq!(&uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
788                    "..ac\n");
789         assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
790     }
791
792     #[test]
793     fn test_contains_comment() {
794         assert_eq!(contains_comment("abc"), false);
795         assert_eq!(contains_comment("abc // qsdf"), true);
796         assert_eq!(contains_comment("abc /* kqsdf"), true);
797         assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
798     }
799
800     #[test]
801     fn test_find_uncommented() {
802         fn check(haystack: &str, needle: &str, expected: Option<usize>) {
803             assert_eq!(expected, haystack.find_uncommented(needle));
804         }
805
806         check("/*/ */test", "test", Some(6));
807         check("//test\ntest", "test", Some(7));
808         check("/* comment only */", "whatever", None);
809         check("/* comment */ some text /* more commentary */ result",
810               "result",
811               Some(46));
812         check("sup // sup", "p", Some(2));
813         check("sup", "x", None);
814         check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
815         check("/*sup yo? \n sup*/ sup", "p", Some(20));
816         check("hel/*lohello*/lo", "hello", None);
817         check("acb", "ab", None);
818         check(",/*A*/ ", ",", Some(0));
819         check("abc", "abc", Some(0));
820         check("/* abc */", "abc", None);
821         check("/**/abc/* */", "abc", Some(4));
822         check("\"/* abc */\"", "abc", Some(4));
823         check("\"/* abc", "abc", Some(4));
824     }
825 }