enact-lang/enact

Implement references

Dandigit opened this issue · 1 comments

I'd now like to implement references, as in the following:

const x = 2
// Create references with &
const ref = &x

// Dereferencing is automatic
print(ref + 3) // 5

var y = 3
// Create variable references with &var
var yref = &var y
yref = 2

// You cannot reference a reference
const refref = &&x // Error!
// ...Or an rvalue
const rvref = &2 // Error!

// Reference types: &T/&var T
fun add(a int, b int, target &var int):
    target = a + b
end

// Subscripting a variable array returns a variable reference
var arr = [1, 2, 3, 4, 5]
arr[0] = 2 // arr = [2, 2, 3, 4, 5]

// Unless the array is const, of course
const carr = [1, 2, 3, 4, 5]
carr[0] = 2 // Error: Cannot assign to a const reference!

// Same applies for variable structs
struct Person:
    name string
    age int
end

var jim = Person("Jim", 99)

// Accessing a struct member returns a reference
jim.age = 98

// Unless the struct is const, of course
const sam = Person("Sam", 42)
sam.age = 43 // Error: Cannot assign to a const reference!

// Variable references are implicitly convertible to const references, but not the other way around
fun printPerson(person &Person):
    print("Person("+person.name", "+string(person.age)+")")
end

printPerson(&var jim) // Works, but could be confusing
printPerson(&jim) // Better

fun jimmifyPerson(person &var Person):
    person.name = "Jim"
    person.age = 99
end

jimmifyPerson(&sam) // Cannot do this!

I've decided to move away from this proposal and instead implement the system described in #61.