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 /// Given the span, rewrite the missing comment inside it if available.
369 /// Note that the given span must only include comments (or leading/trailing whitespaces).
370 pub fn rewrite_missing_comment(
373 context: &RewriteContext,
374 ) -> Option<String> {
375 let missing_snippet = context.snippet(span);
376 let trimmed_snippet = missing_snippet.trim();
377 if !trimmed_snippet.is_empty() {
378 rewrite_comment(trimmed_snippet, false, shape, context.config)
384 /// Recover the missing comments in the specified span, if available.
385 /// The layout of the comments will be preserved as long as it does not break the code
386 /// and its total width does not exceed the max width.
387 pub fn recover_missing_comment_in_span(
390 context: &RewriteContext,
392 ) -> Option<String> {
393 let missing_comment = try_opt!(rewrite_missing_comment(span, shape, context));
394 if missing_comment.is_empty() {
397 let missing_snippet = context.snippet(span);
398 let pos = missing_snippet.chars().position(|c| c == '/').unwrap_or(0);
400 let total_width = missing_comment.len() + used_width + 1;
401 let force_new_line_before_comment =
402 missing_snippet[..pos].contains('\n') || total_width > context.config.max_width();
403 let sep = if force_new_line_before_comment {
404 format!("\n{}", shape.indent.to_string(context.config))
408 Some(format!("{}{}", sep, missing_comment))
412 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
413 fn light_rewrite_comment(orig: &str, offset: Indent, config: &Config) -> Option<String> {
414 let lines: Vec<&str> = orig.lines()
416 // This is basically just l.trim(), but in the case that a line starts
417 // with `*` we want to leave one space before it, so it aligns with the
419 let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
420 if let Some(fnw) = first_non_whitespace {
421 if l.as_bytes()[fnw] == '*' as u8 && fnw > 0 {
431 Some(lines.join(&format!("\n{}", offset.to_string(config))))
434 /// Trims comment characters and possibly a single space from the left of a string.
435 /// Does not trim all whitespace.
436 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle) -> &'a str {
437 if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") ||
438 line.starts_with("/** ")
441 } else if let &CommentStyle::Custom(opener) = style {
442 if line.starts_with(opener) {
443 &line[opener.len()..]
445 &line[opener.trim_right().len()..]
447 } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!") ||
448 line.starts_with("///") || line.starts_with("** ") ||
449 line.starts_with("/*!") ||
450 (line.starts_with("/**") && !line.starts_with("/**/"))
453 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") ||
454 line.starts_with("**")
457 } else if line.starts_with('*') {
464 pub trait FindUncommented {
465 fn find_uncommented(&self, pat: &str) -> Option<usize>;
468 impl FindUncommented for str {
469 fn find_uncommented(&self, pat: &str) -> Option<usize> {
470 let mut needle_iter = pat.chars();
471 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
472 match needle_iter.next() {
474 return Some(i - pat.len());
476 Some(c) => match kind {
477 FullCodeCharKind::Normal if b == c => {}
479 needle_iter = pat.chars();
485 // Handle case where the pattern is a suffix of the search string
486 match needle_iter.next() {
488 None => Some(self.len() - pat.len()),
493 // Returns the first byte position after the first comment. The given string
494 // is expected to be prefixed by a comment, including delimiters.
495 // Good: "/* /* inner */ outer */ code();"
496 // Bad: "code(); // hello\n world!"
497 pub fn find_comment_end(s: &str) -> Option<usize> {
498 let mut iter = CharClasses::new(s.char_indices());
499 for (kind, (i, _c)) in &mut iter {
500 if kind == FullCodeCharKind::Normal {
505 // Handle case where the comment ends at the end of s.
506 if iter.status == CharClassesStatus::Normal {
513 /// Returns true if text contains any comment.
514 pub fn contains_comment(text: &str) -> bool {
515 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
518 struct CharClasses<T>
523 base: iter::Peekable<T>,
524 status: CharClassesStatus,
528 fn get_char(&self) -> char;
531 impl RichChar for char {
532 fn get_char(&self) -> char {
537 impl RichChar for (usize, char) {
538 fn get_char(&self) -> char {
543 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
544 enum CharClassesStatus {
550 // The u32 is the nesting deepness of the comment
552 // Status when the '/' has been consumed, but not yet the '*', deepness is
553 // the new deepness (after the comment opening).
554 BlockCommentOpening(u32),
555 // Status when the '*' has been consumed, but not yet the '/', deepness is
556 // the new deepness (after the comment closing).
557 BlockCommentClosing(u32),
561 /// Distinguish between functional part of code and comments
562 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
563 pub enum CodeCharKind {
568 /// Distinguish between functional part of code and comments,
569 /// describing opening and closing of comments for ease when chunking
570 /// code from tagged characters
571 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
572 enum FullCodeCharKind {
574 /// The first character of a comment, there is only one for a comment (always '/')
576 /// Any character inside a comment including the second character of comment
577 /// marks ("//", "/*")
579 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
583 impl FullCodeCharKind {
584 fn is_comment(&self) -> bool {
586 FullCodeCharKind::Normal => false,
587 FullCodeCharKind::StartComment |
588 FullCodeCharKind::InComment |
589 FullCodeCharKind::EndComment => true,
593 fn to_codecharkind(&self) -> CodeCharKind {
594 if self.is_comment() {
595 CodeCharKind::Comment
602 impl<T> CharClasses<T>
607 fn new(base: T) -> CharClasses<T> {
609 base: base.peekable(),
610 status: CharClassesStatus::Normal,
615 impl<T> Iterator for CharClasses<T>
620 type Item = (FullCodeCharKind, T::Item);
622 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
623 let item = try_opt!(self.base.next());
624 let chr = item.get_char();
625 self.status = match self.status {
626 CharClassesStatus::LitString => match chr {
627 '"' => CharClassesStatus::Normal,
628 '\\' => CharClassesStatus::LitStringEscape,
629 _ => CharClassesStatus::LitString,
631 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
632 CharClassesStatus::LitChar => match chr {
633 '\\' => CharClassesStatus::LitCharEscape,
634 '\'' => CharClassesStatus::Normal,
635 _ => CharClassesStatus::LitChar,
637 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
638 CharClassesStatus::Normal => match chr {
639 '"' => CharClassesStatus::LitString,
640 '\'' => CharClassesStatus::LitChar,
641 '/' => match self.base.peek() {
642 Some(next) if next.get_char() == '*' => {
643 self.status = CharClassesStatus::BlockCommentOpening(1);
644 return Some((FullCodeCharKind::StartComment, item));
646 Some(next) if next.get_char() == '/' => {
647 self.status = CharClassesStatus::LineComment;
648 return Some((FullCodeCharKind::StartComment, item));
650 _ => CharClassesStatus::Normal,
652 _ => CharClassesStatus::Normal,
654 CharClassesStatus::BlockComment(deepness) => {
655 assert!(deepness != 0);
656 self.status = match self.base.peek() {
657 Some(next) if next.get_char() == '/' && chr == '*' => {
658 CharClassesStatus::BlockCommentClosing(deepness - 1)
660 Some(next) if next.get_char() == '*' && chr == '/' => {
661 CharClassesStatus::BlockCommentOpening(deepness + 1)
663 _ => CharClassesStatus::BlockComment(deepness),
665 return Some((FullCodeCharKind::InComment, item));
667 CharClassesStatus::BlockCommentOpening(deepness) => {
668 assert_eq!(chr, '*');
669 self.status = CharClassesStatus::BlockComment(deepness);
670 return Some((FullCodeCharKind::InComment, item));
672 CharClassesStatus::BlockCommentClosing(deepness) => {
673 assert_eq!(chr, '/');
675 self.status = CharClassesStatus::Normal;
676 return Some((FullCodeCharKind::EndComment, item));
678 self.status = CharClassesStatus::BlockComment(deepness);
679 return Some((FullCodeCharKind::InComment, item));
682 CharClassesStatus::LineComment => match chr {
684 self.status = CharClassesStatus::Normal;
685 return Some((FullCodeCharKind::EndComment, item));
688 self.status = CharClassesStatus::LineComment;
689 return Some((FullCodeCharKind::InComment, item));
693 Some((FullCodeCharKind::Normal, item))
697 /// Iterator over functional and commented parts of a string. Any part of a string is either
698 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
699 /// comments is functional code. Line comments contain their ending newlines.
700 struct UngroupedCommentCodeSlices<'a> {
702 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
705 impl<'a> UngroupedCommentCodeSlices<'a> {
706 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
707 UngroupedCommentCodeSlices {
709 iter: CharClasses::new(code.char_indices()).peekable(),
714 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
715 type Item = (CodeCharKind, usize, &'a str);
717 fn next(&mut self) -> Option<Self::Item> {
718 let (kind, (start_idx, _)) = try_opt!(self.iter.next());
720 FullCodeCharKind::Normal => {
721 // Consume all the Normal code
722 while let Some(&(FullCodeCharKind::Normal, (_, _))) = self.iter.peek() {
723 let _ = self.iter.next();
726 FullCodeCharKind::StartComment => {
727 // Consume the whole comment
728 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
732 let slice = match self.iter.peek() {
733 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
734 None => &self.slice[start_idx..],
737 if kind.is_comment() {
738 CodeCharKind::Comment
751 /// Iterator over an alternating sequence of functional and commented parts of
752 /// a string. The first item is always a, possibly zero length, subslice of
753 /// functional text. Line style comments contain their ending newlines.
754 pub struct CommentCodeSlices<'a> {
756 last_slice_kind: CodeCharKind,
757 last_slice_end: usize,
760 impl<'a> CommentCodeSlices<'a> {
761 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
764 last_slice_kind: CodeCharKind::Comment,
770 impl<'a> Iterator for CommentCodeSlices<'a> {
771 type Item = (CodeCharKind, usize, &'a str);
773 fn next(&mut self) -> Option<Self::Item> {
774 if self.last_slice_end == self.slice.len() {
778 let mut sub_slice_end = self.last_slice_end;
779 let mut first_whitespace = None;
780 let subslice = &self.slice[self.last_slice_end..];
781 let mut iter = CharClasses::new(subslice.char_indices());
783 for (kind, (i, c)) in &mut iter {
784 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
785 &subslice[..2] == "//" &&
786 [' ', '\t'].contains(&c);
788 if is_comment_connector && first_whitespace.is_none() {
789 first_whitespace = Some(i);
792 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
793 let last_index = match first_whitespace {
797 sub_slice_end = self.last_slice_end + last_index;
801 if !is_comment_connector {
802 first_whitespace = None;
806 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
807 // This was the last subslice.
808 sub_slice_end = match first_whitespace {
809 Some(i) => self.last_slice_end + i,
810 None => self.slice.len(),
814 let kind = match self.last_slice_kind {
815 CodeCharKind::Comment => CodeCharKind::Normal,
816 CodeCharKind::Normal => CodeCharKind::Comment,
821 &self.slice[self.last_slice_end..sub_slice_end],
823 self.last_slice_end = sub_slice_end;
824 self.last_slice_kind = kind;
830 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
831 /// (if it fits in the width/offset, else return None), else return `new`
832 pub fn recover_comment_removed(
835 context: &RewriteContext,
837 ) -> Option<String> {
838 let snippet = context.snippet(span);
839 if changed_comment_content(&snippet, &new) {
840 // We missed some comments
841 // Keep previous formatting if it satisfies the constrains
842 wrap_str(snippet, context.config.max_width(), shape)
848 /// Return true if the two strings of code have the same payload of comments.
849 /// The payload of comments is everything in the string except:
850 /// - actual code (not comments)
851 /// - comment start/end marks
853 /// - '*' at the beginning of lines in block comments
854 fn changed_comment_content(orig: &str, new: &str) -> bool {
855 // Cannot write this as a fn since we cannot return types containing closures
856 let code_comment_content = |code| {
857 let slices = UngroupedCommentCodeSlices::new(code);
859 .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
860 .flat_map(|(_, _, s)| CommentReducer::new(s))
862 let res = code_comment_content(orig).ne(code_comment_content(new));
864 "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
868 code_comment_content(orig).collect::<String>(),
869 code_comment_content(new).collect::<String>()
875 /// Iterator over the 'payload' characters of a comment.
876 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
877 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
879 struct CommentReducer<'a> {
882 iter: std::str::Chars<'a>,
885 impl<'a> CommentReducer<'a> {
886 fn new(comment: &'a str) -> CommentReducer<'a> {
887 let is_block = comment.starts_with("/*");
888 let comment = remove_comment_header(comment);
891 at_start_line: false, // There are no supplementary '*' on the first line
892 iter: comment.chars(),
897 impl<'a> Iterator for CommentReducer<'a> {
899 fn next(&mut self) -> Option<Self::Item> {
901 let mut c = try_opt!(self.iter.next());
902 if self.is_block && self.at_start_line {
903 while c.is_whitespace() {
904 c = try_opt!(self.iter.next());
906 // Ignore leading '*'
908 c = try_opt!(self.iter.next());
912 self.at_start_line = true;
915 if !c.is_whitespace() {
923 fn remove_comment_header(comment: &str) -> &str {
924 if comment.starts_with("///") || comment.starts_with("//!") {
926 } else if comment.starts_with("//") {
928 } else if (comment.starts_with("/**") && !comment.starts_with("/**/")) ||
929 comment.starts_with("/*!")
931 &comment[3..comment.len() - 2]
934 comment.starts_with("/*"),
935 format!("string '{}' is not a comment", comment)
937 &comment[2..comment.len() - 2]
943 use super::{contains_comment, rewrite_comment, CharClasses, CodeCharKind, CommentCodeSlices,
944 FindUncommented, FullCodeCharKind};
949 let mut iter = CharClasses::new("//\n\n".chars());
951 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
952 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
953 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
954 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
955 assert_eq!(None, iter.next());
959 fn comment_code_slices() {
960 let input = "code(); /* test */ 1 + 1";
961 let mut iter = CommentCodeSlices::new(input);
963 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
965 (CodeCharKind::Comment, 8, "/* test */"),
968 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
969 assert_eq!(None, iter.next());
973 fn comment_code_slices_two() {
974 let input = "// comment\n test();";
975 let mut iter = CommentCodeSlices::new(input);
977 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
979 (CodeCharKind::Comment, 0, "// comment\n"),
983 (CodeCharKind::Normal, 11, " test();"),
986 assert_eq!(None, iter.next());
990 fn comment_code_slices_three() {
991 let input = "1 // comment\n // comment2\n\n";
992 let mut iter = CommentCodeSlices::new(input);
994 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
996 (CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
999 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
1000 assert_eq!(None, iter.next());
1004 #[cfg_attr(rustfmt, rustfmt_skip)]
1005 fn format_comments() {
1006 let mut config: ::config::Config = Default::default();
1007 config.set().wrap_comments(true);
1008 config.set().normalize_comments(true);
1010 let comment = rewrite_comment(" //test",
1012 Shape::legacy(100, Indent::new(0, 100)),
1014 assert_eq!("/* test */", comment);
1016 let comment = rewrite_comment("// comment on a",
1018 Shape::legacy(10, Indent::empty()),
1020 assert_eq!("// comment\n// on a", comment);
1022 let comment = rewrite_comment("// A multi line comment\n // between args.",
1024 Shape::legacy(60, Indent::new(0, 12)),
1026 assert_eq!("// A multi line comment\n // between args.", comment);
1028 let input = "// comment";
1031 let comment = rewrite_comment(input,
1033 Shape::legacy(9, Indent::new(0, 69)),
1035 assert_eq!(expected, comment);
1037 let comment = rewrite_comment("/* trimmed */",
1039 Shape::legacy(100, Indent::new(0, 100)),
1041 assert_eq!("/* trimmed */", comment);
1044 // This is probably intended to be a non-test fn, but it is not used. I'm
1045 // keeping it around unless it helps us test stuff.
1046 fn uncommented(text: &str) -> String {
1047 CharClasses::new(text.chars())
1048 .filter_map(|(s, c)| match s {
1049 FullCodeCharKind::Normal => Some(c),
1056 fn test_uncommented() {
1057 assert_eq!(&uncommented("abc/*...*/"), "abc");
1059 &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
1062 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
1066 fn test_contains_comment() {
1067 assert_eq!(contains_comment("abc"), false);
1068 assert_eq!(contains_comment("abc // qsdf"), true);
1069 assert_eq!(contains_comment("abc /* kqsdf"), true);
1070 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
1074 fn test_find_uncommented() {
1075 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
1076 assert_eq!(expected, haystack.find_uncommented(needle));
1079 check("/*/ */test", "test", Some(6));
1080 check("//test\ntest", "test", Some(7));
1081 check("/* comment only */", "whatever", None);
1083 "/* comment */ some text /* more commentary */ result",
1087 check("sup // sup", "p", Some(2));
1088 check("sup", "x", None);
1089 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
1090 check("/*sup yo? \n sup*/ sup", "p", Some(20));
1091 check("hel/*lohello*/lo", "hello", None);
1092 check("acb", "ab", None);
1093 check(",/*A*/ ", ",", Some(0));
1094 check("abc", "abc", Some(0));
1095 check("/* abc */", "abc", None);
1096 check("/**/abc/* */", "abc", Some(4));
1097 check("\"/* abc */\"", "abc", Some(4));
1098 check("\"/* abc", "abc", Some(4));