LuaLS / LuaLS/lua-language-server

Widening cast has no effect

Open
#2,215 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Lua
Stars
4.4k
Forks
442
PR merge metrics
No merged PRs in 30d

Description

### How are you using the lua-language-server?

Visual Studio Code Extension (sumneko.lua)

### Which OS are you using?

Linux

### What is the issue affecting?

Annotations, Type Checking, Hover

### Expected Behaviour

Cast unconditionally overwrites the variable's type with the new type.

### Actual Behaviour

Cast is ignored and in some cases causes additional type check errors.

### Reproduction steps

```lua
---@param str string
local function foo(str)
---@cast str +?
if str == '' then str = nil end
end
```
Note how it produces an error on assignment:
```
This variable is defined as type `string`. Cannot convert its type to `nil`.
- `nil` cannot match `string`
- Type `nil` cannot match `string` Lua Diagnostics.(cast-local-type)
```
Note also that the tooltip for `str` in the comparison says correctly that it is a `string?`. But this has no observable effect on the actual type.

Example two (attempted workaround):
```lua
---@param str string
local function foo(str)
---@cast str string?
if str == '' then str = nil end
end
```
Note how the cast causes a type check error now, which makes no sense.

Example three (from the wiki on cast, modified to actually verify that the cast worked):
```lua
---@type integer
local x

---@cast x +boolean
x = false
```
Note how it produces an error, similarly to the first example. You would expect at least the example from the official documentation itself to work, but it doesn't. This leads me to conclude this is a bug.

### Additional Notes

_No response_

### Log File

_No response_

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the three Lua reproductions in the issue and compare hover information with assignment diagnostics. Trace the cast handling and subsequent type-checking path for local variables, then add or update coverage so widening casts affect assignment checks without introducing contradictory errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
lua
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.