Fix incorrect suggestions for E0605 #84968
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #84598. Here is a simplified version of the problem presented in issue #84598:
The current output is:
This is incorrect, though: The cast will not be valid when writing
&t
instead oft
:The correct suggestion is
&*t
, which I have implemented in this pull request. Of course, this suggestion will always require an unsafe block, but arguably, that's what the user really wants if they're trying to cast a pointer to a reference.In any case, claiming that the cast will be valid after implementing the suggestion is overly optimistic, as the coercion logic doesn't seem to resolve all nested obligations, i.e. the cast may still be invalid after implementing the suggestion. I have therefore rephrased the suggestion slightly ("consider borrowing the value" instead of "borrow the value for the cast to be valid").
Additionally, I have fixed another incorrect suggestion not mentioned in #84598, which relates to casting immutable references to mutable ones:
currently leads to
which is obviously incorrect:
I've changed the suggestion to a note explaining the problem:
In this example, it would have been even nicer to suggest replacing
&x
with&mut x
, but this would be much more complex because we would have to take apart the expression to be cast (currently, we only look at its type), and&x
could be stored in a variable, where such a suggestion would not even be directly applicable:My solution covers this case, too.