teal-language / tl

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

Cannot use generics with methods #657

Closed crai0 closed 12 months ago

crai0 commented 1 year ago

It's not possible to use methods with generic records:

Code:

local record Test<T>
    value: T
end

function Test.new<T>(value: T): Test<T>
    return setmetatable({ value = value }, { __index = Test })
end

function Test:print()
    print(self.value)
end

Output:

========================================
2 errors:
test.tl:9:10: missing type arguments in record<T> (value: T; new: function<T>(T): Test<T>; print: function(self))
test.tl:10:16: cannot index key 'value' in bad_nominal 'self' of type Test

The compiler should automatically assume that self is of type Test<T>.

hishamhm commented 1 year ago

@crai0 Thank you for the report and test case! I'll work on a fix.

The compiler should automatically assume that self is of type Test.

Indeed! Also, given that the generic code of the function Test.new<T>(value: T): Test<T> declaration translates to function Test.new(value) — in other words, since it is not really possible to declare multiple implementations of a record function for different type variables — I think the type variable <T> in Test.new<T> should be made implicit as well.

hishamhm commented 1 year ago

@crai0 testing/feedback is most welcome for PR #669!