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("//") {
26 } else if let Some(c) = comment.chars().nth(2) {
27 !c.is_alphanumeric() && !c.is_whitespace()
33 #[derive(Copy, Clone, PartialEq, Eq)]
34 pub enum CommentStyle<'a> {
44 fn custom_opener(s: &str) -> &str {
45 s.lines().next().map_or("", |first_line| {
48 .map_or(first_line, |space_index| &first_line[0..space_index + 1])
52 impl<'a> CommentStyle<'a> {
53 pub fn opener(&self) -> &'a str {
55 CommentStyle::DoubleSlash => "// ",
56 CommentStyle::TripleSlash => "/// ",
57 CommentStyle::Doc => "//! ",
58 CommentStyle::SingleBullet => "/* ",
59 CommentStyle::DoubleBullet => "/** ",
60 CommentStyle::Exclamation => "/*! ",
61 CommentStyle::Custom(opener) => opener,
65 pub fn closer(&self) -> &'a str {
67 CommentStyle::DoubleSlash |
68 CommentStyle::TripleSlash |
69 CommentStyle::Custom(..) |
70 CommentStyle::Doc => "",
71 CommentStyle::DoubleBullet => " **/",
72 CommentStyle::SingleBullet | CommentStyle::Exclamation => " */",
76 pub fn line_start(&self) -> &'a str {
78 CommentStyle::DoubleSlash => "// ",
79 CommentStyle::TripleSlash => "/// ",
80 CommentStyle::Doc => "//! ",
81 CommentStyle::SingleBullet | CommentStyle::Exclamation => " * ",
82 CommentStyle::DoubleBullet => " ** ",
83 CommentStyle::Custom(opener) => opener,
87 pub fn to_str_tuplet(&self) -> (&'a str, &'a str, &'a str) {
88 (self.opener(), self.closer(), self.line_start())
91 pub fn line_with_same_comment_style(&self, line: &str, normalize_comments: bool) -> bool {
93 CommentStyle::DoubleSlash | CommentStyle::TripleSlash | CommentStyle::Doc => {
94 line.trim_left().starts_with(self.line_start().trim_left()) ||
95 comment_style(line, normalize_comments) == *self
97 CommentStyle::DoubleBullet | CommentStyle::SingleBullet | CommentStyle::Exclamation => {
98 line.trim_left().starts_with(self.closer().trim_left()) ||
99 line.trim_left().starts_with(self.line_start().trim_left()) ||
100 comment_style(line, normalize_comments) == *self
102 CommentStyle::Custom(opener) => line.trim_left().starts_with(opener.trim_right()),
107 fn comment_style(orig: &str, normalize_comments: bool) -> CommentStyle {
108 if !normalize_comments {
109 if orig.starts_with("/**") && !orig.starts_with("/**/") {
110 CommentStyle::DoubleBullet
111 } else if orig.starts_with("/*!") {
112 CommentStyle::Exclamation
113 } else if orig.starts_with("/*") {
114 CommentStyle::SingleBullet
115 } else if orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/') {
116 CommentStyle::TripleSlash
117 } else if orig.starts_with("//!") {
119 } else if is_custom_comment(orig) {
120 CommentStyle::Custom(custom_opener(orig))
122 CommentStyle::DoubleSlash
124 } else if (orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/')) ||
125 (orig.starts_with("/**") && !orig.starts_with("/**/"))
127 CommentStyle::TripleSlash
128 } else if orig.starts_with("//!") || orig.starts_with("/*!") {
130 } else if is_custom_comment(orig) {
131 CommentStyle::Custom(custom_opener(orig))
133 CommentStyle::DoubleSlash
137 pub fn combine_strs_with_missing_comments(
138 context: &RewriteContext,
144 ) -> Option<String> {
145 let mut allow_one_line = !prev_str.contains('\n') && !next_str.contains('\n');
146 let first_sep = if prev_str.is_empty() || next_str.is_empty() {
151 let mut one_line_width =
152 last_line_width(prev_str) + first_line_width(next_str) + first_sep.len();
154 let indent_str = shape.indent.to_string(context.config);
155 let missing_comment = try_opt!(rewrite_missing_comment(span, shape, context));
157 if missing_comment.is_empty() {
158 if allow_extend && prev_str.len() + first_sep.len() + next_str.len() <= shape.width {
159 return Some(format!("{}{}{}", prev_str, first_sep, next_str));
161 let sep = if prev_str.is_empty() {
164 String::from("\n") + &indent_str
166 return Some(format!("{}{}{}", prev_str, sep, next_str));
170 // We have a missing comment between the first expression and the second expression.
172 // Peek the the original source code and find out whether there is a newline between the first
173 // expression and the second expression or the missing comment. We will preserve the orginal
174 // layout whenever possible.
175 let original_snippet = context.snippet(span);
176 let prefer_same_line = if let Some(pos) = original_snippet.chars().position(|c| c == '/') {
177 !original_snippet[..pos].contains('\n')
179 !original_snippet.contains('\n')
182 one_line_width -= first_sep.len();
183 let first_sep = if prev_str.is_empty() || missing_comment.is_empty() {
186 let one_line_width = last_line_width(prev_str) + first_line_width(&missing_comment) + 1;
187 if prefer_same_line && one_line_width <= shape.width {
190 format!("\n{}", indent_str)
193 let second_sep = if missing_comment.is_empty() || next_str.is_empty() {
195 } else if missing_comment.starts_with("//") {
196 format!("\n{}", indent_str)
198 one_line_width += missing_comment.len() + first_sep.len() + 1;
199 allow_one_line &= !missing_comment.starts_with("//") && !missing_comment.contains('\n');
200 if prefer_same_line && allow_one_line && one_line_width <= shape.width {
203 format!("\n{}", indent_str)
216 pub fn rewrite_comment(
221 ) -> Option<String> {
222 // If there are lines without a starting sigil, we won't format them correctly
223 // so in that case we won't even re-align (if !config.normalize_comments()) and
224 // we should stop now.
225 let num_bare_lines = orig.lines()
226 .map(|line| line.trim())
228 !(l.starts_with('*') || l.starts_with("//") || l.starts_with("/*"))
231 if num_bare_lines > 0 && !config.normalize_comments() {
232 return Some(orig.to_owned());
234 if !config.normalize_comments() && !config.wrap_comments() {
235 return light_rewrite_comment(orig, shape.indent, config);
238 identify_comment(orig, block_style, shape, config)
246 ) -> Option<String> {
247 let style = comment_style(orig, false);
248 let first_group = orig.lines()
249 .take_while(|l| style.line_with_same_comment_style(l, false))
252 let rest = orig.lines()
253 .skip(first_group.lines().count())
257 let first_group_str = try_opt!(rewrite_comment_inner(
265 Some(first_group_str)
267 identify_comment(&rest, block_style, shape, config).map(|rest_str| {
271 shape.indent.to_string(config),
278 fn rewrite_comment_inner(
284 ) -> Option<String> {
285 let (opener, closer, line_start) = if block_style {
286 CommentStyle::SingleBullet.to_str_tuplet()
288 comment_style(orig, config.normalize_comments()).to_str_tuplet()
291 let max_chars = shape
293 .checked_sub(closer.len() + opener.len())
295 let indent_str = shape.indent.to_string(config);
296 let fmt = StringFormat {
299 line_start: line_start,
301 shape: Shape::legacy(max_chars, shape.indent + (opener.len() - line_start.len())),
306 let line_breaks = orig.trim_right().chars().filter(|&c| c == '\n').count();
307 let lines = orig.lines()
309 .map(|(i, mut line)| {
312 if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
313 line = line[..(line.len() - 2)].trim_right();
318 .map(|s| left_trim_comment_line(s, &style))
319 .map(|line| if orig.starts_with("/*") && line_breaks == 0 {
325 let mut result = opener.to_owned();
327 if result == opener {
333 result.push_str(&indent_str);
334 result.push_str(line_start);
337 if config.wrap_comments() && line.len() > max_chars {
338 let rewrite = rewrite_string(line, &fmt).unwrap_or_else(|| line.to_owned());
339 result.push_str(&rewrite);
341 if line.is_empty() && result.ends_with(' ') {
342 // Remove space if this is an empty comment or a doc comment.
345 result.push_str(line);
349 result.push_str(closer);
350 if result == opener && result.ends_with(' ') {
358 /// Given the span, rewrite the missing comment inside it if available.
359 /// Note that the given span must only include comments (or leading/trailing whitespaces).
360 pub fn rewrite_missing_comment(
363 context: &RewriteContext,
364 ) -> Option<String> {
365 let missing_snippet = context.snippet(span);
366 let trimmed_snippet = missing_snippet.trim();
367 if !trimmed_snippet.is_empty() {
368 rewrite_comment(trimmed_snippet, false, shape, context.config)
374 /// Recover the missing comments in the specified span, if available.
375 /// The layout of the comments will be preserved as long as it does not break the code
376 /// and its total width does not exceed the max width.
377 pub fn recover_missing_comment_in_span(
380 context: &RewriteContext,
382 ) -> Option<String> {
383 let missing_comment = try_opt!(rewrite_missing_comment(span, shape, context));
384 if missing_comment.is_empty() {
387 let missing_snippet = context.snippet(span);
388 let pos = missing_snippet.chars().position(|c| c == '/').unwrap_or(0);
390 let total_width = missing_comment.len() + used_width + 1;
391 let force_new_line_before_comment =
392 missing_snippet[..pos].contains('\n') || total_width > context.config.max_width();
393 let sep = if force_new_line_before_comment {
394 format!("\n{}", shape.indent.to_string(context.config))
398 Some(format!("{}{}", sep, missing_comment))
402 /// Trims whitespace and aligns to indent, but otherwise does not change comments.
403 fn light_rewrite_comment(orig: &str, offset: Indent, config: &Config) -> Option<String> {
404 let lines: Vec<&str> = orig.lines()
406 // This is basically just l.trim(), but in the case that a line starts
407 // with `*` we want to leave one space before it, so it aligns with the
409 let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
410 if let Some(fnw) = first_non_whitespace {
411 if l.as_bytes()[fnw] == b'*' && fnw > 0 {
421 Some(lines.join(&format!("\n{}", offset.to_string(config))))
424 /// Trims comment characters and possibly a single space from the left of a string.
425 /// Does not trim all whitespace.
426 fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle) -> &'a str {
427 if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") ||
428 line.starts_with("/** ")
431 } else if let CommentStyle::Custom(opener) = *style {
432 if line.starts_with(opener) {
433 &line[opener.len()..]
435 &line[opener.trim_right().len()..]
437 } else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!") ||
438 line.starts_with("///") || line.starts_with("** ") ||
439 line.starts_with("/*!") ||
440 (line.starts_with("/**") && !line.starts_with("/**/"))
443 } else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//") ||
444 line.starts_with("**")
447 } else if line.starts_with('*') {
454 pub trait FindUncommented {
455 fn find_uncommented(&self, pat: &str) -> Option<usize>;
458 impl FindUncommented for str {
459 fn find_uncommented(&self, pat: &str) -> Option<usize> {
460 let mut needle_iter = pat.chars();
461 for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
462 match needle_iter.next() {
464 return Some(i - pat.len());
466 Some(c) => match kind {
467 FullCodeCharKind::Normal if b == c => {}
469 needle_iter = pat.chars();
475 // Handle case where the pattern is a suffix of the search string
476 match needle_iter.next() {
478 None => Some(self.len() - pat.len()),
483 // Returns the first byte position after the first comment. The given string
484 // is expected to be prefixed by a comment, including delimiters.
485 // Good: "/* /* inner */ outer */ code();"
486 // Bad: "code(); // hello\n world!"
487 pub fn find_comment_end(s: &str) -> Option<usize> {
488 let mut iter = CharClasses::new(s.char_indices());
489 for (kind, (i, _c)) in &mut iter {
490 if kind == FullCodeCharKind::Normal {
495 // Handle case where the comment ends at the end of s.
496 if iter.status == CharClassesStatus::Normal {
503 /// Returns true if text contains any comment.
504 pub fn contains_comment(text: &str) -> bool {
505 CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
508 struct CharClasses<T>
513 base: iter::Peekable<T>,
514 status: CharClassesStatus,
518 fn get_char(&self) -> char;
521 impl RichChar for char {
522 fn get_char(&self) -> char {
527 impl RichChar for (usize, char) {
528 fn get_char(&self) -> char {
533 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
534 enum CharClassesStatus {
540 // The u32 is the nesting deepness of the comment
542 // Status when the '/' has been consumed, but not yet the '*', deepness is
543 // the new deepness (after the comment opening).
544 BlockCommentOpening(u32),
545 // Status when the '*' has been consumed, but not yet the '/', deepness is
546 // the new deepness (after the comment closing).
547 BlockCommentClosing(u32),
551 /// Distinguish between functional part of code and comments
552 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
553 pub enum CodeCharKind {
558 /// Distinguish between functional part of code and comments,
559 /// describing opening and closing of comments for ease when chunking
560 /// code from tagged characters
561 #[derive(PartialEq, Eq, Debug, Clone, Copy)]
562 enum FullCodeCharKind {
564 /// The first character of a comment, there is only one for a comment (always '/')
566 /// Any character inside a comment including the second character of comment
567 /// marks ("//", "/*")
569 /// Last character of a comment, '\n' for a line comment, '/' for a block comment.
573 impl FullCodeCharKind {
574 fn is_comment(&self) -> bool {
576 FullCodeCharKind::Normal => false,
577 FullCodeCharKind::StartComment |
578 FullCodeCharKind::InComment |
579 FullCodeCharKind::EndComment => true,
583 fn to_codecharkind(&self) -> CodeCharKind {
584 if self.is_comment() {
585 CodeCharKind::Comment
592 impl<T> CharClasses<T>
597 fn new(base: T) -> CharClasses<T> {
599 base: base.peekable(),
600 status: CharClassesStatus::Normal,
605 impl<T> Iterator for CharClasses<T>
610 type Item = (FullCodeCharKind, T::Item);
612 fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
613 let item = try_opt!(self.base.next());
614 let chr = item.get_char();
615 self.status = match self.status {
616 CharClassesStatus::LitString => match chr {
617 '"' => CharClassesStatus::Normal,
618 '\\' => CharClassesStatus::LitStringEscape,
619 _ => CharClassesStatus::LitString,
621 CharClassesStatus::LitStringEscape => CharClassesStatus::LitString,
622 CharClassesStatus::LitChar => match chr {
623 '\\' => CharClassesStatus::LitCharEscape,
624 '\'' => CharClassesStatus::Normal,
625 _ => CharClassesStatus::LitChar,
627 CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
628 CharClassesStatus::Normal => match chr {
629 '"' => CharClassesStatus::LitString,
630 '\'' => CharClassesStatus::LitChar,
631 '/' => match self.base.peek() {
632 Some(next) if next.get_char() == '*' => {
633 self.status = CharClassesStatus::BlockCommentOpening(1);
634 return Some((FullCodeCharKind::StartComment, item));
636 Some(next) if next.get_char() == '/' => {
637 self.status = CharClassesStatus::LineComment;
638 return Some((FullCodeCharKind::StartComment, item));
640 _ => CharClassesStatus::Normal,
642 _ => CharClassesStatus::Normal,
644 CharClassesStatus::BlockComment(deepness) => {
645 assert_ne!(deepness, 0);
646 self.status = match self.base.peek() {
647 Some(next) if next.get_char() == '/' && chr == '*' => {
648 CharClassesStatus::BlockCommentClosing(deepness - 1)
650 Some(next) if next.get_char() == '*' && chr == '/' => {
651 CharClassesStatus::BlockCommentOpening(deepness + 1)
653 _ => CharClassesStatus::BlockComment(deepness),
655 return Some((FullCodeCharKind::InComment, item));
657 CharClassesStatus::BlockCommentOpening(deepness) => {
658 assert_eq!(chr, '*');
659 self.status = CharClassesStatus::BlockComment(deepness);
660 return Some((FullCodeCharKind::InComment, item));
662 CharClassesStatus::BlockCommentClosing(deepness) => {
663 assert_eq!(chr, '/');
665 self.status = CharClassesStatus::Normal;
666 return Some((FullCodeCharKind::EndComment, item));
668 self.status = CharClassesStatus::BlockComment(deepness);
669 return Some((FullCodeCharKind::InComment, item));
672 CharClassesStatus::LineComment => match chr {
674 self.status = CharClassesStatus::Normal;
675 return Some((FullCodeCharKind::EndComment, item));
678 self.status = CharClassesStatus::LineComment;
679 return Some((FullCodeCharKind::InComment, item));
683 Some((FullCodeCharKind::Normal, item))
687 /// Iterator over functional and commented parts of a string. Any part of a string is either
688 /// functional code, either *one* block comment, either *one* line comment. Whitespace between
689 /// comments is functional code. Line comments contain their ending newlines.
690 struct UngroupedCommentCodeSlices<'a> {
692 iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
695 impl<'a> UngroupedCommentCodeSlices<'a> {
696 fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
697 UngroupedCommentCodeSlices {
699 iter: CharClasses::new(code.char_indices()).peekable(),
704 impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
705 type Item = (CodeCharKind, usize, &'a str);
707 fn next(&mut self) -> Option<Self::Item> {
708 let (kind, (start_idx, _)) = try_opt!(self.iter.next());
710 FullCodeCharKind::Normal => {
711 // Consume all the Normal code
712 while let Some(&(FullCodeCharKind::Normal, (_, _))) = self.iter.peek() {
713 let _ = self.iter.next();
716 FullCodeCharKind::StartComment => {
717 // Consume the whole comment
718 while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
722 let slice = match self.iter.peek() {
723 Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
724 None => &self.slice[start_idx..],
727 if kind.is_comment() {
728 CodeCharKind::Comment
741 /// Iterator over an alternating sequence of functional and commented parts of
742 /// a string. The first item is always a, possibly zero length, subslice of
743 /// functional text. Line style comments contain their ending newlines.
744 pub struct CommentCodeSlices<'a> {
746 last_slice_kind: CodeCharKind,
747 last_slice_end: usize,
750 impl<'a> CommentCodeSlices<'a> {
751 pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
754 last_slice_kind: CodeCharKind::Comment,
760 impl<'a> Iterator for CommentCodeSlices<'a> {
761 type Item = (CodeCharKind, usize, &'a str);
763 fn next(&mut self) -> Option<Self::Item> {
764 if self.last_slice_end == self.slice.len() {
768 let mut sub_slice_end = self.last_slice_end;
769 let mut first_whitespace = None;
770 let subslice = &self.slice[self.last_slice_end..];
771 let mut iter = CharClasses::new(subslice.char_indices());
773 for (kind, (i, c)) in &mut iter {
774 let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal &&
775 &subslice[..2] == "//" &&
776 [' ', '\t'].contains(&c);
778 if is_comment_connector && first_whitespace.is_none() {
779 first_whitespace = Some(i);
782 if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
783 let last_index = match first_whitespace {
787 sub_slice_end = self.last_slice_end + last_index;
791 if !is_comment_connector {
792 first_whitespace = None;
796 if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
797 // This was the last subslice.
798 sub_slice_end = match first_whitespace {
799 Some(i) => self.last_slice_end + i,
800 None => self.slice.len(),
804 let kind = match self.last_slice_kind {
805 CodeCharKind::Comment => CodeCharKind::Normal,
806 CodeCharKind::Normal => CodeCharKind::Comment,
811 &self.slice[self.last_slice_end..sub_slice_end],
813 self.last_slice_end = sub_slice_end;
814 self.last_slice_kind = kind;
820 /// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
821 /// (if it fits in the width/offset, else return None), else return `new`
822 pub fn recover_comment_removed(
825 context: &RewriteContext,
827 ) -> Option<String> {
828 let snippet = context.snippet(span);
829 if changed_comment_content(&snippet, &new) {
830 // We missed some comments
831 // Keep previous formatting if it satisfies the constrains
832 wrap_str(snippet, context.config.max_width(), shape)
838 /// Return true if the two strings of code have the same payload of comments.
839 /// The payload of comments is everything in the string except:
840 /// - actual code (not comments)
841 /// - comment start/end marks
843 /// - '*' at the beginning of lines in block comments
844 fn changed_comment_content(orig: &str, new: &str) -> bool {
845 // Cannot write this as a fn since we cannot return types containing closures
846 let code_comment_content = |code| {
847 let slices = UngroupedCommentCodeSlices::new(code);
849 .filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
850 .flat_map(|(_, _, s)| CommentReducer::new(s))
852 let res = code_comment_content(orig).ne(code_comment_content(new));
854 "comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
858 code_comment_content(orig).collect::<String>(),
859 code_comment_content(new).collect::<String>()
865 /// Iterator over the 'payload' characters of a comment.
866 /// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
867 /// The comment must be one comment, ie not more than one start mark (no multiple line comments,
869 struct CommentReducer<'a> {
872 iter: std::str::Chars<'a>,
875 impl<'a> CommentReducer<'a> {
876 fn new(comment: &'a str) -> CommentReducer<'a> {
877 let is_block = comment.starts_with("/*");
878 let comment = remove_comment_header(comment);
881 at_start_line: false, // There are no supplementary '*' on the first line
882 iter: comment.chars(),
887 impl<'a> Iterator for CommentReducer<'a> {
889 fn next(&mut self) -> Option<Self::Item> {
891 let mut c = try_opt!(self.iter.next());
892 if self.is_block && self.at_start_line {
893 while c.is_whitespace() {
894 c = try_opt!(self.iter.next());
896 // Ignore leading '*'
898 c = try_opt!(self.iter.next());
900 } else if c == '\n' {
901 self.at_start_line = true;
903 if !c.is_whitespace() {
911 fn remove_comment_header(comment: &str) -> &str {
912 if comment.starts_with("///") || comment.starts_with("//!") {
914 } else if comment.starts_with("//") {
916 } else if (comment.starts_with("/**") && !comment.starts_with("/**/")) ||
917 comment.starts_with("/*!")
919 &comment[3..comment.len() - 2]
922 comment.starts_with("/*"),
923 format!("string '{}' is not a comment", comment)
925 &comment[2..comment.len() - 2]
931 use super::{contains_comment, rewrite_comment, CharClasses, CodeCharKind, CommentCodeSlices,
932 FindUncommented, FullCodeCharKind};
937 let mut iter = CharClasses::new("//\n\n".chars());
939 assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
940 assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
941 assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
942 assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
943 assert_eq!(None, iter.next());
947 fn comment_code_slices() {
948 let input = "code(); /* test */ 1 + 1";
949 let mut iter = CommentCodeSlices::new(input);
951 assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
953 (CodeCharKind::Comment, 8, "/* test */"),
956 assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
957 assert_eq!(None, iter.next());
961 fn comment_code_slices_two() {
962 let input = "// comment\n test();";
963 let mut iter = CommentCodeSlices::new(input);
965 assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
967 (CodeCharKind::Comment, 0, "// comment\n"),
971 (CodeCharKind::Normal, 11, " test();"),
974 assert_eq!(None, iter.next());
978 fn comment_code_slices_three() {
979 let input = "1 // comment\n // comment2\n\n";
980 let mut iter = CommentCodeSlices::new(input);
982 assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
984 (CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
987 assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
988 assert_eq!(None, iter.next());
992 #[cfg_attr(rustfmt, rustfmt_skip)]
993 fn format_comments() {
994 let mut config: ::config::Config = Default::default();
995 config.set().wrap_comments(true);
996 config.set().normalize_comments(true);
998 let comment = rewrite_comment(" //test",
1000 Shape::legacy(100, Indent::new(0, 100)),
1002 assert_eq!("/* test */", comment);
1004 let comment = rewrite_comment("// comment on a",
1006 Shape::legacy(10, Indent::empty()),
1008 assert_eq!("// comment\n// on a", comment);
1010 let comment = rewrite_comment("// A multi line comment\n // between args.",
1012 Shape::legacy(60, Indent::new(0, 12)),
1014 assert_eq!("// A multi line comment\n // between args.", comment);
1016 let input = "// comment";
1019 let comment = rewrite_comment(input,
1021 Shape::legacy(9, Indent::new(0, 69)),
1023 assert_eq!(expected, comment);
1025 let comment = rewrite_comment("/* trimmed */",
1027 Shape::legacy(100, Indent::new(0, 100)),
1029 assert_eq!("/* trimmed */", comment);
1032 // This is probably intended to be a non-test fn, but it is not used. I'm
1033 // keeping it around unless it helps us test stuff.
1034 fn uncommented(text: &str) -> String {
1035 CharClasses::new(text.chars())
1036 .filter_map(|(s, c)| match s {
1037 FullCodeCharKind::Normal => Some(c),
1044 fn test_uncommented() {
1045 assert_eq!(&uncommented("abc/*...*/"), "abc");
1047 &uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
1050 assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
1054 fn test_contains_comment() {
1055 assert_eq!(contains_comment("abc"), false);
1056 assert_eq!(contains_comment("abc // qsdf"), true);
1057 assert_eq!(contains_comment("abc /* kqsdf"), true);
1058 assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
1062 fn test_find_uncommented() {
1063 fn check(haystack: &str, needle: &str, expected: Option<usize>) {
1064 assert_eq!(expected, haystack.find_uncommented(needle));
1067 check("/*/ */test", "test", Some(6));
1068 check("//test\ntest", "test", Some(7));
1069 check("/* comment only */", "whatever", None);
1071 "/* comment */ some text /* more commentary */ result",
1075 check("sup // sup", "p", Some(2));
1076 check("sup", "x", None);
1077 check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
1078 check("/*sup yo? \n sup*/ sup", "p", Some(20));
1079 check("hel/*lohello*/lo", "hello", None);
1080 check("acb", "ab", None);
1081 check(",/*A*/ ", ",", Some(0));
1082 check("abc", "abc", Some(0));
1083 check("/* abc */", "abc", None);
1084 check("/**/abc/* */", "abc", Some(4));
1085 check("\"/* abc */\"", "abc", Some(4));
1086 check("\"/* abc", "abc", Some(4));