Skip to content

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

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

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

Conversation

@tao501
Copy link
Copy Markdown
Owner

@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 rust-lang#4050

@tao501 tao501 force-pushed the fix-issue-4050 branch 4 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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Rustfmt changes meaning of closure, also not idempotent

1 participant