aptos-core
aptos-core copied to clipboard
[Bug] Match arm conditions should not be allowed to mutate what is being matched
🐛 Bug
Consider the following example:
//# publish
module 0xc0ffee::m {
enum W has copy, drop {
W1(u64),
W2(u64),
}
fun use_it(_x: u64) {}
fun weird(w: &mut W): bool {
*w = W::W2(10);
false
}
public fun test(w: &mut W) {
match (w) {
W::W2(_) => {},
W::W1(_) if (weird(w)) => {},
W::W2(x) => { use_it(*x); },
_ => {
assert!(!(*w is W::W2));
},
}
}
public fun run() {
let w = W::W1(5);
test(&mut w);
}
}
This code fails compilation with:
error: unreachable pattern
┌─ TEMPFILE:16:13
│
16 │ W::W2(x) => { use_it(*x); },
│ ^^^^^^^^```
But if you comment out this line, then run run(), the assertion fails (that is, *w is indeed W::W2, so it is reachable, as opposed to what the compiler says).
Note: Rust disallows such mutations in the match arm conditions.