From d4a22f436f8deb77f80ece751973f6c7b76dbd25 Mon Sep 17 00:00:00 2001 From: Matthew Hughes Date: Wed, 2 Sep 2026 19:50:34 +0100 Subject: [PATCH] `chain`: drop redundant check MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In the code: `chain_item` is a _child_ in the chain, and not the root, e.g. `1.foo.bar` in `root.1.foo.bar`. So the question is, can a `try!(..)` expression appear there, e.g. `root.try!(something).0`? My conclusion is that it cannot: firstly note `try!` is not a valid identifier (because of the `!`), so working through the possible chain types (see `pop_expr_chain`): * `MethodCallExpression → Expression . PathExprSegment ( CallParams? )` (e.g. `root.some_method()`): `PathExprSegment` starts with a `PathIdentSegment`, starts with a `IDENTIFIER`: `try!` doesn't match * `FieldExpression → Expression . IDENTIFIER` (e.g. `root.sub`): `try!` doesn't match * `TupleIndexingExpression → Expression . TUPLE_INDEX` (e.g. `root.0`): tuple index is repeated decimal digits: `try!` doesn't match * keywords:`.await`, `.use`, `.yield`: `try!` doesn't match Of course a: `try!` can be the _root_ of a chain `try!(foo).bar` is perfectly valid. This fixes an issue: as previously, if the `use_try_shorthand` config was set we would skip over any comments in any children of the chain, so they would be dropped. The added test case covers this situation. Fixes: rust-lang/rustfmt#6121 --- src/chains.rs | 4 +--- tests/source/chains.rs | 6 ++++++ tests/target/chains.rs | 6 ++++++ 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/chains.rs b/src/chains.rs index 45d9d488c76..dd826734db4 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -458,9 +458,7 @@ impl Chain { } while let Some(chain_item) = iter.next() { let comment_snippet = context.snippet(chain_item.span); - // FIXME: Figure out the way to get a correct span when converting `try!` to `?`. - let handle_comment = - !(context.config.use_try_shorthand() || is_tries(comment_snippet.trim())); + let handle_comment = !is_tries(comment_snippet.trim()); // Pre-comment if handle_comment { diff --git a/tests/source/chains.rs b/tests/source/chains.rs index c77f5bac4cb..a16712e5be1 100644 --- a/tests/source/chains.rs +++ b/tests/source/chains.rs @@ -264,3 +264,9 @@ fn issue_3034() { disallowed_headers.iter().any(|header| *header == name) || disallowed_header_prefixes.iter().any(|prefix| name.starts_with(prefix)) } + +fn issue_6121() { + let _ = foo // some comment + .bar // some other comment + .buz; +} diff --git a/tests/target/chains.rs b/tests/target/chains.rs index 292da298195..4fc23745126 100644 --- a/tests/target/chains.rs +++ b/tests/target/chains.rs @@ -304,3 +304,9 @@ fn issue_3034() { disallowed_headers.iter().any(|header| *header == name) || disallowed_header_prefixes.iter().any(|prefix| name.starts_with(prefix)) } + +fn issue_6121() { + let _ = foo // some comment + .bar // some other comment + .buz; +}