aptos-labs / aptos-core

Aptos is a layer 1 blockchain built to support the widespread use of blockchain through better technology and user experience.
https://aptosfoundation.org
Other
6k stars 3.61k forks source link

[Bug][Compiler-v2] false positive `cannot mutably borrow since immutable references exist` when function returns a tuple containing both immutable and mutable references #13608

Closed rahxephon89 closed 3 weeks ago

rahxephon89 commented 3 months ago

🐛 Bug

When compiling the following program using V2:

module 0x8675309::M {

    fun t3(u1: &mut u64, u2: &mut u64): (&mut u64, &u64) {
        (u1, u2)
    }
    public fun bar2() {
        let x: &mut u64;
        let y: &u64;
        (x, y) = t3(&mut 3, &mut 4);
        x;
        y;
    }

}

Following error is generated:

Diagnostics:
error: cannot mutably borrow since immutable references exist
   ┌─ tests/reference-safety/debug-12394.move:9:18
   │
 9 │         (x, y) = t3(&mut 3, &mut 4);
   │                  ^^^^^^^^^^^^^^^^^^
   │                  │
   │                  mutable borrow attempted here
   │                  previous call result
10 │         x;
   │         - requirement enforced here
11 │         y;
   │         - conflicting reference `y` used here
zzjas commented 1 month ago

Another related example:

//# publish
module 0xCAFE::Module0 {
    use std::vector;
    public fun function1() : u8 {
        let x: vector<u8> =  vector[123u8];
        let y =  vector::borrow<u8>(&x, 0);
        vector::push_back<u8>(&mut x, *y);
        vector::pop_back<u8>(&mut x)
    }
}

//# run 0xCAFE::Module0::function1

V2 gives:

 error: cannot mutably borrow since immutable references exist
  ┌─ TEMPFILE:7:31
  │
6 │         let y =  vector::borrow<u8>(&x, 0);
  │                  -------------------------
  │                  │                  │
  │                  │                  previous local borrow
  │                  used by call result
7 │         vector::push_back<u8>(&mut x, *y);
  │                               ^^^^^^  -- requirement enforced here
  │                               │        
  │                               mutable borrow attempted here
rahxephon89 commented 3 weeks ago

fixed by #14276