Skip to content

Add checking for unnecessary delims in closure body #136906

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 2 commits into from
Jul 10, 2025

Conversation

chenyukang
Copy link
Member

Fixes #136741

@rustbot
Copy link
Collaborator

rustbot commented Feb 12, 2025

r? @jieyouxu

rustbot has assigned @jieyouxu.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Feb 12, 2025
@chenyukang chenyukang force-pushed the yukang-fix-136741-closure-body branch 3 times, most recently from 3b739b5 to ccdf053 Compare February 12, 2025 05:27
if matches!(closure.fn_decl.output, FnRetTy::Default(_))
// skip `#[core::contracts::requires(...)]` and `#[core::contracts::ensures(...)]` which generate closure
&& !cx
.sess()
Copy link
Member Author

@chenyukang chenyukang Feb 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

any better check for this?
seems the AST generated by contracts are the same with normal closures.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we could generate an #[allow] for this lint as part of the ast we generate. Alternatively you could check that it's expanded code in general and just ignore all of this. Likely some macros will hit this issue, too (add a test for that, too)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternatively you could check that it's expanded code in general and just ignore all of this.

The following check here https://github.com/rust-lang/rust/pull/136906/files#diff-e25b2c6c1fa434ab8078db81003888370f06b9da5503d1590757350be8e31103L945-L946 already checked it?

I also tried to use closure.body.span.can_be_used_for_suggestions(), seems can not exclude this scenario.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for the solution we could generate an #[allow] for this lint as part of the ast we generate.

I tried to add it here:
428b251

which will break the parser.

seems we only add simple tokentree for the contract and parse it here:
https://github.com/chenyukang/rust/blob/428b251feb3e87e41c9e46656cc96a3b94d88ea5/compiler/rustc_parse/src/parser/generics.rs#L302-L325

we do not expect too much change just to generate an #[allow(unused_parens)], where is the proper point to inject it.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

already checked it?

ah that means contract expansion doesn't add the expansion info to the spans. I did indeed forget to check for that at all when it was introduced

cc @celinval

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to mark the span with DesugaringKind::Contract at here: https://github.com/chenyukang/rust/blob/9ec13a62cafd1448b2d43d887034ae6501fca6d0/compiler/rustc_ast_lowering/src/item.rs#L1082-L1089

But found that early lint check is run before this point.

I think this solution with span check maybe enough: 64f1f52

the generated closure span are all the same, which is different from real code.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah right this is due to the macro expansion from

