Skip to content

Fix closure with block body followed by method call (issue #4050)#6900

Open
tao501 wants to merge 1 commit into
rust-lang:mainfrom
tao501:fix-issue-4050
Open

Fix closure with block body followed by method call (issue #4050)#6900
tao501 wants to merge 1 commit into
rust-lang:mainfrom
tao501:fix-issue-4050

Conversation

@tao501
Copy link
Copy Markdown

@tao501 tao501 commented May 17, 2026

Description

Fix for rustfmt issue #4050: "Rustfmt changes meaning of closure, also not idempotent"

Problem

When a closure with a block body is followed by a method call (e.g., || { ... }().to_string()), rustfmt incorrectly formats it as:

|| { { println!(); || 0 }().to_string(); }

This changes the program's semantics from ((|| {...}())..to_string()) to || {({...}()..to_string());}.

Root Cause

In src/chains.rs, the should_add_parens() function returns false for closures with block bodies, so the chain formatter doesn't add the necessary parentheses around the closure call before the method call.

Fix

Added ast::ExprKind::Block(..) => true to the closure match in should_add_parens(), ensuring that closures with block bodies get parenthesized when followed by method calls.

This produces the correct output:

(|| { println!(); || 0 }()).to_string()

Closes #4050

@rustbot rustbot added the S-waiting-on-review Status: awaiting review from the assignee but also interested parties. label May 17, 2026
@tao501 tao501 force-pushed the fix-issue-4050 branch 2 times, most recently from 538e2f9 to 5192d69 Compare May 17, 2026 13:09
…4050)

In src/chains.rs should_add_parens(), closures with block bodies were
not getting parentheses when followed by method calls, causing rustfmt
to change program semantics.

This adds ast::ExprKind::Block(..) => true to the closure match
to ensure block-bodied closures get proper parenthesization.
@tao501 tao501 force-pushed the fix-issue-4050 branch 2 times, most recently from f8d7e01 to ae40c17 Compare May 17, 2026 14:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-waiting-on-review Status: awaiting review from the assignee but also interested parties.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Rustfmt changes meaning of closure, also not idempotent

2 participants