titzer / virgil

A fast and lightweight native programming language
1.13k stars 40 forks source link

Array type init with a negative value. #245

Closed kalwalt closed 2 months ago

kalwalt commented 2 months ago

If you create an Array like this one: var test: Array<byte> = Array<byte>.new(-1); with a negative length it will compile wthout errors but you will receive a !LengthCheckException when you run the builded app. Does it is correct? Because the parameter in the new constructor is an int but should be better an unsigned int type instead?

titzer commented 2 months ago

The exception is the correct behavior. I agree that it would be better for Array to take an unsigned integer, but in the very beginning there weren't any unsigned types. In the future I was hoping that this could be improved, and that arrays could also accept larger-sized integer types.

kalwalt commented 2 months ago

The exception is the correct behavior. I agree that it would be better for Array to take an unsigned integer, but in the very beginning there weren't any unsigned types. In the future I was hoping that this could be improved, and that arrays could also accept larger-sized integer types.

Sorry to re-open this issue, i want only to answer. I agree with you that this is the correct behavior, I was only thinking if it can be improved. Not a real issue, to be honest i will never assign a negative value to an Array.new(), but if you have a function that as a parameter an unsigned integer and this is assigned to the Array you need to cast to int. I hope that in a future this can be improved.

titzer commented 2 months ago

Sure. Not that array accesses do allow using an integer of any width (or signedness), and if it's a signed integer, the bounds check will check for negative values as well. So this code works:

var x = Array<int>.new(33);
var y1 = x[0uL]; // u64 index
var y2 = x[0L]; // i64 index
var y3 = x[0u]; // u32 index

In theory, new could also be polymorphic in this way.

A natural question is then: what is the type of Array.length--right now it's actually int, but guaranteed to be non-negative. So it's kind of u31. But Virgil's other rules for arithmetic would make it inconvenient to make the type of an array length u31.

Sorry for the small ugliness here.

kalwalt commented 2 months ago

Thank you for the clarification Ben @titzer !