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 original_snippet = context.snippet(span);
157 let trimmed_snippet = original_snippet.trim();
158 let indent_str = shape.indent.to_string(context.config);
160 if trimmed_snippet.is_empty() {
161 if allow_extend && prev_str.len() + first_sep.len() + next_str.len() <= shape.width {
162 return Some(format!("{}{}{}", prev_str, first_sep, next_str));
164 let sep = if prev_str.is_empty() {
167 String::from("\n") + &indent_str
169 return Some(format!("{}{}{}", prev_str, sep, next_str));
173 // We have a missing comment between the first expression and the second expression.
175 // Peek the the original source code and find out whether there is a newline between the first
176 // expression and the second expression or the missing comment. We will preserve the orginal
177 // layout whenever possible.
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 let missing_comment = try_opt!(rewrite_comment(
190 one_line_width -= first_sep.len();
191 let first_sep = if prev_str.is_empty() || missing_comment.is_empty() {
194 let one_line_width = last_line_width(prev_str) + first_line_width(&missing_comment) + 1;
195 if prefer_same_line && one_line_width <= shape.width {
198 format!("\n{}", indent_str)
201 let second_sep = if missing_comment.is_empty() || next_str.is_empty() {
204 if missing_comment.starts_with("//") {
205 format!("\n{}", indent_str)
207 one_line_width += missing_comment.len() + first_sep.len() + 1;
208 allow_one_line &= !missing_comment.starts_with("//") && !missing_comment.contains('\n');
209 if prefer_same_line && allow_one_line && one_line_width <= shape.width {
212 format!("\n{}", indent_str)
226 pub fn rewrite_comment(
231 ) -> Option<String> {
232 // If there are lines without a starting sigil, we won't format them correctly
233 // so in that case we won't even re-align (if !config.normalize_comments()) and
234 // we should stop now.
235 let num_bare_lines = orig.lines()
236 .map(|line| line.trim())
238 !(l.starts_with('*') || l.starts_with("//") || l.starts_with("/*"))
241 if num_bare_lines > 0 && !config.normalize_comments() {
242 return Some(orig.to_owned());
244 if !config.normalize_comments() && !config.wrap_comments() {
245 return light_rewrite_comment(orig, shape.indent, config);
248 identify_comment(orig, block_style, shape, config)
256 ) -> Option<String> {
257 let style = comment_style(orig, false);
258 let first_group = orig.lines()
259 .take_while(|l| style.line_with_same_comment_style(l, false))
262 let rest = orig.lines()
263 .skip(first_group.lines().count())
267 let first_group_str = try_opt!(rewrite_comment_inner(
275 Some(first_group_str)
277 identify_comment(&rest, block_style, shape, config).map(|rest_str| {
281 shape.indent.to_string(config),
288 fn rewrite_comment_inner(
294 ) -> Option<String> {
295 let (opener, closer, line_start) = if block_style {
296 CommentStyle::SingleBullet.to_str_tuplet()
298 comment_style(orig, config.normalize_comments()).to_str_tuplet()
301 let max_chars = shape
303 .checked_sub(closer.len() + opener.len())
305 let indent_str = shape.indent.to_string(config);
306 let fmt = StringFormat {
309 line_start: line_start,
311 shape: Shape::legacy(max_chars, shape.indent + (opener.len() - line_start.len())),
316 let line_breaks = orig.trim_right().chars().filter(|&c| c == '\n').count();
317 let lines = orig.lines()
319 .map(|(i, mut line)| {
322 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
323 line = &line[..(line.len() - 2)].trim_right();
328 .map(|s| left_trim_comment_line(s, &style))
329 .map(|line| if orig.starts_with("/*") && line_breaks == 0 {
335 let mut result = opener.to_owned();
337 if result == opener {
343 result.push_str(&indent_str);
344 result.push_str(line_start);
347 if config.wrap_comments() && line.len() > max_chars {
348 let rewrite = rewrite_string(line, &fmt).unwrap_or(line.to_owned());
349 result.push_str(&rewrite);
351 if line.is_empty() && result.ends_with(' ') {
352 // Remove space if this is an empty comment or a doc comment.
355 result.push_str(line);
359 result.push_str(closer);
360 if result == opener && result.ends_with(' ') {
368 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
369 fn light_rewrite_comment(orig: &str, offset: Indent, config: &Config) -> Option<String> {
370 let lines: Vec<&str> = orig.lines()
372 // This is basically just l.trim(), but in the case that a line starts
373 // with `*` we want to leave one space before it, so it aligns with the
375 let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
376 if let Some(fnw) = first_non_whitespace {
377 if l.as_bytes()[fnw] == '*' as u8 && fnw > 0 {
387 Some(lines.join(&format!("\n{}", offset.to_string(config))))
390 /// Trims comment characters and possibly a single space from the left of a string.
391 /// Does not trim all whitespace.
392 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle) -> &'a str {
393 if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") ||
394 line.starts_with("/** ")
397 } else if let &CommentStyle::Custom(opener) = style {
398 if line.starts_with(opener) {
399 &line[opener.len()..]
401 &line[opener.trim_right().len()..]
403 } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!") ||
404 line.starts_with("///") || line.starts_with("** ") ||
405 line.starts_with("/*!") ||
406 (line.starts_with("/**") && !line.starts_with("/**/"))
409 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") ||
410 line.starts_with("**")
413 } else if line.starts_with('*') {
420 pub trait FindUncommented {
421 fn find_uncommented(&self, pat: &str) -> Option<usize>;
424 impl FindUncommented for str {
425 fn find_uncommented(&self, pat: &str) -> Option<usize> {
426 let mut needle_iter = pat.chars();
427 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
428 match needle_iter.next() {
430 return Some(i - pat.len());
432 Some(c) => match kind {
433 FullCodeCharKind::Normal if b == c => {}
435 needle_iter = pat.chars();
441 // Handle case where the pattern is a suffix of the search string
442 match needle_iter.next() {
444 None => Some(self.len() - pat.len()),
449 // Returns the first byte position after the first comment. The given string
450 // is expected to be prefixed by a comment, including delimiters.
451 // Good: "/* /* inner */ outer */ code();"
452 // Bad: "code(); // hello\n world!"
453 pub fn find_comment_end(s: &str) -> Option<usize> {
454 let mut iter = CharClasses::new(s.char_indices());
455 for (kind, (i, _c)) in &mut iter {
456 if kind == FullCodeCharKind::Normal {
461 // Handle case where the comment ends at the end of s.
462 if iter.status == CharClassesStatus::Normal {
469 /// Returns true if text contains any comment.
470 pub fn contains_comment(text: &str) -> bool {
471 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
474 struct CharClasses<T>
479 base: iter::Peekable<T>,
480 status: CharClassesStatus,
484 fn get_char(&self) -> char;
487 impl RichChar for char {
488 fn get_char(&self) -> char {
493 impl RichChar for (usize, char) {
494 fn get_char(&self) -> char {
499 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
500 enum CharClassesStatus {
506 // The u32 is the nesting deepness of the comment
508 // Status when the '/' has been consumed, but not yet the '*', deepness is
509 // the new deepness (after the comment opening).
510 BlockCommentOpening(u32),
511 // Status when the '*' has been consumed, but not yet the '/', deepness is
512 // the new deepness (after the comment closing).
513 BlockCommentClosing(u32),
517 /// Distinguish between functional part of code and comments
518 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
519 pub enum CodeCharKind {
524 /// Distinguish between functional part of code and comments,
525 /// describing opening and closing of comments for ease when chunking
526 /// code from tagged characters
527 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
528 enum FullCodeCharKind {
530 /// The first character of a comment, there is only one for a comment (always '/')
532 /// Any character inside a comment including the second character of comment
533 /// marks ("//", "/*")
535 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
539 impl FullCodeCharKind {
540 fn is_comment(&self) -> bool {
542 FullCodeCharKind::Normal => false,
543 FullCodeCharKind::StartComment |
544 FullCodeCharKind::InComment |
545 FullCodeCharKind::EndComment => true,
549 fn to_codecharkind(&self) -> CodeCharKind {
550 if self.is_comment() {
551 CodeCharKind::Comment
558 impl<T> CharClasses<T>
563 fn new(base: T) -> CharClasses<T> {
565 base: base.peekable(),
566 status: CharClassesStatus::Normal,
571 impl<T> Iterator for CharClasses<T>
576 type Item = (FullCodeCharKind, T::Item);
578 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
579 let item = try_opt!(self.base.next());
580 let chr = item.get_char();
581 self.status = match self.status {
582 CharClassesStatus::LitString => match chr {
583 '"' => CharClassesStatus::Normal,
584 '\\' => CharClassesStatus::LitStringEscape,
585 _ => CharClassesStatus::LitString,
587 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
588 CharClassesStatus::LitChar => match chr {
589 '\\' => CharClassesStatus::LitCharEscape,
590 '\'' => CharClassesStatus::Normal,
591 _ => CharClassesStatus::LitChar,
593 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
594 CharClassesStatus::Normal => match chr {
595 '"' => CharClassesStatus::LitString,
596 '\'' => CharClassesStatus::LitChar,
597 '/' => match self.base.peek() {
598 Some(next) if next.get_char() == '*' => {
599 self.status = CharClassesStatus::BlockCommentOpening(1);
600 return Some((FullCodeCharKind::StartComment, item));
602 Some(next) if next.get_char() == '/' => {
603 self.status = CharClassesStatus::LineComment;
604 return Some((FullCodeCharKind::StartComment, item));
606 _ => CharClassesStatus::Normal,
608 _ => CharClassesStatus::Normal,
610 CharClassesStatus::BlockComment(deepness) => {
611 assert!(deepness != 0);
612 self.status = match self.base.peek() {
613 Some(next) if next.get_char() == '/' && chr == '*' => {
614 CharClassesStatus::BlockCommentClosing(deepness - 1)
616 Some(next) if next.get_char() == '*' && chr == '/' => {
617 CharClassesStatus::BlockCommentOpening(deepness + 1)
619 _ => CharClassesStatus::BlockComment(deepness),
621 return Some((FullCodeCharKind::InComment, item));
623 CharClassesStatus::BlockCommentOpening(deepness) => {
624 assert_eq!(chr, '*');
625 self.status = CharClassesStatus::BlockComment(deepness);
626 return Some((FullCodeCharKind::InComment, item));
628 CharClassesStatus::BlockCommentClosing(deepness) => {
629 assert_eq!(chr, '/');
631 self.status = CharClassesStatus::Normal;
632 return Some((FullCodeCharKind::EndComment, item));
634 self.status = CharClassesStatus::BlockComment(deepness);
635 return Some((FullCodeCharKind::InComment, item));
638 CharClassesStatus::LineComment => match chr {
640 self.status = CharClassesStatus::Normal;
641 return Some((FullCodeCharKind::EndComment, item));
644 self.status = CharClassesStatus::LineComment;
645 return Some((FullCodeCharKind::InComment, item));
649 Some((FullCodeCharKind::Normal, item))
653 /// Iterator over functional and commented parts of a string. Any part of a string is either
654 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
655 /// comments is functional code. Line comments contain their ending newlines.
656 struct UngroupedCommentCodeSlices<'a> {
658 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
661 impl<'a> UngroupedCommentCodeSlices<'a> {
662 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
663 UngroupedCommentCodeSlices {
665 iter: CharClasses::new(code.char_indices()).peekable(),
670 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
671 type Item = (CodeCharKind, usize, &'a str);
673 fn next(&mut self) -> Option<Self::Item> {
674 let (kind, (start_idx, _)) = try_opt!(self.iter.next());
676 FullCodeCharKind::Normal => {
677 // Consume all the Normal code
678 while let Some(&(FullCodeCharKind::Normal, (_, _))) = self.iter.peek() {
679 let _ = self.iter.next();
682 FullCodeCharKind::StartComment => {
683 // Consume the whole comment
684 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
688 let slice = match self.iter.peek() {
689 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
690 None => &self.slice[start_idx..],
693 if kind.is_comment() {
694 CodeCharKind::Comment
707 /// Iterator over an alternating sequence of functional and commented parts of
708 /// a string. The first item is always a, possibly zero length, subslice of
709 /// functional text. Line style comments contain their ending newlines.
710 pub struct CommentCodeSlices<'a> {
712 last_slice_kind: CodeCharKind,
713 last_slice_end: usize,
716 impl<'a> CommentCodeSlices<'a> {
717 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
720 last_slice_kind: CodeCharKind::Comment,
726 impl<'a> Iterator for CommentCodeSlices<'a> {
727 type Item = (CodeCharKind, usize, &'a str);
729 fn next(&mut self) -> Option<Self::Item> {
730 if self.last_slice_end == self.slice.len() {
734 let mut sub_slice_end = self.last_slice_end;
735 let mut first_whitespace = None;
736 let subslice = &self.slice[self.last_slice_end..];
737 let mut iter = CharClasses::new(subslice.char_indices());
739 for (kind, (i, c)) in &mut iter {
740 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
741 &subslice[..2] == "//" &&
742 [' ', '\t'].contains(&c);
744 if is_comment_connector && first_whitespace.is_none() {
745 first_whitespace = Some(i);
748 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
749 let last_index = match first_whitespace {
753 sub_slice_end = self.last_slice_end + last_index;
757 if !is_comment_connector {
758 first_whitespace = None;
762 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
763 // This was the last subslice.
764 sub_slice_end = match first_whitespace {
765 Some(i) => self.last_slice_end + i,
766 None => self.slice.len(),
770 let kind = match self.last_slice_kind {
771 CodeCharKind::Comment => CodeCharKind::Normal,
772 CodeCharKind::Normal => CodeCharKind::Comment,
777 &self.slice[self.last_slice_end..sub_slice_end],
779 self.last_slice_end = sub_slice_end;
780 self.last_slice_kind = kind;
786 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
787 /// (if it fits in the width/offset, else return None), else return `new`
788 pub fn recover_comment_removed(
791 context: &RewriteContext,
793 ) -> Option<String> {
794 let snippet = context.snippet(span);
795 if changed_comment_content(&snippet, &new) {
796 // We missed some comments
797 // Keep previous formatting if it satisfies the constrains
798 wrap_str(snippet, context.config.max_width(), shape)
804 /// Return true if the two strings of code have the same payload of comments.
805 /// The payload of comments is everything in the string except:
806 /// - actual code (not comments)
807 /// - comment start/end marks
809 /// - '*' at the beginning of lines in block comments
810 fn changed_comment_content(orig: &str, new: &str) -> bool {
811 // Cannot write this as a fn since we cannot return types containing closures
812 let code_comment_content = |code| {
813 let slices = UngroupedCommentCodeSlices::new(code);
815 .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
816 .flat_map(|(_, _, s)| CommentReducer::new(s))
818 let res = code_comment_content(orig).ne(code_comment_content(new));
820 "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
824 code_comment_content(orig).collect::<String>(),
825 code_comment_content(new).collect::<String>()
831 /// Iterator over the 'payload' characters of a comment.
832 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
833 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
835 struct CommentReducer<'a> {
838 iter: std::str::Chars<'a>,
841 impl<'a> CommentReducer<'a> {
842 fn new(comment: &'a str) -> CommentReducer<'a> {
843 let is_block = comment.starts_with("/*");
844 let comment = remove_comment_header(comment);
847 at_start_line: false, // There are no supplementary '*' on the first line
848 iter: comment.chars(),
853 impl<'a> Iterator for CommentReducer<'a> {
855 fn next(&mut self) -> Option<Self::Item> {
857 let mut c = try_opt!(self.iter.next());
858 if self.is_block && self.at_start_line {
859 while c.is_whitespace() {
860 c = try_opt!(self.iter.next());
862 // Ignore leading '*'
864 c = try_opt!(self.iter.next());
868 self.at_start_line = true;
871 if !c.is_whitespace() {
879 fn remove_comment_header(comment: &str) -> &str {
880 if comment.starts_with("///") || comment.starts_with("//!") {
882 } else if comment.starts_with("//") {
884 } else if (comment.starts_with("/**") && !comment.starts_with("/**/")) ||
885 comment.starts_with("/*!")
887 &comment[3..comment.len() - 2]
890 comment.starts_with("/*"),
891 format!("string '{}' is not a comment", comment)
893 &comment[2..comment.len() - 2]
899 use super::{contains_comment, rewrite_comment, CharClasses, CodeCharKind, CommentCodeSlices,
900 FindUncommented, FullCodeCharKind};
905 let mut iter = CharClasses::new("//\n\n".chars());
907 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
908 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
909 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
910 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
911 assert_eq!(None, iter.next());
915 fn comment_code_slices() {
916 let input = "code(); /* test */ 1 + 1";
917 let mut iter = CommentCodeSlices::new(input);
919 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
921 (CodeCharKind::Comment, 8, "/* test */"),
924 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
925 assert_eq!(None, iter.next());
929 fn comment_code_slices_two() {
930 let input = "// comment\n test();";
931 let mut iter = CommentCodeSlices::new(input);
933 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
935 (CodeCharKind::Comment, 0, "// comment\n"),
939 (CodeCharKind::Normal, 11, " test();"),
942 assert_eq!(None, iter.next());
946 fn comment_code_slices_three() {
947 let input = "1 // comment\n // comment2\n\n";
948 let mut iter = CommentCodeSlices::new(input);
950 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
952 (CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
955 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
956 assert_eq!(None, iter.next());
960 #[cfg_attr(rustfmt, rustfmt_skip)]
961 fn format_comments() {
962 let mut config: ::config::Config = Default::default();
963 config.set().wrap_comments(true);
964 config.set().normalize_comments(true);
966 let comment = rewrite_comment(" //test",
968 Shape::legacy(100, Indent::new(0, 100)),
970 assert_eq!("/* test */", comment);
972 let comment = rewrite_comment("// comment on a",
974 Shape::legacy(10, Indent::empty()),
976 assert_eq!("// comment\n// on a", comment);
978 let comment = rewrite_comment("// A multi line comment\n // between args.",
980 Shape::legacy(60, Indent::new(0, 12)),
982 assert_eq!("// A multi line comment\n // between args.", comment);
984 let input = "// comment";
987 let comment = rewrite_comment(input,
989 Shape::legacy(9, Indent::new(0, 69)),
991 assert_eq!(expected, comment);
993 let comment = rewrite_comment("/* trimmed */",
995 Shape::legacy(100, Indent::new(0, 100)),
997 assert_eq!("/* trimmed */", comment);
1000 // This is probably intended to be a non-test fn, but it is not used. I'm
1001 // keeping it around unless it helps us test stuff.
1002 fn uncommented(text: &str) -> String {
1003 CharClasses::new(text.chars())
1004 .filter_map(|(s, c)| match s {
1005 FullCodeCharKind::Normal => Some(c),
1012 fn test_uncommented() {
1013 assert_eq!(&uncommented("abc/*...*/"), "abc");
1015 &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
1018 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
1022 fn test_contains_comment() {
1023 assert_eq!(contains_comment("abc"), false);
1024 assert_eq!(contains_comment("abc // qsdf"), true);
1025 assert_eq!(contains_comment("abc /* kqsdf"), true);
1026 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
1030 fn test_find_uncommented() {
1031 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
1032 assert_eq!(expected, haystack.find_uncommented(needle));
1035 check("/*/ */test", "test", Some(6));
1036 check("//test\ntest", "test", Some(7));
1037 check("/* comment only */", "whatever", None);
1039 "/* comment */ some text /* more commentary */ result",
1043 check("sup // sup", "p", Some(2));
1044 check("sup", "x", None);
1045 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
1046 check("/*sup yo? \n sup*/ sup", "p", Some(20));
1047 check("hel/*lohello*/lo", "hello", None);
1048 check("acb", "ab", None);
1049 check(",/*A*/ ", ",", Some(0));
1050 check("abc", "abc", Some(0));
1051 check("/* abc */", "abc", None);
1052 check("/**/abc/* */", "abc", Some(4));
1053 check("\"/* abc */\"", "abc", Some(4));
1054 check("\"/* abc", "abc", Some(4));