teal-language / tl

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

Feature/record body declared methods #642

Closed JR-Mitchell closed 1 year ago

JR-Mitchell commented 1 year ago

What?

Why?

See #638 - this PR allows for forward declaration of methods in records, based on the first argument being named self and being correctly typed. This allows for warnings and clearer errors when using types defined in .d.tl files, as well as allowing methods to be declared in one scope and then defined in another without losing these warnings.

Anything else?

There is an edge case which may need discussion: the code

local record MyRecord<T>
    add: function(self: MyRecord<integer>, other: MyRecord<integer>)
end
local first: MyRecord<integer> = {}
local second: MyRecord<integer> = {}
first.add(second)

does not raise a warning, since add is not treated as a method for MyRecord, even though it could be argued that it should be treated as a method of the type realisation MyRecord<integer>. I have a vague idea of how this could be achieved if we want this behaviour, but haven't been able to properly implement it yet. Let me know whether it is fine that there is no warning in this situation, whether this can go into a separate issue / PR, or whether I should try to resolve it in this PR.

github-actions[bot] commented 1 year ago

Teal Playground URL: https://642--teal-playground-preview.netlify.app

hishamhm commented 1 year ago

There is an edge case which may need discussion

I think this is fine. The best we could do in that case would be to add a warning hint if the type (including type arguments) for a first argument called self is not nominally the same as the record the function is in, but for such specific scenario the programmer might want to call that self consciously and we'd be drifting into coding style, so better not make the type checker that opinionated.

Overall the PR looks good as far as I can tell! Merging, thanks!!

hishamhm commented 1 year ago

also: released in Teal 0.15.2!