JSAbrahams / mamba

🐍 The Mamba programming language, because we care about safety
MIT License
85 stars 3 forks source link

We can circumvent mutability by assigning to fields of function returns #188

Closed JSAbrahams closed 1 year ago

JSAbrahams commented 4 years ago

Description of Bug

Due to Python returning shallow copies from functions, we can reassign to fields of values even if the values themselves are immutable.

This behaviour was observed in #181, which contains an ignored test assign_to_inner_non_mut3.

How to Reproduce

class A
    def c: C

class C
    def my_class: D := D()
    def my_field_accessor(self) -> D => self.my_class

class D
    def mut my_field: Int := 10

def mut a := A()
# should raise an error but doesn't
a.c.my_field_accessor().my_field := 20

Expected behaviour

We expect a type error because while my_field is mutable, the class in which it is contained, C, stored as my_class within c, is not.

Additional context

It might be best to take a look at Rust's borrow system and take inspiration from there. In Mamba, we could:

See Rust's borrow checker, which addresses an issue similar to ours (though their solution is more verbose due to Rust's low level nature).