Skip to content

Enhance comment formatting #1925

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 8 commits into from
Aug 27, 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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ description = "Tool to find and fix Rust formatting issues"
repository = "https://github.com/rust-lang-nursery/rustfmt"
readme = "README.md"
license = "Apache-2.0/MIT"
include = ["src/*.rs", "Cargo.toml", "build.rs", "LICENSE-*"]
include = ["src/**", "Cargo.toml", "build.rs", "LICENSE-*"]
build = "build.rs"
categories = ["development-tools"]

Expand Down
56 changes: 47 additions & 9 deletions src/comment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,11 +153,10 @@ pub fn combine_strs_with_missing_comments(
let mut one_line_width =
last_line_width(prev_str) + first_line_width(next_str) + first_sep.len();

let original_snippet = context.snippet(span);
let trimmed_snippet = original_snippet.trim();
let indent_str = shape.indent.to_string(context.config);
let missing_comment = try_opt!(rewrite_missing_comment(span, shape, context));

if trimmed_snippet.is_empty() {
if missing_comment.is_empty() {
if allow_extend && prev_str.len() + first_sep.len() + next_str.len() <= shape.width {
return Some(format!("{}{}{}", prev_str, first_sep, next_str));
} else {
Expand All @@ -175,18 +174,13 @@ pub fn combine_strs_with_missing_comments(
// Peek the the original source code and find out whether there is a newline between the first
// expression and the second expression or the missing comment. We will preserve the orginal
// layout whenever possible.
let original_snippet = context.snippet(span);
let prefer_same_line = if let Some(pos) = original_snippet.chars().position(|c| c == '/') {
!original_snippet[..pos].contains('\n')
} else {
!original_snippet.contains('\n')
};

let missing_comment = try_opt!(rewrite_comment(
trimmed_snippet,
false,
shape,
context.config
));
one_line_width -= first_sep.len();
let first_sep = if prev_str.is_empty() || missing_comment.is_empty() {
String::new()
Expand Down Expand Up @@ -365,6 +359,50 @@ fn rewrite_comment_inner(
Some(result)
}

/// Given the span, rewrite the missing comment inside it if available.
/// Note that the given span must only include comments (or leading/trailing whitespaces).
pub fn rewrite_missing_comment(
span: Span,
shape: Shape,
context: &RewriteContext,
) -> Option<String> {
let missing_snippet = context.snippet(span);
let trimmed_snippet = missing_snippet.trim();
if !trimmed_snippet.is_empty() {
rewrite_comment(trimmed_snippet, false, shape, context.config)
} else {
Some(String::new())
}
}

/// Recover the missing comments in the specified span, if available.
/// The layout of the comments will be preserved as long as it does not break the code
/// and its total width does not exceed the max width.
pub fn recover_missing_comment_in_span(
span: Span,
shape: Shape,
context: &RewriteContext,
used_width: usize,
) -> Option<String> {
let missing_comment = try_opt!(rewrite_missing_comment(span, shape, context));
if missing_comment.is_empty() {
Some(String::new())
} else {
let missing_snippet = context.snippet(span);
let pos = missing_snippet.chars().position(|c| c == '/').unwrap_or(0);
// 1 = ` `
let total_width = missing_comment.len() + used_width + 1;
let force_new_line_before_comment =
missing_snippet[..pos].contains('\n') || total_width > context.config.max_width();
let sep = if force_new_line_before_comment {
format!("\n{}", shape.indent.to_string(context.config))
} else {
String::from(" ")
};
Some(format!("{}{}", sep, missing_comment))
}
}

/// Trims whitespace and aligns to indent, but otherwise does not change comments.
fn light_rewrite_comment(orig: &str, offset: Indent, config: &Config) -> Option<String> {
let lines: Vec<&str> = orig.lines()
Expand Down
26 changes: 11 additions & 15 deletions src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use {Indent, Shape, Spanned};
use chains::rewrite_chain;
use codemap::{LineRangeUtils, SpanUtils};
use comment::{combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
rewrite_comment, FindUncommented};
rewrite_comment, rewrite_missing_comment, FindUncommented};
use config::{Config, ControlBraceStyle, IndentStyle, MultilineStyle, Style};
use items::{span_hi_for_arg, span_lo_for_arg};
use lists::{definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting,
Expand Down Expand Up @@ -1195,9 +1195,13 @@ impl<'a> ControlFlow<'a> {
mk_sp(self.block.span.lo, self.block.span.lo)
};

// for event in event
// `for event in event`
// Do not include label in the span.
let lo = self.label.map_or(self.span.lo, |label| label.span.hi);
let between_kwd_cond = mk_sp(
context.codemap.span_after(self.span, self.keyword.trim()),
context
.codemap
.span_after(mk_sp(lo, self.span.hi), self.keyword.trim()),
self.pat
.map_or(cond_span.lo, |p| if self.matcher.is_empty() {
p.span.lo
Expand Down Expand Up @@ -1378,21 +1382,13 @@ fn rewrite_label(label: Option<ast::SpannedIdent>) -> String {
}

fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
let comment_str = context.snippet(span);
if contains_comment(&comment_str) {
let comment = try_opt!(rewrite_comment(
comment_str.trim(),
false,
shape,
context.config,
));
Some(format!(
match rewrite_missing_comment(span, shape, context) {
Some(ref comment) if !comment.is_empty() => Some(format!(
"\n{indent}{}\n{indent}",
comment,
indent = shape.indent.to_string(context.config)
))
} else {
None
)),
_ => None,
}
}

Expand Down
Loading