s.lines().next().map_or("", |first_line| {
first_line
.find(' ')
- .map_or(first_line, |space_index| &first_line[0..space_index + 1])
+ .map_or(first_line, |space_index| &first_line[0..=space_index])
})
}
impl<'a> CommentStyle<'a> {
+ /// Returns true if the commenting style covers a line only.
+ pub fn is_line_comment(&self) -> bool {
+ match *self {
+ CommentStyle::DoubleSlash
+ | CommentStyle::TripleSlash
+ | CommentStyle::Doc
+ | CommentStyle::Custom(_) => true,
+ _ => false,
+ }
+ }
+
+ /// Returns true if the commenting style can span over multiple lines.
+ pub fn is_block_comment(&self) -> bool {
+ match *self {
+ CommentStyle::SingleBullet | CommentStyle::DoubleBullet | CommentStyle::Exclamation => {
+ true
+ }
+ _ => false,
+ }
+ }
+
+ /// Returns true if the commenting style is for documentation.
pub fn is_doc_comment(&self) -> bool {
match *self {
CommentStyle::TripleSlash | CommentStyle::Doc => true,
}
pub fn rewrite_doc_comment(orig: &str, shape: Shape, config: &Config) -> Option<String> {
- _rewrite_comment(orig, false, shape, config, true)
+ identify_comment(orig, false, shape, config, true)
}
pub fn rewrite_comment(
shape: Shape,
config: &Config,
) -> Option<String> {
- _rewrite_comment(orig, block_style, shape, config, false)
-}
-
-fn _rewrite_comment(
- orig: &str,
- block_style: bool,
- shape: Shape,
- config: &Config,
- is_doc_comment: bool,
-) -> Option<String> {
- // If there are lines without a starting sigil, we won't format them correctly
- // so in that case we won't even re-align (if !config.normalize_comments()) and
- // we should stop now.
- let num_bare_lines = orig
- .lines()
- .map(|line| line.trim())
- .filter(|l| !(l.starts_with('*') || l.starts_with("//") || l.starts_with("/*")))
- .count();
- if num_bare_lines > 0 && !config.normalize_comments() {
- return Some(orig.to_owned());
- }
- if !config.normalize_comments() && !config.wrap_comments() {
- return light_rewrite_comment(orig, shape.indent, config, is_doc_comment);
- }
-
- identify_comment(orig, block_style, shape, config, is_doc_comment)
+ identify_comment(orig, block_style, shape, config, false)
}
fn identify_comment(
is_doc_comment: bool,
) -> Option<String> {
let style = comment_style(orig, false);
- let mut first_group_ending = 0;
+ // Computes the len of line taking into account a newline if the line is part of a paragraph.
fn compute_len(orig: &str, line: &str) -> usize {
if orig.len() > line.len() {
if orig.as_bytes()[line.len()] == b'\r' {
}
}
- match style {
+ // Get the first group of line comments having the same commenting style.
+ //
+ // Returns a tuple with:
+ // - a boolean indicating if there is a blank line
+ // - a number indicating the size of the first group of comments
+ fn consume_same_line_comments(
+ style: CommentStyle,
+ orig: &str,
+ line_start: &str,
+ ) -> (bool, usize) {
+ let mut first_group_ending = 0;
+ let mut hbl = false;
+
+ for line in orig.lines() {
+ let trimmed_line = line.trim_left();
+ if trimmed_line.is_empty() {
+ hbl = true;
+ break;
+ } else if trimmed_line.starts_with(line_start)
+ || comment_style(trimmed_line, false) == style
+ {
+ first_group_ending += compute_len(&orig[first_group_ending..], line);
+ } else {
+ break;
+ }
+ }
+ (hbl, first_group_ending)
+ }
+
+ let (has_bare_lines, first_group_ending) = match style {
CommentStyle::DoubleSlash | CommentStyle::TripleSlash | CommentStyle::Doc => {
let line_start = style.line_start().trim_left();
- for line in orig.lines() {
- if line.trim_left().starts_with(line_start) || comment_style(line, false) == style {
- first_group_ending += compute_len(&orig[first_group_ending..], line);
- } else {
- break;
- }
- }
+ consume_same_line_comments(style, orig, line_start)
}
CommentStyle::Custom(opener) => {
let trimmed_opener = opener.trim_right();
- for line in orig.lines() {
- if line.trim_left().starts_with(trimmed_opener) {
- first_group_ending += compute_len(&orig[first_group_ending..], line);
- } else {
- break;
- }
- }
+ consume_same_line_comments(style, orig, trimmed_opener)
}
// for a block comment, search for the closing symbol
CommentStyle::DoubleBullet | CommentStyle::SingleBullet | CommentStyle::Exclamation => {
let closer = style.closer().trim_left();
+ let mut closing_symbol_offset = 0;
+ let mut hbl = false;
for line in orig.lines() {
- first_group_ending += compute_len(&orig[first_group_ending..], line);
- if line.trim_left().ends_with(closer) {
+ closing_symbol_offset += compute_len(&orig[closing_symbol_offset..], line);
+ let trimmed_line = line.trim_left();
+ if !trimmed_line.starts_with('*')
+ && !trimmed_line.starts_with("//")
+ && !trimmed_line.starts_with("/*")
+ {
+ hbl = true;
+ }
+ if trimmed_line.ends_with(closer) {
break;
}
}
+ (hbl, closing_symbol_offset)
}
- }
+ };
let (first_group, rest) = orig.split_at(first_group_ending);
- let first_group_str = rewrite_comment_inner(
- first_group,
- block_style,
- style,
- shape,
- config,
- is_doc_comment || style.is_doc_comment(),
- )?;
+ let rewritten_first_group =
+ if !config.normalize_comments() && has_bare_lines && style.is_block_comment() {
+ light_rewrite_block_comment_with_bare_lines(first_group, shape, config)?
+ } else if !config.normalize_comments() && !config.wrap_comments() {
+ light_rewrite_comment(first_group, shape.indent, config, is_doc_comment)?
+ } else {
+ rewrite_comment_inner(
+ first_group,
+ block_style,
+ style,
+ shape,
+ config,
+ is_doc_comment || style.is_doc_comment(),
+ )?
+ };
if rest.is_empty() {
- Some(first_group_str)
+ Some(rewritten_first_group)
} else {
- identify_comment(rest, block_style, shape, config, is_doc_comment).map(|rest_str| {
- format!(
- "{}\n{}{}",
- first_group_str,
- shape.indent.to_string(config),
- rest_str
- )
+ identify_comment(rest.trim_left(), block_style, shape, config, is_doc_comment).map(
+ |rest_str| {
+ format!(
+ "{}\n{}{}{}",
+ rewritten_first_group,
+ // insert back the blank line
+ if has_bare_lines && style.is_line_comment() {
+ "\n"
+ } else {
+ ""
+ },
+ shape.indent.to_string(config),
+ rest_str
+ )
+ },
+ )
+ }
+}
+
+/// Trims a minimum of leading whitespaces so that the content layout is kept and aligns to indent.
+fn light_rewrite_block_comment_with_bare_lines(
+ orig: &str,
+ shape: Shape,
+ config: &Config,
+) -> Option<String> {
+ let prefix_whitespace_min = orig
+ .lines()
+ // skip the line with the starting sigil since the leading whitespace is removed
+ // otherwise, the minimum would always be zero
+ .skip(1)
+ .filter(|line| !line.is_empty())
+ .map(|line| {
+ let mut width = 0;
+ for c in line.chars() {
+ match c {
+ ' ' => width += 1,
+ '\t' => width += config.tab_spaces(),
+ _ => break,
+ }
+ }
+ width
})
+ .min()?;
+
+ let indent_str = shape.indent.to_string(config);
+ let mut lines = orig.lines();
+ let first_line = lines.next()?;
+ let rest = lines
+ .map(|line| {
+ if line.is_empty() {
+ line
+ } else {
+ &line[prefix_whitespace_min..]
+ }
+ })
+ .collect::<Vec<&str>>()
+ .join(&format!("\n{}", indent_str));
+ Some(format!("{}\n{}{}", first_line, indent_str, rest))
+}
+
+/// Attributes for code blocks in rustdoc.
+/// See https://doc.rust-lang.org/rustdoc/print.html#attributes
+enum CodeBlockAttribute {
+ Rust,
+ Ignore,
+ Text,
+ ShouldPanic,
+ NoRun,
+ CompileFail,
+}
+
+impl CodeBlockAttribute {
+ fn new(attribute: &str) -> CodeBlockAttribute {
+ match attribute {
+ "rust" | "" => CodeBlockAttribute::Rust,
+ "ignore" => CodeBlockAttribute::Ignore,
+ "text" => CodeBlockAttribute::Text,
+ "should_panic" => CodeBlockAttribute::ShouldPanic,
+ "no_run" => CodeBlockAttribute::NoRun,
+ "compile_fail" => CodeBlockAttribute::CompileFail,
+ _ => CodeBlockAttribute::Text,
+ }
}
}
}
line
- }).map(|s| left_trim_comment_line(s, &style))
+ })
+ .map(|s| left_trim_comment_line(s, &style))
.map(|(line, has_leading_whitespace)| {
if orig.starts_with("/*") && line_breaks == 0 {
(
result.push_str(opener);
let mut code_block_buffer = String::with_capacity(128);
let mut is_prev_line_multi_line = false;
- let mut inside_code_block = false;
+ let mut code_block_attr = None;
let comment_line_separator = format!("{}{}", indent_str, line_start);
let join_code_block_with_comment_line_separator = |s: &str| {
let mut result = String::with_capacity(s.len() + 128);
for (i, (line, has_leading_whitespace)) in lines.enumerate() {
let is_last = i == count_newlines(orig);
- if inside_code_block {
+ if let Some(ref attr) = code_block_attr {
if line.starts_with("```") {
- inside_code_block = false;
- result.push_str(&comment_line_separator);
- let code_block = {
- let mut config = config.clone();
- config.set().wrap_comments(false);
- match ::format_code_block(&code_block_buffer, &config) {
- Some(ref s) => trim_custom_comment_prefix(s),
- None => trim_custom_comment_prefix(&code_block_buffer),
+ let code_block = match attr {
+ CodeBlockAttribute::Ignore | CodeBlockAttribute::Text => {
+ trim_custom_comment_prefix(&code_block_buffer)
+ }
+ _ if code_block_buffer.is_empty() => String::new(),
+ _ => {
+ let mut config = config.clone();
+ config.set().wrap_comments(false);
+ match ::format_code_block(&code_block_buffer, &config) {
+ Some(ref s) => trim_custom_comment_prefix(s),
+ None => trim_custom_comment_prefix(&code_block_buffer),
+ }
}
};
- result.push_str(&join_code_block_with_comment_line_separator(&code_block));
+ if !code_block.is_empty() {
+ result.push_str(&comment_line_separator);
+ result.push_str(&join_code_block_with_comment_line_separator(&code_block));
+ }
code_block_buffer.clear();
result.push_str(&comment_line_separator);
result.push_str(line);
+ code_block_attr = None;
} else {
code_block_buffer.push_str(&hide_sharp_behind_comment(line));
code_block_buffer.push('\n');
if is_last {
- // There is an code block that is not properly enclosed by backticks.
+ // There is a code block that is not properly enclosed by backticks.
// We will leave them untouched.
result.push_str(&comment_line_separator);
result.push_str(&join_code_block_with_comment_line_separator(
continue;
} else {
- inside_code_block = line.starts_with("```");
+ code_block_attr = if line.starts_with("```") {
+ Some(CodeBlockAttribute::new(&line[3..]))
+ } else {
+ None
+ };
if result == opener {
let force_leading_whitespace = opener == "/* " && count_newlines(orig) == 0;
} else {
line
}
- }).collect::<Vec<_>>()
+ })
+ .collect::<Vec<_>>()
.join("\n")
}
};
// Preserve markdown's double-space line break syntax in doc comment.
trim_right_unless_two_whitespaces(left_trimmed, is_doc_comment)
- }).collect();
+ })
+ .collect();
Some(lines.join(&format!("\n{}", offset.to_string(config))))
}
Normal,
LitString,
LitStringEscape,
+ LitRawString(u32),
+ RawStringPrefix(u32),
+ RawStringSuffix(u32),
LitChar,
LitCharEscape,
// The u32 is the nesting deepness of the comment
InComment,
/// Last character of a comment, '\n' for a line comment, '/' for a block comment.
EndComment,
+ /// Start of a mutlitine string
+ StartString,
+ /// End of a mutlitine string
+ EndString,
/// Inside a string.
InString,
}
}
pub fn is_string(self) -> bool {
- self == FullCodeCharKind::InString
+ self == FullCodeCharKind::InString || self == FullCodeCharKind::StartString
}
fn to_codecharkind(self) -> CodeCharKind {
}
}
+fn is_raw_string_suffix<T>(iter: &mut MultiPeek<T>, count: u32) -> bool
+where
+ T: Iterator,
+ T::Item: RichChar,
+{
+ for _ in 0..count {
+ match iter.peek() {
+ Some(c) if c.get_char() == '#' => continue,
+ _ => return false,
+ }
+ }
+ true
+}
+
impl<T> Iterator for CharClasses<T>
where
T: Iterator,
let chr = item.get_char();
let mut char_kind = FullCodeCharKind::Normal;
self.status = match self.status {
- CharClassesStatus::LitString => match chr {
- '"' => CharClassesStatus::Normal,
- '\\' => {
- char_kind = FullCodeCharKind::InString;
- CharClassesStatus::LitStringEscape
+ CharClassesStatus::LitRawString(sharps) => {
+ char_kind = FullCodeCharKind::InString;
+ match chr {
+ '"' => {
+ if sharps == 0 {
+ char_kind = FullCodeCharKind::Normal;
+ CharClassesStatus::Normal
+ } else if is_raw_string_suffix(&mut self.base, sharps) {
+ CharClassesStatus::RawStringSuffix(sharps)
+ } else {
+ CharClassesStatus::LitRawString(sharps)
+ }
+ }
+ _ => CharClassesStatus::LitRawString(sharps),
}
- _ => {
- char_kind = FullCodeCharKind::InString;
- CharClassesStatus::LitString
+ }
+ CharClassesStatus::RawStringPrefix(sharps) => {
+ char_kind = FullCodeCharKind::InString;
+ match chr {
+ '#' => CharClassesStatus::RawStringPrefix(sharps + 1),
+ '"' => CharClassesStatus::LitRawString(sharps),
+ _ => CharClassesStatus::Normal, // Unreachable.
}
- },
+ }
+ CharClassesStatus::RawStringSuffix(sharps) => {
+ match chr {
+ '#' => {
+ if sharps == 1 {
+ CharClassesStatus::Normal
+ } else {
+ char_kind = FullCodeCharKind::InString;
+ CharClassesStatus::RawStringSuffix(sharps - 1)
+ }
+ }
+ _ => CharClassesStatus::Normal, // Unreachable
+ }
+ }
+ CharClassesStatus::LitString => {
+ char_kind = FullCodeCharKind::InString;
+ match chr {
+ '"' => CharClassesStatus::Normal,
+ '\\' => CharClassesStatus::LitStringEscape,
+ _ => CharClassesStatus::LitString,
+ }
+ }
CharClassesStatus::LitStringEscape => {
char_kind = FullCodeCharKind::InString;
CharClassesStatus::LitString
},
CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
CharClassesStatus::Normal => match chr {
+ 'r' => match self.base.peek().map(|c| c.get_char()) {
+ Some('#') | Some('"') => {
+ char_kind = FullCodeCharKind::InString;
+ CharClassesStatus::RawStringPrefix(0)
+ }
+ _ => CharClassesStatus::Normal,
+ },
'"' => {
char_kind = FullCodeCharKind::InString;
CharClassesStatus::LitString
let mut line = String::new();
+ let start_class = match self.base.peek() {
+ Some((kind, _)) => *kind,
+ None => FullCodeCharKind::Normal,
+ };
+
while let Some((kind, c)) = self.base.next() {
- self.kind = kind;
if c == '\n' {
+ self.kind = match (start_class, kind) {
+ (FullCodeCharKind::Normal, FullCodeCharKind::InString) => {
+ FullCodeCharKind::StartString
+ }
+ (FullCodeCharKind::InString, FullCodeCharKind::Normal) => {
+ FullCodeCharKind::EndString
+ }
+ _ => kind,
+ };
break;
} else {
line.push(c);
context.report.append(
context.source_map.span_to_filename(span).into(),
vec![FormattingError::from_span(
- &span,
+ span,
&context.source_map,
ErrorKind::LostComment,
)],
pub fn filter_normal_code(code: &str) -> String {
let mut buffer = String::with_capacity(code.len());
LineClasses::new(code).for_each(|(kind, line)| match kind {
- FullCodeCharKind::Normal | FullCodeCharKind::InString => {
+ FullCodeCharKind::Normal
+ | FullCodeCharKind::StartString
+ | FullCodeCharKind::InString
+ | FullCodeCharKind::EndString => {
buffer.push_str(&line);
buffer.push('\n');
}
#[test]
#[rustfmt::skip]
fn format_comments() {
- let mut config: ::config::Config = Default::default();
- config.set().wrap_comments(true);
- config.set().normalize_comments(true);
+ let mut wrap_normalize_config: ::config::Config = Default::default();
+ wrap_normalize_config.set().wrap_comments(true);
+ wrap_normalize_config.set().normalize_comments(true);
+
+ let mut wrap_config: ::config::Config = Default::default();
+ wrap_config.set().wrap_comments(true);
let comment = rewrite_comment(" //test",
true,
Shape::legacy(100, Indent::new(0, 100)),
- &config).unwrap();
+ &wrap_normalize_config).unwrap();
assert_eq!("/* test */", comment);
let comment = rewrite_comment("// comment on a",
false,
Shape::legacy(10, Indent::empty()),
- &config).unwrap();
+ &wrap_normalize_config).unwrap();
assert_eq!("// comment\n// on a", comment);
let comment = rewrite_comment("// A multi line comment\n // between args.",
false,
Shape::legacy(60, Indent::new(0, 12)),
- &config).unwrap();
+ &wrap_normalize_config).unwrap();
assert_eq!("// A multi line comment\n // between args.", comment);
let input = "// comment";
let comment = rewrite_comment(input,
true,
Shape::legacy(9, Indent::new(0, 69)),
- &config).unwrap();
+ &wrap_normalize_config).unwrap();
assert_eq!(expected, comment);
let comment = rewrite_comment("/* trimmed */",
true,
Shape::legacy(100, Indent::new(0, 100)),
- &config).unwrap();
+ &wrap_normalize_config).unwrap();
assert_eq!("/* trimmed */", comment);
+
+ // check that different comment style are properly recognised
+ let comment = rewrite_comment(r#"/// test1
+ /// test2
+ /*
+ * test3
+ */"#,
+ false,
+ Shape::legacy(100, Indent::new(0, 0)),
+ &wrap_normalize_config).unwrap();
+ assert_eq!("/// test1\n/// test2\n// test3", comment);
+
+ // check that the blank line marks the end of a commented paragraph
+ let comment = rewrite_comment(r#"// test1
+
+ // test2"#,
+ false,
+ Shape::legacy(100, Indent::new(0, 0)),
+ &wrap_normalize_config).unwrap();
+ assert_eq!("// test1\n\n// test2", comment);
+
+ // check that the blank line marks the end of a custom-commented paragraph
+ let comment = rewrite_comment(r#"//@ test1
+
+ //@ test2"#,
+ false,
+ Shape::legacy(100, Indent::new(0, 0)),
+ &wrap_normalize_config).unwrap();
+ assert_eq!("//@ test1\n\n//@ test2", comment);
+
+ // check that bare lines are just indented but left unchanged otherwise
+ let comment = rewrite_comment(r#"// test1
+ /*
+ a bare line!
+
+ another bare line!
+ */"#,
+ false,
+ Shape::legacy(100, Indent::new(0, 0)),
+ &wrap_config).unwrap();
+ assert_eq!("// test1\n/*\n a bare line!\n\n another bare line!\n*/", comment);
}
// This is probably intended to be a non-test fn, but it is not used. I'm
.filter_map(|(s, c)| match s {
FullCodeCharKind::Normal | FullCodeCharKind::InString => Some(c),
_ => None,
- }).collect()
+ })
+ .collect()
}
#[test]
#[test]
fn test_remove_trailing_white_spaces() {
- let s = format!(" r#\"\n test\n \"#");
+ let s = " r#\"\n test\n \"#";
assert_eq!(remove_trailing_white_spaces(&s), s);
}