fn expand_contract_clause(
maybe the span can be annotated there?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to follow mark_with_reason https://github.com/chenyukang/rust/blob/59281e98d0af7ed5071d141235ce5ddff1f60253/compiler/rustc_span/src/hygiene.rs#L906-L919

to create a span with annotation:
59281e9#diff-0843065cebe8379cca975e505c67c393f9933c8d9019fb6a6e3b3d5654157bc1R70

The problem is how can we get a ctx which meet the trait here, seems we're at a very early stage:

error[E0277]: the trait bound `SyntaxContext: rustc_span::HashStableContext` is not satisfied
   --> compiler/rustc_builtin_macros/src/contracts.rs:70:49
    |
70  |     let expn_id = LocalExpnId::fresh(expn_data, attr_span.ctxt());
    |                   ------------------            ^^^^^^^^^^^^^^^^ the trait `rustc_span::HashStableContext` is not implemented for `SyntaxContext`
    |                   |
    |                   required by a bound introduced by this call
    |
note: required by a bound in `LocalExpnId::fresh`
   --> /Users/yukang/rust/compiler/rustc_span/src/hygiene.rs:200:53
    |
200 |     pub fn fresh(mut expn_data: ExpnData, ctx: impl HashStableContext) -> LocalExpnId {
    |                                                     ^^^^^^^^^^^^^^^^^ required by this bound in `LocalExpnId::fresh`

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the span checking here is enough for avoid lint for contract syntax here?
https://github.com/rust-lang/rust/pull/136906/files#diff-e25b2c6c1fa434ab8078db81003888370f06b9da5503d1590757350be8e31103R917-R918

it's a bit hacky, but user written code will always true on : e.span != closure.body.span.

And also considering the fact that contract syntax is temporary, if we can not find a perfect way to mark the span we should not introduce more change for it. #137134 (comment)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're absolutely right. Sorry for holding it up

@rust-log-analyzer

This comment has been minimized.

@rust-log-analyzer

This comment has been minimized.

@chenyukang chenyukang force-pushed the yukang-fix-136741-closure-body branch from c755f78 to c7ec66c Compare February 12, 2025 07:06
@rustbot
Copy link
Collaborator

rustbot commented Feb 12, 2025

Some changes occurred to MIR optimizations

cc @rust-lang/wg-mir-opt

Some changes occurred in coverage instrumentation.

cc @Zalathar

@rust-log-analyzer

This comment has been minimized.

@rustbot
Copy link
Collaborator

rustbot commented Feb 12, 2025

The Miri subtree was changed

cc @rust-lang/miri

Some changes occurred in src/tools/clippy

cc @rust-lang/clippy

Copy link
Contributor

@oli-obk oli-obk left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that's a lot of changes in unrelated tests. Changing tests for such reasons isn't too great and the value of this change in tests isn't really there either. Maybe add the lint to the list of lints that compiletest allows for all tests?

@rust-log-analyzer

This comment has been minimized.

@jieyouxu
Copy link
Member

jieyouxu commented Feb 12, 2025

That's a lot of changes in unrelated tests. Changing tests for such reasons isn't too great and the value of this change in tests isn't really there either.

IMO we may want to just not warn on this case. Looking at the diffs both in the compiler and in the tests, it doesn't seem like a strict readability improvement to me (at times I find it even a bit harder to read). unused_parens is also a warn-by-default lint, so we'd be warning on a lot of existing code (judging by quite a few instances of compiler code getting newly linted on when we expand this lint).

Maybe add the lint to the list of lints that compiletest allows for all tests?

I think we should avoid adding blanket allows for all tests where feasible (many tests getting affected is itself a decent indicator, albeit rough, for if a change may impact a lot of cases).

@oli-obk
Copy link
Contributor

oli-obk commented Feb 12, 2025

Looking at the diffs both in the compiler and in the tests, it doesn't seem like a strict readability improvement to me (at times I find it even a bit harder to read)

in the compiler and tools it was always an improvement to me. What specific examples do you dislike?

@jieyouxu
Copy link
Member

jieyouxu commented Feb 12, 2025

in the compiler and tools it was always an improvement to me. What specific examples do you dislike?

This probably comes down to personal preference, but I don't really find these specific examples to be strictly better (I find the { } helps with visual separation of the body expr. I don't feel too strongly about this so 🤷

-.all(|(node, span_edge)| { span_edge.is_some() <= self.is_supernode(node) }),
+.all(|(node, span_edge)| span_edge.is_some() <= self.is_supernode(node)),

-write!(&mut counter, "{:#}", fmt::from_fn(|f| { self.inner_full_print(None, f, cx) }))
+write!(&mut counter, "{:#}", fmt::from_fn(|f| self.inner_full_print(None, f, cx)))

Removing parens on the very short exprs do look more readable to me. So I guess I feel mixed about it? lol

@jieyouxu
Copy link
Member

Since you're already looking at it... r? @oli-obk

@rustbot rustbot assigned oli-obk and unassigned jieyouxu Feb 12, 2025
@chenyukang chenyukang force-pushed the yukang-fix-136741-closure-body branch from 5e56316 to 9ec13a6 Compare February 13, 2025 01:14
@rustbot rustbot added A-compiletest Area: The compiletest test runner A-testsuite Area: The testsuite used to check the correctness of rustc T-bootstrap Relevant to the bootstrap subteam: Rust's build system (x.py and src/bootstrap) labels Feb 13, 2025
@rustbot
Copy link
Collaborator

rustbot commented Feb 13, 2025

Some changes occurred in src/tools/compiletest

cc @jieyouxu

@rust-log-analyzer

This comment has been minimized.

@chenyukang
Copy link
Member Author

that's a lot of changes in unrelated tests. Changing tests for such reasons isn't too great and the value of this change in tests isn't really there either. Maybe add the lint to the list of lints that compiletest allows for all tests?

done with commit 3a34ad7

@chenyukang
Copy link
Member Author

Yes, this seems comes down to personal preference, but I just found rustfmt will remove the braces in this closure:

 let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };

@rust-log-analyzer

This comment has been minimized.

@chenyukang chenyukang force-pushed the yukang-fix-136741-closure-body branch from d2998ad to 7a7feeb Compare June 29, 2025 11:17
@rustbot
Copy link
Collaborator

rustbot commented Jun 29, 2025

rust-analyzer is developed in its own repository. If possible, consider making this change to rust-lang/rust-analyzer instead.

cc @rust-lang/rust-analyzer

@rust-log-analyzer

This comment has been minimized.

@chenyukang
Copy link
Member Author

rust-lang/rust-analyzer#20122 is merged, rebase and try again...

@chenyukang chenyukang force-pushed the yukang-fix-136741-closure-body branch from ef8eac4 to 93db9e7 Compare July 10, 2025 01:29
@rust-log-analyzer

This comment has been minimized.

@lnicola
Copy link
Member

lnicola commented Jul 10, 2025

@chenyukang feel free to patch this here instead.

@chenyukang
Copy link
Member Author

@chenyukang feel free to patch this here instead.

yeah, seems rust-analyzer haven't synced up, CI is ok now.

@rustbot ready

@oli-obk
Copy link
Contributor

oli-obk commented Jul 10, 2025

@bors r+ rollup

@bors
Copy link
Collaborator

bors commented Jul 10, 2025

📌 Commit 4dc954f has been approved by oli-obk

It is now in the queue for this repository.

@bors bors added S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Jul 10, 2025
bors added a commit that referenced this pull request Jul 10, 2025
Rollup of 12 pull requests

Successful merges:

 - #136906 (Add checking for unnecessary delims in closure body)
 - #143652 (docs: document trait upcasting rules in `Unsize` trait)
 - #143657 (Resolver: refact macro map into external and local maps)
 - #143659 (Use "Innermost" & "Outermost" terminology for `AttributeOrder`)
 - #143663 (fix: correct typo in attr_parsing_previously_accepted message key)
 - #143666 (Re-expose nested bodies in rustc_borrowck::consumers)
 - #143668 (Fix VxWorks build errors)
 - #143670 (Add a new maintainer to the wasm32-wasip1 target)
 - #143675 (improve lint doc text)
 - #143683 (Assorted `run-make-support` maintenance)
 - #143695 (Auto-add `S-waiting-on-author` when the PR is/switches to draft state)
 - #143706 (triagebot.toml: ping lolbinarycat if tidy extra checks were modified)

r? `@ghost`
`@rustbot` modify labels: rollup
@bors bors merged commit a0c7887 into rust-lang:master Jul 10, 2025
11 checks passed
@rustbot rustbot added this to the 1.90.0 milestone Jul 10, 2025
@rfcbot rfcbot removed proposed-final-comment-period Proposed to merge/close by relevant subteam, see T-<team> label. Will enter FCP once signed off. disposition-merge This issue / PR is in PFCP or FCP with a disposition to merge it. labels Jul 10, 2025
rust-timer added a commit that referenced this pull request Jul 10, 2025
Rollup merge of #136906 - chenyukang:yukang-fix-136741-closure-body, r=oli-obk

Add checking for unnecessary delims in closure body

Fixes #136741
@Kobzol
Copy link
Member

Kobzol commented Jul 10, 2025

@rust-timer build 936033a

Checking for #143731.

@rust-timer

This comment has been minimized.

@rust-timer
Copy link
Collaborator

Finished benchmarking commit (936033a): comparison URL.

Overall result: ❌ regressions - please read the text below

Benchmarking this pull request means it may be perf-sensitive – we'll automatically label it not fit for rolling up. You can override this, but we strongly advise not to, due to possible changes in compiler perf.

Next Steps: If you can justify the regressions found in this try perf run, please do so in sufficient writing along with @rustbot label: +perf-regression-triaged. If not, please fix the regressions and do another perf run. If its results are neutral or positive, the label will be automatically removed.

@bors rollup=never
@rustbot label: -S-waiting-on-perf +perf-regression

Instruction count

Our most reliable metric. Used to determine the overall result above. However, even this metric can be noisy.

mean range count
Regressions ❌
(primary)
0.2% [0.1%, 0.4%] 11
Regressions ❌
(secondary)
0.3% [0.1%, 0.9%] 13
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
- - 0
All ❌✅ (primary) 0.2% [0.1%, 0.4%] 11

Max RSS (memory usage)

Results (primary 1.2%, secondary -0.9%)

A less reliable metric. May be of interest, but not used to determine the overall result above.

mean range count
Regressions ❌
(primary)
1.2% [0.6%, 3.6%] 7
Regressions ❌
(secondary)
4.2% [2.0%, 6.4%] 2
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
-4.3% [-6.0%, -2.3%] 3
All ❌✅ (primary) 1.2% [0.6%, 3.6%] 7

Cycles

This benchmark run did not return any relevant results for this metric.

Binary size

This benchmark run did not return any relevant results for this metric.

Bootstrap: 463.013s -> 465.296s (0.49%)
Artifact size: 374.51 MiB -> 374.53 MiB (0.01%)

@rustbot rustbot added the perf-regression Performance regression. label Jul 10, 2025
@Kobzol
Copy link
Member

Kobzol commented Jul 10, 2025

Looks like this is the source of the small regression from #143731. Any ideas about clawing that back? Or do you think it's expected since we do more work Oli?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-compiletest Area: The compiletest test runner A-testsuite Area: The testsuite used to check the correctness of rustc I-lang-radar Items that are on lang's radar and will need eventual work or consideration. P-lang-drag-2 Lang team prioritization drag level 2.https://rust-lang.zulipchat.com/#narrow/channel/410516-t-lang. perf-regression Performance regression. S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. S-waiting-on-concerns Status: Awaiting concerns to be addressed by the author T-bootstrap Relevant to the bootstrap subteam: Rust's build system (x.py and src/bootstrap) T-lang Relevant to the language team T-rustdoc-frontend Relevant to the rustdoc-frontend team, which will review and decide on the web UI/UX output.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

false-negative unused_parens in closures consisting of just one expression