Skip to content

Format comments with different opening in different manner #1604

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 29, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
183 changes: 156 additions & 27 deletions src/comment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,122 @@ fn is_custom_comment(comment: &str) -> bool {
}
}

#[derive(PartialEq, Eq)]
pub enum CommentStyle {
DoubleSlash,
TripleSlash,
Doc,
SingleBullet,
DoubleBullet,
Exclamation,
Custom,
}

impl CommentStyle {
pub fn opener<'a>(&self, orig: &'a str) -> &'a str {
match *self {
CommentStyle::DoubleSlash => "// ",
CommentStyle::TripleSlash => "/// ",
CommentStyle::Doc => "//! ",
CommentStyle::SingleBullet => "/* ",
CommentStyle::DoubleBullet => "/** ",
CommentStyle::Exclamation => "/*! ",
CommentStyle::Custom => {
if orig.chars().nth(3) == Some(' ') {
&orig[0..4]
} else {
&orig[0..3]
}
}
}
}

pub fn closer<'a>(&self) -> &'a str {
match *self {
CommentStyle::DoubleSlash |
CommentStyle::TripleSlash |
CommentStyle::Custom |
CommentStyle::Doc => "",
CommentStyle::DoubleBullet => " **/",
CommentStyle::SingleBullet |
CommentStyle::Exclamation => " */",
}
}

pub fn line_start<'a>(&self, orig: &'a str) -> &'a str {
match *self {
CommentStyle::DoubleSlash => "// ",
CommentStyle::TripleSlash => "/// ",
CommentStyle::Doc => "//! ",
CommentStyle::SingleBullet |
CommentStyle::Exclamation => " * ",
CommentStyle::DoubleBullet => " ** ",
CommentStyle::Custom => {
if orig.chars().nth(3) == Some(' ') {
&orig[0..4]
} else {
&orig[0..3]
}
}
}
}

pub fn to_str_tuplet<'a>(&self, orig: &'a str) -> (&'a str, &'a str, &'a str) {
(self.opener(orig), self.closer(), self.line_start(orig))
}

pub fn line_with_same_comment_style<'a>(&self,
line: &str,
orig: &'a str,
normalize_comments: bool)
-> bool {
match *self {
CommentStyle::DoubleSlash |
CommentStyle::TripleSlash |
CommentStyle::Custom |
CommentStyle::Doc => {
line.trim_left()
.starts_with(self.line_start(orig).trim_left()) ||
comment_style(line, normalize_comments) == *self
}
CommentStyle::DoubleBullet |
CommentStyle::SingleBullet |
CommentStyle::Exclamation => {
line.trim_left().starts_with(self.closer().trim_left()) ||
line.trim_left()
.starts_with(self.line_start(orig).trim_left()) ||
comment_style(line, normalize_comments) == *self
}
}
}
}

fn comment_style(orig: &str, normalize_comments: bool) -> CommentStyle {
if !normalize_comments {
if orig.starts_with("/**") && !orig.starts_with("/**/") {
CommentStyle::DoubleBullet
} else if orig.starts_with("/*!") {
CommentStyle::Exclamation
} else if orig.starts_with("/*") {
CommentStyle::SingleBullet
} else if orig.starts_with("///") {
CommentStyle::TripleSlash
} else if orig.starts_with("//!") {
CommentStyle::Doc
} else {
CommentStyle::DoubleSlash
}
} else if orig.starts_with("///") || (orig.starts_with("/**") && !orig.starts_with("/**/")) {
CommentStyle::TripleSlash
} else if orig.starts_with("//!") || orig.starts_with("/*!") {
CommentStyle::Doc
} else if is_custom_comment(orig) {
CommentStyle::Custom
} else {
CommentStyle::DoubleSlash
}
}

pub fn rewrite_comment(orig: &str,
block_style: bool,
shape: Shape,
Expand All @@ -47,39 +163,52 @@ pub fn rewrite_comment(orig: &str,
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);
}

identify_comment(orig, block_style, shape, config)
}

