teal-language / tl

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

Associated types #666

Open voltangle opened 1 year ago

voltangle commented 1 year ago

As a suggestion for a future interface implementation in Teal, I can suggest a system of associated types. It's easier to just show an example:

local interface View
    associatedtype Props
    metamethod __call: function(props: Props): View
    props: Props
    body: function(self)
end

local record Button: View
    type Props = record
        label: string
        action: function()
    end
    -- or
    record Props
        label: string
        action: function()
    end
end

function Button:body()
    local myLabel = self.props.label -- totally valid
    -- do something
end

-- this is also totally valid
Button {
    label = "My label"
    action = function() 
        -- do something
    end
}

(daym dat issue number is fire)

hishamhm commented 1 year ago

@ggoraa thanks for the suggestion -- this looks equivalent to type variables in interfaces, which are another way of declaring type parameters. Using type variables, as in local interface View<Props>, would make it more similar to the way we handle type variables in records today.

Just for fun, the following approximation works today, albeit with bad ergonomics (and a warning) because that local type Button doesn't work like a type alias, but rather as a new unrelated nominal type.

local record View<Props>
    metamethod __call: function(self: View<Props>, props: Props): View<Props>
    props: Props
    body: function(self: View<Props>)
end

local record ButtonProps
     label: string
     action: function()
end

local type Button = View<ButtonProps>

function Button.body(self: View<ButtonProps>)
    local myLabel = self.props.label -- totally valid
    -- do something
    print(myLabel)
end

-- this is also totally valid
local b = Button {
  label = "My label",
  action = function()
      -- do something
  end
}

b.body(b as View<ButtonProps>)

When adding interfaces, my plan is to fix those ergonomics/aliasing issues by handling self in a special way (not unlike e.g. Rust).

voltangle commented 1 year ago

Thanks for the reply!

Yeah, currently it doesn't look great, but I think the addition of interfaces will definitely elevate Teal to be an actually production-ready language that can be used in real projects

Also, I think that the associatedtype syntax (or similar) is better in terms of code reading imo

(Btw, Teal is currently thought about (well mostly by me, I actually pitched the idea to the devs) as an official language for EdgeTX to be used alongside Lua, so if there is any room for cooperation between the two projects it will be great!)