Skip to content

Issues with booleans #1294

@firas-assaad

Description

@firas-assaad

Describe the bug
In certain cases, boolean inferred values don't work as expected. This usually happens when calling functions that don't have explicit @return annotations and that return true or false explicitly (e.g. return false).

To Reproduce
Example 1:

---@param int integer
local function x(int)
end

local function y()
    if math.random() > 0.5 then
        return true
    else
        return false
    end
end

local bool = y()
local should_be_int = bool and 300 or 500
x(should_be_int) 
-- Warning: Cannot assign `integer|true` to parameter `integer`.Lua Diagnostics.(param-type-mismatch)

should_be_int is inferred as integer|true. If I annotate the function y with @return boolean or if function y is rewritten as return math.random() > 0.5, then should_be_int is correctly deduced as integer.

Example 2:

local function y()
    if math.random() < 0.5 then
        return true
    else
        return false
    end
end

---@return boolean
local function x()
    local bool = true

    bool = y()

    bool = bool and y()

    if bool then
        print(1)
    end

    return bool
    -- Warning: The type of the 1 return value is `boolean`, but the actual return is `boolean|true|false`
end

The variable bool is inferred as boolean|true|false which is somehow incompatible with the specified @return. If I remove the @return annotation, or if the y function doesn't explicitly return true/false, or if you change the body of the function x, the warning does not happen.

Expected behavior
The boolean return types should be treated the same in all cases.

Screenshots
I wrote down the warnings in the code snippets, but if you want screenshots let me know.

Environment (please complete the following information):

  • OS: Windows 10
  • Is WSL remote? No
  • Client: VSCode 1.68.1
  • lua-language-server version v3.4.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinggood issueArt of asking

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions