compiler icon indicating copy to clipboard operation
compiler copied to clipboard

Typed local variables

Open thekid opened this issue 1 year ago • 1 comments

Inspired by https://externals.io/message/119470#119488 and https://wiki.php.net/rfc/local_variable_types

What we would like to achieve

int $i= 0;

$i= 'Test'; // Should throw an exception

How it can be implemented

($_w= new class(0) { public function __construct(public int $value) { } }) ? $i= &$_w->value : null;

$i= 'Test'; // Cannot assign string to reference held by property class@anonymous::$value of type int

In the compiler, we could keep of the variables and instead of using references, emit $_i->value everywhere we encounter $i in the current block. This would also allow us to implement readonly local variables (like const in JavaScript):

// readonly int $i= 5;
$_i= new class(5) { public function __construct(public readonly int $value) { } };

// $i++;
$_i->value++; // Cannot modify readonly property class@anonymous::$value

Limitations

We can only use types in the PHP type system, e.g. the above wouldn't work for array<int> for example.

Performance

Using $_i->value instead of $i timed in at 175 milliseconds instead of 127 for 10 million assignments - a very small decrease, which will mostly not be noticed.

thekid avatar Feb 12 '23 11:02 thekid

This could also be used to implemented readonly / constant function arguments, as discussed in https://externals.io/message/120615 and https://externals.io/message/120203#120210

thekid avatar Jun 24 '23 10:06 thekid