Skip to content

Commit 7298ce9

Browse files
authored
Merge pull request #1925 from topecongiro/enhance-comment
Enhance comment formatting
2 parents 4b90fb1 + 1015dd8 commit 7298ce9

File tree

12 files changed

+232
-124
lines changed

12 files changed

+232
-124
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ description = "Tool to find and fix Rust formatting issues"
77
repository = "https://github.com/rust-lang-nursery/rustfmt"
88
readme = "README.md"
99
license = "Apache-2.0/MIT"
10-
include = ["src/*.rs", "Cargo.toml", "build.rs", "LICENSE-*"]
10+
include = ["src/**", "Cargo.toml", "build.rs", "LICENSE-*"]
1111
build = "build.rs"
1212
categories = ["development-tools"]
1313

src/comment.rs

Lines changed: 47 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -153,11 +153,10 @@ pub fn combine_strs_with_missing_comments(
153153
let mut one_line_width =
154154
last_line_width(prev_str) + first_line_width(next_str) + first_sep.len();
155155

156-
let original_snippet = context.snippet(span);
157-
let trimmed_snippet = original_snippet.trim();
158156
let indent_str = shape.indent.to_string(context.config);
157+
let missing_comment = try_opt!(rewrite_missing_comment(span, shape, context));
159158

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

184-
let missing_comment = try_opt!(rewrite_comment(
185-
trimmed_snippet,
186-
false,
187-
shape,
188-
context.config
189-
));
190184
one_line_width -= first_sep.len();
191185
let first_sep = if prev_str.is_empty() || missing_comment.is_empty() {
192186
String::new()
@@ -365,6 +359,50 @@ fn rewrite_comment_inner(
365359
Some(result)
366360
}
367361

362+
/// Given the span, rewrite the missing comment inside it if available.
363+
/// Note that the given span must only include comments (or leading/trailing whitespaces).
364+
pub fn rewrite_missing_comment(
365+
span: Span,
366+
shape: Shape,
367+
context: &RewriteContext,
368+
) -> Option<String> {
369+
let missing_snippet = context.snippet(span);
370+
let trimmed_snippet = missing_snippet.trim();
371+
if !trimmed_snippet.is_empty() {
372+
rewrite_comment(trimmed_snippet, false, shape, context.config)
373+
} else {
374+
Some(String::new())
375+
}
376+
}
377+
378+
/// Recover the missing comments in the specified span, if available.
379+
/// The layout of the comments will be preserved as long as it does not break the code
380+
/// and its total width does not exceed the max width.
381+
pub fn recover_missing_comment_in_span(
382+
span: Span,
383+
shape: Shape,
384+
context: &RewriteContext,
385+
used_width: usize,
386+
) -> Option<String> {
387+
let missing_comment = try_opt!(rewrite_missing_comment(span, shape, context));
388+
if missing_comment.is_empty() {
389+
Some(String::new())
390+
} else {
391+
let missing_snippet = context.snippet(span);
392+
let pos = missing_snippet.chars().position(|c| c == '/').unwrap_or(0);
393+
// 1 = ` `
394+
let total_width = missing_comment.len() + used_width + 1;
395+
let force_new_line_before_comment =
396+
missing_snippet[..pos].contains('\n') || total_width > context.config.max_width();
397+
let sep = if force_new_line_before_comment {
398+
format!("\n{}", shape.indent.to_string(context.config))
399+
} else {
400+
String::from(" ")
401+
};
402+
Some(format!("{}{}", sep, missing_comment))
403+
}
404+
}
405+
368406
/// Trims whitespace and aligns to indent, but otherwise does not change comments.
369407
fn light_rewrite_comment(orig: &str, offset: Indent, config: &Config) -> Option<String> {
370408
let lines: Vec<&str> = orig.lines()

src/expr.rs

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use {Indent, Shape, Spanned};
2020
use chains::rewrite_chain;
2121
use codemap::{LineRangeUtils, SpanUtils};
2222
use comment::{combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
23-
rewrite_comment, FindUncommented};
23+
rewrite_comment, rewrite_missing_comment, FindUncommented};
2424
use config::{Config, ControlBraceStyle, IndentStyle, MultilineStyle, Style};
2525
use items::{span_hi_for_arg, span_lo_for_arg};
2626
use lists::{definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting,
@@ -1195,9 +1195,13 @@ impl<'a> ControlFlow<'a> {
11951195
mk_sp(self.block.span.lo, self.block.span.lo)
11961196
};
11971197

1198-
// for event in event
1198+
// `for event in event`
1199+
// Do not include label in the span.
1200+
let lo = self.label.map_or(self.span.lo, |label| label.span.hi);
11991201
let between_kwd_cond = mk_sp(
1200-
context.codemap.span_after(self.span, self.keyword.trim()),
1202+
context
1203+
.codemap
1204+
.span_after(mk_sp(lo, self.span.hi), self.keyword.trim()),
12011205
self.pat
12021206
.map_or(cond_span.lo, |p| if self.matcher.is_empty() {
12031207
p.span.lo
@@ -1378,21 +1382,13 @@ fn rewrite_label(label: Option<ast::SpannedIdent>) -> String {
13781382
}
13791383

13801384
fn extract_comment(span: Span, context: &RewriteContext, shape: Shape) -> Option<String> {
1381-
let comment_str = context.snippet(span);
1382-
if contains_comment(&comment_str) {
1383-
let comment = try_opt!(rewrite_comment(
1384-
comment_str.trim(),
1385-
false,
1386-
shape,
1387-
context.config,
1388-
));
1389-
Some(format!(
1385+
match rewrite_missing_comment(span, shape, context) {
1386+
Some(ref comment) if !comment.is_empty() => Some(format!(
13901387
"\n{indent}{}\n{indent}",
13911388
comment,
13921389
indent = shape.indent.to_string(context.config)
1393-
))
1394-
} else {
1395-
None
1390+
)),
1391+
_ => None,
13961392
}
13971393
}
13981394

0 commit comments

Comments
 (0)