lua-language-server icon indicating copy to clipboard operation
lua-language-server copied to clipboard

Feature Request: Add constant annotation to show a warning when modifying variables marked as const

Open sniper00 opened this issue 2 years ago • 4 comments

Constant modifications can be detected in the editor in advance.

example:


---@const_type  ErrorCode
local errorCode = {}

errorCode.NOT_FOUND = 10 --- show warnings attemp modify constant variables.

sniper00 avatar Apr 04 '23 09:04 sniper00

I love the idea, but I would suggest using ---@const for the variable itself to show that the variable cannot be reassigned, and if you want values within a data structure to be constants then use something like ---@readonly or ReadOnly data types.

local tbl = {}; ---@const table<string, string>

tbl = 123 -- this should not be allowed!

tbl.hello = "hi" -- this is fine

and for making the hello field also a constant:

local tbl = {} ---@const ReadOnly<table<string, string>>
tbl.hello = "hi" -- not allowed!

Or readonly for @field and @param annotations:

---@param readonly msg string
local function Print(msg)
  msg = "something else" -- not allowed!
end 

---@class Program
---@field readonly ProcessID number

Mayron avatar Apr 07 '23 12:04 Mayron

I love the idea, but I would suggest using ---@const for the variable itself to show that the variable cannot be reassigned, and if you want values within a data structure to be constants then use something like ---@readonly or ReadOnly data types.

local tbl = {}; ---@const table<string, string>

tbl = 123 -- this should not be allowed!

tbl.hello = "hi" -- this is fine

and for making the hello field also a constant:

local tbl = {} ---@const ReadOnly<table<string, string>>
tbl.hello = "hi" -- not allowed!

Or readonly for @field and @param annotations:

---@param readonly msg string
local function Print(msg)
  msg = "something else" -- not allowed!
end 

---@class Program
---@field readonly ProcessID number

Yes, readonly is indeed more appropriate.

sniper00 avatar Apr 07 '23 12:04 sniper00

This would be ultra extremely helpful. Perhaps lump together the four. immutable constant final readOnly. In lua's case, these all have the same effect.

jordan4ibanez avatar Apr 27 '23 23:04 jordan4ibanez

I desperately need a way to mark mutability/ownership of function parameters and return values. A feature like this might help.

curiosity-a avatar May 15 '24 12:05 curiosity-a