-
Notifications
You must be signed in to change notification settings - Fork 12.8k
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
Mutating matched value in pattern guard causes segfault in safe code #14684
Comments
Oh dear, nominating. |
I guess the right thing to do is to restrict mutation and mutable borrows of the head expression in guards, but not in the arm expressions themselves. |
The same restrictions also need to apply to any mutable references bound by the patterns. |
cc me |
related to #6393, because the best thing would be to say that the match induces a loan that begins after evaluating head expr and terminates when entering each arm body |
P-backcompat-lang, 1.0. |
the CFG for match statements. There were two bugs in issue #14684. One was simply that the borrow check didn't know about the correct CFG for match statements: the pattern must be a predecessor of the guard. This disallows the bad behavior if there are bindings in the pattern. But it isn't enough to prevent the memory safety problem, because of wildcards; thus, this patch introduces a more restrictive rule, which disallows assignments and mutable borrows inside guards outright. I discussed this with Niko and we decided this was the best plan of action. This breaks code that performs mutable borrows in pattern guards. Most commonly, the code looks like this: impl Foo { fn f(&mut self, ...) {} fn g(&mut self, ...) { match bar { Baz if self.f(...) => { ... } _ => { ... } } } } Change this code to not use a guard. For example: impl Foo { fn f(&mut self, ...) {} fn g(&mut self, ...) { match bar { Baz => { if self.f(...) { ... } else { ... } } _ => { ... } } } } Sometimes this can result in code duplication, but often it illustrates a hidden memory safety problem. Closes #14684. [breaking-change] r? @pnkfelix
The following example causes a segfault for me on OS X / x86_64:
The text was updated successfully, but these errors were encountered: