LuaLS / LuaLS/lua-language-server
`---@cast` annotation doesn't respect scope rules
Nobody has claimed this yet.
- 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?
Windows
### What is the issue affecting?
Type Checking
### Expected Behaviour
The `---@cast` annotation should respect Lua scoping rules.
### Actual Behaviour
Let's consider:
```lua
--- @class foo
--- @field a number
--- @class bar
--- @field b string
--- @type { [integer]: foo|bar }
local array = {}
for i, instance in ipairs(array) do
if instance.a then
-- First if block
--- @cast instance foo
end
if instance.b then
-- Second if block
end
end
```
In the first if block, we cast the `instance` to the `foo` type. When hovering over the `instance` variable in the second if block we can see its type is `foo`. It would be expected for its type to be `bar` since the `---@cast` happened in different scope.

### Reproduction steps
1. Copy-paste the given example code into your text editor.
2. Hover over the `instance` variable in the second if block.
3. See the error in the popup.
### Additional Notes
_No response_
### Log File
_No response_
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the issue with the supplied Lua example in the Visual Studio Code extension and inspect how type checking handles the two if-block scopes. Done means the cast to foo applies only within the first block, while the instance in the second block retains the appropriate inferred type instead of foo.
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
- Clearly specified
- Newbie friendliness
- 42/100