teal-language / tl

The compiler for Teal, a typed dialect of Lua
MIT License
2.02k stars 101 forks source link

Optional Compiler-enforced nil-checking #721

Closed paulsgcross closed 7 months ago

paulsgcross commented 7 months ago

Apologies if this is already a feature.

Context

Currently, it is possible to do this:

local record MyRecord
     SomeField: number
end

local function MyFunction(rec : MyRecord)
     -- Do something...
end

MyFunction({ }) -- This is what I am interested in.

This is fine and supported by the Lua syntax (it is equivilant to 'assigning' nil to every field) and so no reason to prevent it. However, there would be benefit to optionally enforce that specific (or all) Record fields must not be 'nil' when passed into a function or declared as a type - compiler-side.

Proposal

When defining records, allow the programmer to set fields as <required> (a different name to distinguish from require would be better):

local record MyRecord
     <required> SomeField: number
end

-- Compiler will Complain:
local variable : MyRecord = {} 
MyFunction({ })

-- Compiler will Be Happy:
local variable : MyRecord = {SomeField = 5} 
MyFunction({SomeField = 5})

Likewise, if you're lazy and don't want to be forced to set this for every field:

local <required> record MyBigRecord
     SomeField: number
     AnotherField: number
     PleaseStopAddingFields: number
end

MyFunction({SomeField = 5, AnotherField = 4}) -- Compiler will complain.
MyFunction({SomeField = 5, AnotherField = 4, PleaseStopAddingFields = 1}) -- Compiler is happy.

This would be the equivilent of adding <required> to every field.

Anything that matches the required record signature should also be accepted as to allow for polymorphism and the ability to substitute records with 'sub-types':

local <required> record MyBigRecord
     SomeField: number
end

local record AnotherRecord
     SomeField: number
end

local RecOne: AnotherRecord = {}
local RecTwo: AnotherRecord = {SomeField = 5}

MyFunction(RecOne) -- Compiler will complain.
MyFunction(RecTwo) -- Compiler is happy.

Pros

Cons

hishamhm commented 7 months ago

Nil-checking has already been asked for several times. Please see #598 and following discussions. Closing this one as a duplicate, thanks for understanding!

paulsgcross commented 7 months ago

Yep, totally understand. Not sure if I added much to the discussion but will continue to funnel any thoughts into those open issues :)