teal-language / tl

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

Possible Typechecking Failure on Union Return #758

Closed balajeerc closed 1 day ago

balajeerc commented 2 days ago

I suspect I might have run into a type checking bug as relates to functions returning a union type.

Here's a small snippet:

local record Message
  message_id: number
end

local record MessageQueue
  messages: {Message}
end

local function pop_message(msg_queue: MessageQueue): Message | nil
  return table.remove(msg_queue.messages, 1)
end

local function pop_msg_wrapper(msg_queue: MessageQueue): Message
  local message = pop_message(msg_queue)
  return message 
end

local msg_queue: MessageQueue = {messages = {}}
local invalid_msg: Message = pop_msg_wrapper(msg_queue)
print(invalid_msg.message_id) -- Errors out at runtime :(

This script passes tl check without errors or warnings. It errors out on tl run though.

tl check fails to flag the error that pop_msg_wrapper is returning a Message | nil union type, whereas it should be returning a Message type as per the declared signature for pop_msg_wrapper.

Is this a bug or is there a misunderstanding on my part?

$ tl --version
0.15.3
Frityet commented 1 day ago

all teal types are nillable, so the | nil is ignored

balajeerc commented 1 day ago

all types are nillable

Got it, that I suppose also explains why this code also passes type check

local function takes_type(val: string)
    print(val)
end

takes_type(nil)

Thanks for the clarification. @Frityet Closing this issue.