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.
11 // Formatting and tools for comments.
13 use std::{self, iter};
15 use syntax::codemap::Span;
19 use rewrite::RewriteContext;
20 use string::{rewrite_string, StringFormat};
21 use utils::{first_line_width, last_line_width, wrap_str};
23 fn is_custom_comment(comment: &str) -> bool {
24 if !comment.starts_with("//") {
27 if let Some(c) = comment.chars().nth(2) {
28 !c.is_alphanumeric() && !c.is_whitespace()
35 #[derive(PartialEq, Eq)]
36 pub enum CommentStyle<'a> {
46 fn custom_opener(s: &str) -> &str {
47 s.lines().next().map_or("", |first_line| {
50 .map_or(first_line, |space_index| &first_line[0..space_index + 1])
54 impl<'a> CommentStyle<'a> {
55 pub fn opener(&self) -> &'a str {
57 CommentStyle::DoubleSlash => "// ",
58 CommentStyle::TripleSlash => "/// ",
59 CommentStyle::Doc => "//! ",
60 CommentStyle::SingleBullet => "/* ",
61 CommentStyle::DoubleBullet => "/** ",
62 CommentStyle::Exclamation => "/*! ",
63 CommentStyle::Custom(opener) => opener,
67 pub fn closer(&self) -> &'a str {
69 CommentStyle::DoubleSlash |
70 CommentStyle::TripleSlash |
71 CommentStyle::Custom(..) |
72 CommentStyle::Doc => "",
73 CommentStyle::DoubleBullet => " **/",
74 CommentStyle::SingleBullet | CommentStyle::Exclamation => " */",
78 pub fn line_start(&self) -> &'a str {
80 CommentStyle::DoubleSlash => "// ",
81 CommentStyle::TripleSlash => "/// ",
82 CommentStyle::Doc => "//! ",
83 CommentStyle::SingleBullet | CommentStyle::Exclamation => " * ",
84 CommentStyle::DoubleBullet => " ** ",
85 CommentStyle::Custom(opener) => opener,
89 pub fn to_str_tuplet(&self) -> (&'a str, &'a str, &'a str) {
90 (self.opener(), self.closer(), self.line_start())
93 pub fn line_with_same_comment_style(&self, line: &str, normalize_comments: bool) -> bool {
95 CommentStyle::DoubleSlash | CommentStyle::TripleSlash | CommentStyle::Doc => {
96 line.trim_left().starts_with(self.line_start().trim_left()) ||
97 comment_style(line, normalize_comments) == *self
99 CommentStyle::DoubleBullet | CommentStyle::SingleBullet | CommentStyle::Exclamation => {
100 line.trim_left().starts_with(self.closer().trim_left()) ||
101 line.trim_left().starts_with(self.line_start().trim_left()) ||
102 comment_style(line, normalize_comments) == *self
104 CommentStyle::Custom(opener) => line.trim_left().starts_with(opener.trim_right()),
109 fn comment_style(orig: &str, normalize_comments: bool) -> CommentStyle {
110 if !normalize_comments {
111 if orig.starts_with("/**") && !orig.starts_with("/**/") {
112 CommentStyle::DoubleBullet
113 } else if orig.starts_with("/*!") {
114 CommentStyle::Exclamation
115 } else if orig.starts_with("/*") {
116 CommentStyle::SingleBullet
117 } else if orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/') {
118 CommentStyle::TripleSlash
119 } else if orig.starts_with("//!") {
121 } else if is_custom_comment(orig) {
122 CommentStyle::Custom(custom_opener(orig))
124 CommentStyle::DoubleSlash
126 } else if (orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/')) ||
127 (orig.starts_with("/**") && !orig.starts_with("/**/"))
129 CommentStyle::TripleSlash
130 } else if orig.starts_with("//!") || orig.starts_with("/*!") {
132 } else if is_custom_comment(orig) {
133 CommentStyle::Custom(custom_opener(orig))
135 CommentStyle::DoubleSlash
139 pub fn combine_strs_with_missing_comments(
140 context: &RewriteContext,
146 ) -> Option<String> {
147 let mut allow_one_line = !prev_str.contains('\n') && !next_str.contains('\n');
148 let first_sep = if prev_str.is_empty() || next_str.is_empty() {
153 let mut one_line_width =
154 last_line_width(prev_str) + first_line_width(next_str) + first_sep.len();
156 let indent_str = shape.indent.to_string(context.config);
157 let missing_comment = try_opt!(rewrite_missing_comment(span, shape, context));
159 if missing_comment.is_empty() {
160 if allow_extend && prev_str.len() + first_sep.len() + next_str.len() <= shape.width {
161 return Some(format!("{}{}{}", prev_str, first_sep, next_str));
163 let sep = if prev_str.is_empty() {
166 String::from("\n") + &indent_str
168 return Some(format!("{}{}{}", prev_str, sep, next_str));
172 // We have a missing comment between the first expression and the second expression.
174 // Peek the the original source code and find out whether there is a newline between the first
175 // expression and the second expression or the missing comment. We will preserve the orginal
176 // layout whenever possible.
177 let original_snippet = context.snippet(span);
178 let prefer_same_line = if let Some(pos) = original_snippet.chars().position(|c| c == '/') {
179 !original_snippet[..pos].contains('\n')
181 !original_snippet.contains('\n')
184 one_line_width -= first_sep.len();
185 let first_sep = if prev_str.is_empty() || missing_comment.is_empty() {
188 let one_line_width = last_line_width(prev_str) + first_line_width(&missing_comment) + 1;
189 if prefer_same_line && one_line_width <= shape.width {
192 format!("\n{}", indent_str)
195 let second_sep = if missing_comment.is_empty() || next_str.is_empty() {
198 if missing_comment.starts_with("//") {
199 format!("\n{}", indent_str)
201 one_line_width += missing_comment.len() + first_sep.len() + 1;
202 allow_one_line &= !missing_comment.starts_with("//") && !missing_comment.contains('\n');
203 if prefer_same_line && allow_one_line && one_line_width <= shape.width {
206 format!("\n{}", indent_str)
220 pub fn rewrite_comment(
225 ) -> Option<String> {
226 // If there are lines without a starting sigil, we won't format them correctly
227 // so in that case we won't even re-align (if !config.normalize_comments()) and
228 // we should stop now.
229 let num_bare_lines = orig.lines()
230 .map(|line| line.trim())
232 !(l.starts_with('*') || l.starts_with("//") || l.starts_with("/*"))
235 if num_bare_lines > 0 && !config.normalize_comments() {
236 return Some(orig.to_owned());
238 if !config.normalize_comments() && !config.wrap_comments() {
239 return light_rewrite_comment(orig, shape.indent, config);
242 identify_comment(orig, block_style, shape, config)
250 ) -> Option<String> {
251 let style = comment_style(orig, false);
252 let first_group = orig.lines()
253 .take_while(|l| style.line_with_same_comment_style(l, false))
256 let rest = orig.lines()
257 .skip(first_group.lines().count())
261 let first_group_str = try_opt!(rewrite_comment_inner(
269 Some(first_group_str)
271 identify_comment(&rest, block_style, shape, config).map(|rest_str| {
275 shape.indent.to_string(config),
282 fn rewrite_comment_inner(
288 ) -> Option<String> {
289 let (opener, closer, line_start) = if block_style {
290 CommentStyle::SingleBullet.to_str_tuplet()
292 comment_style(orig, config.normalize_comments()).to_str_tuplet()
295 let max_chars = shape
297 .checked_sub(closer.len() + opener.len())
299 let indent_str = shape.indent.to_string(config);
300 let fmt = StringFormat {
303 line_start: line_start,
305 shape: Shape::legacy(max_chars, shape.indent + (opener.len() - line_start.len())),
310 let line_breaks = orig.trim_right().chars().filter(|&c| c == '\n').count();
311 let lines = orig.lines()
313 .map(|(i, mut line)| {
316 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
317 line = &line[..(line.len() - 2)].trim_right();
322 .map(|s| left_trim_comment_line(s, &style))
323 .map(|line| if orig.starts_with("/*") && line_breaks == 0 {
329 let mut result = opener.to_owned();
331 if result == opener {
337 result.push_str(&indent_str);
338 result.push_str(line_start);
341 if config.wrap_comments() && line.len() > max_chars {
342 let rewrite = rewrite_string(line, &fmt).unwrap_or(line.to_owned());
343 result.push_str(&rewrite);
345 if line.is_empty() && result.ends_with(' ') {
346 // Remove space if this is an empty comment or a doc comment.
349 result.push_str(line);
353 result.push_str(closer);
354 if result == opener && result.ends_with(' ') {
362 /// Given the span, rewrite the missing comment inside it if available.
363 /// Note that the given span must only include comments (or leading/trailing whitespaces).
364 pub fn rewrite_missing_comment(
367 context: &RewriteContext,
368 ) -> Option<String> {
369 let missing_snippet = context.snippet(span);
370 let trimmed_snippet = missing_snippet.trim();
371 if !trimmed_snippet.is_empty() {
372 rewrite_comment(trimmed_snippet, false, shape, context.config)
378 /// Recover the missing comments in the specified span, if available.
379 /// The layout of the comments will be preserved as long as it does not break the code
380 /// and its total width does not exceed the max width.
381 pub fn recover_missing_comment_in_span(
384 context: &RewriteContext,
386 ) -> Option<String> {
387 let missing_comment = try_opt!(rewrite_missing_comment(span, shape, context));
388 if missing_comment.is_empty() {
391 let missing_snippet = context.snippet(span);
392 let pos = missing_snippet.chars().position(|c| c == '/').unwrap_or(0);
394 let total_width = missing_comment.len() + used_width + 1;
395 let force_new_line_before_comment =
396 missing_snippet[..pos].contains('\n') || total_width > context.config.max_width();
397 let sep = if force_new_line_before_comment {
398 format!("\n{}", shape.indent.to_string(context.config))
402 Some(format!("{}{}", sep, missing_comment))
406 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
407 fn light_rewrite_comment(orig: &str, offset: Indent, config: &Config) -> Option<String> {
408 let lines: Vec<&str> = orig.lines()
410 // This is basically just l.trim(), but in the case that a line starts
411 // with `*` we want to leave one space before it, so it aligns with the
413 let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
414 if let Some(fnw) = first_non_whitespace {
415 if l.as_bytes()[fnw] == '*' as u8 && fnw > 0 {
425 Some(lines.join(&format!("\n{}", offset.to_string(config))))
428 /// Trims comment characters and possibly a single space from the left of a string.
429 /// Does not trim all whitespace.
430 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle) -> &'a str {
431 if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") ||
432 line.starts_with("/** ")
435 } else if let &CommentStyle::Custom(opener) = style {
436 if line.starts_with(opener) {
437 &line[opener.len()..]
439 &line[opener.trim_right().len()..]
441 } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!") ||
442 line.starts_with("///") || line.starts_with("** ") ||
443 line.starts_with("/*!") ||
444 (line.starts_with("/**") && !line.starts_with("/**/"))
447 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") ||
448 line.starts_with("**")
451 } else if line.starts_with('*') {
458 pub trait FindUncommented {
459 fn find_uncommented(&self, pat: &str) -> Option<usize>;
462 impl FindUncommented for str {
463 fn find_uncommented(&self, pat: &str) -> Option<usize> {
464 let mut needle_iter = pat.chars();
465 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
466 match needle_iter.next() {
468 return Some(i - pat.len());
470 Some(c) => match kind {
471 FullCodeCharKind::Normal if b == c => {}
473 needle_iter = pat.chars();
479 // Handle case where the pattern is a suffix of the search string
480 match needle_iter.next() {
482 None => Some(self.len() - pat.len()),
487 // Returns the first byte position after the first comment. The given string
488 // is expected to be prefixed by a comment, including delimiters.
489 // Good: "/* /* inner */ outer */ code();"
490 // Bad: "code(); // hello\n world!"
491 pub fn find_comment_end(s: &str) -> Option<usize> {
492 let mut iter = CharClasses::new(s.char_indices());
493 for (kind, (i, _c)) in &mut iter {
494 if kind == FullCodeCharKind::Normal {
499 // Handle case where the comment ends at the end of s.
500 if iter.status == CharClassesStatus::Normal {
507 /// Returns true if text contains any comment.
508 pub fn contains_comment(text: &str) -> bool {
509 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
512 struct CharClasses<T>
517 base: iter::Peekable<T>,
518 status: CharClassesStatus,
522 fn get_char(&self) -> char;
525 impl RichChar for char {
526 fn get_char(&self) -> char {
531 impl RichChar for (usize, char) {
532 fn get_char(&self) -> char {
537 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
538 enum CharClassesStatus {
544 // The u32 is the nesting deepness of the comment
546 // Status when the '/' has been consumed, but not yet the '*', deepness is
547 // the new deepness (after the comment opening).
548 BlockCommentOpening(u32),
549 // Status when the '*' has been consumed, but not yet the '/', deepness is
550 // the new deepness (after the comment closing).
551 BlockCommentClosing(u32),
555 /// Distinguish between functional part of code and comments
556 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
557 pub enum CodeCharKind {
562 /// Distinguish between functional part of code and comments,
563 /// describing opening and closing of comments for ease when chunking
564 /// code from tagged characters
565 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
566 enum FullCodeCharKind {
568 /// The first character of a comment, there is only one for a comment (always '/')
570 /// Any character inside a comment including the second character of comment
571 /// marks ("//", "/*")
573 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
577 impl FullCodeCharKind {
578 fn is_comment(&self) -> bool {
580 FullCodeCharKind::Normal => false,
581 FullCodeCharKind::StartComment |
582 FullCodeCharKind::InComment |
583 FullCodeCharKind::EndComment => true,
587 fn to_codecharkind(&self) -> CodeCharKind {
588 if self.is_comment() {
589 CodeCharKind::Comment
596 impl<T> CharClasses<T>
601 fn new(base: T) -> CharClasses<T> {
603 base: base.peekable(),
604 status: CharClassesStatus::Normal,
609 impl<T> Iterator for CharClasses<T>
614 type Item = (FullCodeCharKind, T::Item);
616 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
617 let item = try_opt!(self.base.next());
618 let chr = item.get_char();
619 self.status = match self.status {
620 CharClassesStatus::LitString => match chr {
621 '"' => CharClassesStatus::Normal,
622 '\\' => CharClassesStatus::LitStringEscape,
623 _ => CharClassesStatus::LitString,
625 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
626 CharClassesStatus::LitChar => match chr {
627 '\\' => CharClassesStatus::LitCharEscape,
628 '\'' => CharClassesStatus::Normal,
629 _ => CharClassesStatus::LitChar,
631 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
632 CharClassesStatus::Normal => match chr {
633 '"' => CharClassesStatus::LitString,
634 '\'' => CharClassesStatus::LitChar,
635 '/' => match self.base.peek() {
636 Some(next) if next.get_char() == '*' => {
637 self.status = CharClassesStatus::BlockCommentOpening(1);
638 return Some((FullCodeCharKind::StartComment, item));
640 Some(next) if next.get_char() == '/' => {
641 self.status = CharClassesStatus::LineComment;
642 return Some((FullCodeCharKind::StartComment, item));
644 _ => CharClassesStatus::Normal,
646 _ => CharClassesStatus::Normal,
648 CharClassesStatus::BlockComment(deepness) => {
649 assert!(deepness != 0);
650 self.status = match self.base.peek() {
651 Some(next) if next.get_char() == '/' && chr == '*' => {
652 CharClassesStatus::BlockCommentClosing(deepness - 1)
654 Some(next) if next.get_char() == '*' && chr == '/' => {
655 CharClassesStatus::BlockCommentOpening(deepness + 1)
657 _ => CharClassesStatus::BlockComment(deepness),
659 return Some((FullCodeCharKind::InComment, item));
661 CharClassesStatus::BlockCommentOpening(deepness) => {
662 assert_eq!(chr, '*');
663 self.status = CharClassesStatus::BlockComment(deepness);
664 return Some((FullCodeCharKind::InComment, item));
666 CharClassesStatus::BlockCommentClosing(deepness) => {
667 assert_eq!(chr, '/');
669 self.status = CharClassesStatus::Normal;
670 return Some((FullCodeCharKind::EndComment, item));
672 self.status = CharClassesStatus::BlockComment(deepness);
673 return Some((FullCodeCharKind::InComment, item));
676 CharClassesStatus::LineComment => match chr {
678 self.status = CharClassesStatus::Normal;
679 return Some((FullCodeCharKind::EndComment, item));
682 self.status = CharClassesStatus::LineComment;
683 return Some((FullCodeCharKind::InComment, item));
687 Some((FullCodeCharKind::Normal, item))
691 /// Iterator over functional and commented parts of a string. Any part of a string is either
692 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
693 /// comments is functional code. Line comments contain their ending newlines.
694 struct UngroupedCommentCodeSlices<'a> {
696 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
699 impl<'a> UngroupedCommentCodeSlices<'a> {
700 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
701 UngroupedCommentCodeSlices {
703 iter: CharClasses::new(code.char_indices()).peekable(),
708 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
709 type Item = (CodeCharKind, usize, &'a str);
711 fn next(&mut self) -> Option<Self::Item> {
712 let (kind, (start_idx, _)) = try_opt!(self.iter.next());
714 FullCodeCharKind::Normal => {
715 // Consume all the Normal code
716 while let Some(&(FullCodeCharKind::Normal, (_, _))) = self.iter.peek() {
717 let _ = self.iter.next();
720 FullCodeCharKind::StartComment => {
721 // Consume the whole comment
722 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
726 let slice = match self.iter.peek() {
727 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
728 None => &self.slice[start_idx..],
731 if kind.is_comment() {
732 CodeCharKind::Comment
745 /// Iterator over an alternating sequence of functional and commented parts of
746 /// a string. The first item is always a, possibly zero length, subslice of
747 /// functional text. Line style comments contain their ending newlines.
748 pub struct CommentCodeSlices<'a> {
750 last_slice_kind: CodeCharKind,
751 last_slice_end: usize,
754 impl<'a> CommentCodeSlices<'a> {
755 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
758 last_slice_kind: CodeCharKind::Comment,
764 impl<'a> Iterator for CommentCodeSlices<'a> {
765 type Item = (CodeCharKind, usize, &'a str);
767 fn next(&mut self) -> Option<Self::Item> {
768 if self.last_slice_end == self.slice.len() {
772 let mut sub_slice_end = self.last_slice_end;
773 let mut first_whitespace = None;
774 let subslice = &self.slice[self.last_slice_end..];
775 let mut iter = CharClasses::new(subslice.char_indices());
777 for (kind, (i, c)) in &mut iter {
778 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
779 &subslice[..2] == "//" &&
780 [' ', '\t'].contains(&c);
782 if is_comment_connector && first_whitespace.is_none() {
783 first_whitespace = Some(i);
786 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
787 let last_index = match first_whitespace {
791 sub_slice_end = self.last_slice_end + last_index;
795 if !is_comment_connector {
796 first_whitespace = None;
800 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
801 // This was the last subslice.
802 sub_slice_end = match first_whitespace {
803 Some(i) => self.last_slice_end + i,
804 None => self.slice.len(),
808 let kind = match self.last_slice_kind {
809 CodeCharKind::Comment => CodeCharKind::Normal,
810 CodeCharKind::Normal => CodeCharKind::Comment,
815 &self.slice[self.last_slice_end..sub_slice_end],
817 self.last_slice_end = sub_slice_end;
818 self.last_slice_kind = kind;
824 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
825 /// (if it fits in the width/offset, else return None), else return `new`
826 pub fn recover_comment_removed(
829 context: &RewriteContext,
831 ) -> Option<String> {
832 let snippet = context.snippet(span);
833 if changed_comment_content(&snippet, &new) {
834 // We missed some comments
835 // Keep previous formatting if it satisfies the constrains
836 wrap_str(snippet, context.config.max_width(), shape)
842 /// Return true if the two strings of code have the same payload of comments.
843 /// The payload of comments is everything in the string except:
844 /// - actual code (not comments)
845 /// - comment start/end marks
847 /// - '*' at the beginning of lines in block comments
848 fn changed_comment_content(orig: &str, new: &str) -> bool {
849 // Cannot write this as a fn since we cannot return types containing closures
850 let code_comment_content = |code| {
851 let slices = UngroupedCommentCodeSlices::new(code);
853 .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
854 .flat_map(|(_, _, s)| CommentReducer::new(s))
856 let res = code_comment_content(orig).ne(code_comment_content(new));
858 "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
862 code_comment_content(orig).collect::<String>(),
863 code_comment_content(new).collect::<String>()
869 /// Iterator over the 'payload' characters of a comment.
870 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
871 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
873 struct CommentReducer<'a> {
876 iter: std::str::Chars<'a>,
879 impl<'a> CommentReducer<'a> {
880 fn new(comment: &'a str) -> CommentReducer<'a> {
881 let is_block = comment.starts_with("/*");
882 let comment = remove_comment_header(comment);
885 at_start_line: false, // There are no supplementary '*' on the first line
886 iter: comment.chars(),
891 impl<'a> Iterator for CommentReducer<'a> {
893 fn next(&mut self) -> Option<Self::Item> {
895 let mut c = try_opt!(self.iter.next());
896 if self.is_block && self.at_start_line {
897 while c.is_whitespace() {
898 c = try_opt!(self.iter.next());
900 // Ignore leading '*'
902 c = try_opt!(self.iter.next());
906 self.at_start_line = true;
909 if !c.is_whitespace() {
917 fn remove_comment_header(comment: &str) -> &str {
918 if comment.starts_with("///") || comment.starts_with("//!") {
920 } else if comment.starts_with("//") {
922 } else if (comment.starts_with("/**") && !comment.starts_with("/**/")) ||
923 comment.starts_with("/*!")
925 &comment[3..comment.len() - 2]
928 comment.starts_with("/*"),
929 format!("string '{}' is not a comment", comment)
931 &comment[2..comment.len() - 2]
937 use super::{contains_comment, rewrite_comment, CharClasses, CodeCharKind, CommentCodeSlices,
938 FindUncommented, FullCodeCharKind};
943 let mut iter = CharClasses::new("//\n\n".chars());
945 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
946 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
947 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
948 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
949 assert_eq!(None, iter.next());
953 fn comment_code_slices() {
954 let input = "code(); /* test */ 1 + 1";
955 let mut iter = CommentCodeSlices::new(input);
957 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
959 (CodeCharKind::Comment, 8, "/* test */"),
962 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
963 assert_eq!(None, iter.next());
967 fn comment_code_slices_two() {
968 let input = "// comment\n test();";
969 let mut iter = CommentCodeSlices::new(input);
971 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
973 (CodeCharKind::Comment, 0, "// comment\n"),
977 (CodeCharKind::Normal, 11, " test();"),
980 assert_eq!(None, iter.next());
984 fn comment_code_slices_three() {
985 let input = "1 // comment\n // comment2\n\n";
986 let mut iter = CommentCodeSlices::new(input);
988 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
990 (CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
993 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
994 assert_eq!(None, iter.next());
998 #[cfg_attr(rustfmt, rustfmt_skip)]
999 fn format_comments() {
1000 let mut config: ::config::Config = Default::default();
1001 config.set().wrap_comments(true);
1002 config.set().normalize_comments(true);
1004 let comment = rewrite_comment(" //test",
1006 Shape::legacy(100, Indent::new(0, 100)),
1008 assert_eq!("/* test */", comment);
1010 let comment = rewrite_comment("// comment on a",
1012 Shape::legacy(10, Indent::empty()),
1014 assert_eq!("// comment\n// on a", comment);
1016 let comment = rewrite_comment("// A multi line comment\n // between args.",
1018 Shape::legacy(60, Indent::new(0, 12)),
1020 assert_eq!("// A multi line comment\n // between args.", comment);
1022 let input = "// comment";
1025 let comment = rewrite_comment(input,
1027 Shape::legacy(9, Indent::new(0, 69)),
1029 assert_eq!(expected, comment);
1031 let comment = rewrite_comment("/* trimmed */",
1033 Shape::legacy(100, Indent::new(0, 100)),
1035 assert_eq!("/* trimmed */", comment);
1038 // This is probably intended to be a non-test fn, but it is not used. I'm
1039 // keeping it around unless it helps us test stuff.
1040 fn uncommented(text: &str) -> String {
1041 CharClasses::new(text.chars())
1042 .filter_map(|(s, c)| match s {
1043 FullCodeCharKind::Normal => Some(c),
1050 fn test_uncommented() {
1051 assert_eq!(&uncommented("abc/*...*/"), "abc");
1053 &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
1056 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
1060 fn test_contains_comment() {
1061 assert_eq!(contains_comment("abc"), false);
1062 assert_eq!(contains_comment("abc // qsdf"), true);
1063 assert_eq!(contains_comment("abc /* kqsdf"), true);
1064 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
1068 fn test_find_uncommented() {
1069 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
1070 assert_eq!(expected, haystack.find_uncommented(needle));
1073 check("/*/ */test", "test", Some(6));
1074 check("//test\ntest", "test", Some(7));
1075 check("/* comment only */", "whatever", None);
1077 "/* comment */ some text /* more commentary */ result",
1081 check("sup // sup", "p", Some(2));
1082 check("sup", "x", None);
1083 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
1084 check("/*sup yo? \n sup*/ sup", "p", Some(20));
1085 check("hel/*lohello*/lo", "hello", None);
1086 check("acb", "ab", None);
1087 check(",/*A*/ ", ",", Some(0));
1088 check("abc", "abc", Some(0));
1089 check("/* abc */", "abc", None);
1090 check("/**/abc/* */", "abc", Some(4));
1091 check("\"/* abc */\"", "abc", Some(4));
1092 check("\"/* abc", "abc", Some(4));