-
Notifications
You must be signed in to change notification settings - Fork 248
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
analyze: move
Option<&mut T>
on last use instead of reborrowing (#1179
) Currently, we reborrow `Option<&mut T>` at most use sites by calling `p.as_deref_mut()`. This creates a new reference that's tied to the lifetime of the `Option`, rather than the lifetime of the original reference. This is fine for temporaries and local variables, but creates a problem when returning the result from the current function: ```Rust fn f(x: Option<&mut Foo>) -> Option<&mut i32> { x.as_deref_mut().map(|x| &mut x.field) } ``` This produces a borrowck error because `as_deref_mut` has the signature `(&'b mut Option<&'a mut T>) -> Option<&'b mut T>`, meaning the result must not outlive `x`. The fix here is to consume `x`: ```Rust fn f(x: Option<&mut Foo>) -> Option<&mut i32> { // No `.as_deref_mut()` - `x` is moved into `map()` x.map(|x| &mut x.field) } ``` In this case, `map` has the signature `(Option<&'a mut T>, [closure]) -> Option<&'a mut i32>`, preserving the lifetime of the input reference. This branch adds an analysis to identify the "last use" of each local variable and modifies the rewriting rules around `Option<T>` to omit `.as_deref_mut()` at the last use.
- Loading branch information
Showing
7 changed files
with
778 additions
and
60 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.