Skip to content

Commit 90b3222

Browse files
authored
Merge pull request #2090 from topecongiro/issue-2087
Only read the trailing comma of outermost fn call
2 parents f159d32 + fa7d8de commit 90b3222

File tree

3 files changed

+27
-4
lines changed

3 files changed

+27
-4
lines changed

src/expr.rs

+17-4
Original file line numberDiff line numberDiff line change
@@ -2365,11 +2365,24 @@ pub fn wrap_args_with_parens(
23652365
}
23662366
}
23672367

2368+
/// Return true if a function call or a method call represented by the given span ends with a
2369+
/// trailing comma. This function is used when rewriting macro, as adding or removing a trailing
2370+
/// comma from macro can potentially break the code.
23682371
fn span_ends_with_comma(context: &RewriteContext, span: Span) -> bool {
2369-
let snippet = context.snippet(span);
2370-
snippet
2371-
.trim_right_matches(|c: char| c == ')' || c.is_whitespace())
2372-
.ends_with(',')
2372+
let mut encountered_closing_paren = false;
2373+
for c in context.snippet(span).chars().rev() {
2374+
match c {
2375+
',' => return true,
2376+
')' => if encountered_closing_paren {
2377+
return false;
2378+
} else {
2379+
encountered_closing_paren = true;
2380+
},
2381+
_ if c.is_whitespace() => continue,
2382+
_ => return false,
2383+
}
2384+
}
2385+
false
23732386
}
23742387

23752388
fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, shape: Shape) -> Option<String> {

tests/source/macros.rs

+6
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,12 @@ fn main() {
2121
kaas!(/* comments */ a /* post macro */, b /* another */);
2222

2323
trailingcomma!( a , b , c , );
24+
// Preserve trailing comma only when necessary.
25+
ok!(file.seek(
26+
SeekFrom::Start(
27+
table.map(|table| fixture.offset(table)).unwrap_or(0),
28+
)
29+
));
2430

2531
noexpr!( i am not an expression, OK? );
2632

tests/target/macros.rs

+4
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,10 @@ fn main() {
3333
);
3434

3535
trailingcomma!(a, b, c,);
36+
// Preserve trailing comma only when necessary.
37+
ok!(file.seek(SeekFrom::Start(
38+
table.map(|table| fixture.offset(table)).unwrap_or(0),
39+
)));
3640

3741
noexpr!( i am not an expression, OK? );
3842

0 commit comments

Comments
 (0)