fn identify_comment(orig: &str,
block_style: bool,
shape: Shape,
config: &Config)
-> Option<String> {
let style = comment_style(orig, false);
let first_group = orig.lines()
.take_while(|l| style.line_with_same_comment_style(l, orig, false))
Copy link
Contributor Author

@topecongiro topecongiro May 29, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was wondering if rust has a function equivalent to span in haskell.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think there is one - there might be one in Itertools, but I prefer not to link it and use simpler functions.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You might be able to use partition

.collect::<Vec<_>>()
.join("\n");
let rest = orig.lines()
.skip(first_group.lines().count())
.collect::<Vec<_>>()
.join("\n");

let first_group_str = try_opt!(rewrite_comment_inner(&first_group, block_style, shape, config));
if rest.is_empty() {
Some(first_group_str)
} else {
identify_comment(&rest, block_style, shape, config).map(|rest_str| {
format!("{}\n{}{}",
first_group_str,
shape
.indent
.to_string(config),
rest_str)
})
}
}

fn rewrite_comment_inner(orig: &str,
block_style: bool,
shape: Shape,
config: &Config)
-> Option<String> {
let (opener, closer, line_start) = if block_style {
("/* ", " */", " * ")
} else if !config.normalize_comments() {
if orig.starts_with("/**") && !orig.starts_with("/**/") {
("/** ", " **/", " ** ")
} else if orig.starts_with("/*!") {
("/*! ", " */", " * ")
} else if orig.starts_with("/*") {
("/* ", " */", " * ")
} else if orig.starts_with("///") {
("/// ", "", "/// ")
} else if orig.starts_with("//!") {
("//! ", "", "//! ")
} else {
("// ", "", "// ")
}
} else if orig.starts_with("///") || (orig.starts_with("/**") && !orig.starts_with("/**/")) {
("/// ", "", "/// ")
} else if orig.starts_with("//!") || orig.starts_with("/*!") {
("//! ", "", "//! ")
} else if is_custom_comment(orig) {
if orig.chars().nth(3) == Some(' ') {
(&orig[0..4], "", &orig[0..4])
} else {
(&orig[0..3], "", &orig[0..3])
}
CommentStyle::SingleBullet.to_str_tuplet("")
} else {
("// ", "", "// ")
comment_style(orig, config.normalize_comments()).to_str_tuplet(orig)
};

let max_chars = shape
Expand Down
12 changes: 12 additions & 0 deletions tests/source/closure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,15 @@ impl Foo {
})
}
}

fn issue1329() {
aaaaaaaaaaaaaaaa.map(|x| {
x += 1;
x
})
.filter
}

fn issue325() {
let f = || unsafe { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx };
}
9 changes: 9 additions & 0 deletions tests/source/issue-1278.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// rustfmt-fn_args_layout = "block"

#![feature(pub_restricted)]

mod inner_mode {
pub(super) fn func_name(abc: i32) -> i32 {
abc
}
}
3 changes: 3 additions & 0 deletions tests/source/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,9 @@ fn main() {
let json = json!({
"foo": "bar",
});

// #1092
chain!(input, a:take!(max_size), || []);
}

impl X {
Expand Down
14 changes: 14 additions & 0 deletions tests/target/closure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,17 @@ impl Foo {
})
}
}

fn issue1329() {
aaaaaaaaaaaaaaaa
.map(|x| {
x += 1;
x
})
.filter
}

fn issue325() {
let f =
|| unsafe { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx };
}
14 changes: 14 additions & 0 deletions tests/target/configs-fn_call_style-block-tab_spaces-2.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// rustfmt-fn_call_style: Block
// rustfmt-max_width: 80
// rustfmt-tab_spaces: 2

// #1427
fn main() {
exceptaions::config(move || {
(
NmiConfig {},
HardFaultConfig {},
SysTickConfig { gpio_sbsrr },
)
});
}
8 changes: 8 additions & 0 deletions tests/target/issue-1214.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*!
# Example

```
// Here goes some example
```
*/
struct Item;
9 changes: 9 additions & 0 deletions tests/target/issue-1278.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// rustfmt-fn_args_layout = "block"

#![feature(pub_restricted)]

mod inner_mode {
pub(super) fn func_name(abc: i32) -> i32 {
abc
}
}
9 changes: 9 additions & 0 deletions tests/target/issue-691.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// rustfmt-normalize_comments: true

//! `std` or `core` and simply link to this library. In case the target
//! platform has no hardware
//! support for some operation, software implementations provided by this
//! library will be used automagically.
// TODO: provide instructions to override default libm link and how to link to
// this library.
fn foo() {}
3 changes: 3 additions & 0 deletions tests/target/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,9 @@ fn main() {
let json = json!({
"foo": "bar",
});

// #1092
chain!(input, a:take!(max_size), || []);
}

impl X {
Expand Down