Mutability

From Adam Colton
Jump to navigation Jump to search

Mutability will be explicit.

Variables are mutable or immutable.

Mono Mute

One idea I like but I'm not sure about it's feasibility; there can only ever be one mutable reference. For linear stack calls, this is easy. If we disallow any form of global mutable, it's also easy.

The only complicating factor is concurrency. If I have a mutable reference that I want to share with a concurrent call, then there's two references.

Case Study

How would you add a memoization wrapper? Specifically, to a concurrent Fibonacci call.

States

There are two base states:

  • Mutable
  • Immutable

but that's not enough because something may be mutable to one instance and immutable to another. So it becomes

  • Mutable
  • Fluid
  • Immutable

Fluid means that our copy is read only, but someone may have a writeable copy. Immutable means that the data cannot change. We can create immutable instances by making them immutable at construction, but we'd like to be able to have a mutable instance and when some criteria is met, lock it. This may introduce a new state (though it may not be necessary)

  • Lockable
  • Mutable
  • Fluid
  • Immutable

If A calls B and A has a lockable instance of X, it can pass X in as Mutable and guarantee when B returns that X is still mutable.

These states are also coercible:

  • Lockable
  • Mutable : Lockable
  • Fluid : Mutable, Lockable
  • Immutable

Expressions

It might be good to disallow mutable calls in expressions.

 if a.Foo() || a.Bar() {...}

If a.Bar can mutate a and || is evaluated lazily, this is a good spot for bugs to hide.

Functions

Functions can infer if they are immutable. A function that does not call any functions with side effects or mutate it's arguments is immutable.

This is one of the places where using the same bytecode for the compiler and runtime will be advantageous. If a function is immutable and it's arguments are known at compile time, the compiler can run the function and replace the return value.

Message Passing

A can pass a mutable X to B as a message.