LuaLS / LuaLS/lua-language-server

[Feature request] Add a pseudo-type for custom require-like functions

Open
#3,003 0 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

I think it would be useful to have something like a `Require`-type. This type would take a literal string type `T` and evaluate as the same type that calling `require(modname: T)` would. This way, a wrapper around `require` could easily be built like this:

```lua
--- Require a module, throwing an error if it returned `true` (meaning that you
--- probably forgot to actually return something from it).
---@generic T : string
---@param module_name T
---@return Require module -- <-- Note the use of `Require`
local function checked_require(module_name)
assert(type(module_name) == "string", "The `module_name` must be a string!")

local module = require(module_name)

assert(
module ~= true,
string.format(
"Could not import module: `require(%q)` returned `true`!",
module_name
)
)

return module
end

--------------------------------------------------------------------------------

local socket = checked_require("socket")
local socket_require = require("socket")

assert(socket == socket_require)
```

The type-hint of `require()` could then be changed to the following:

```lua
---@generic T : string
---@param module_name T
---@return Require module
function require(module_name) end
```

The language server already has a way to make global functions behave like `require` built-in, in the form of the `"Lua.runtime.special"` setting. This type would essentially do the same, except that it would be more powerful / broadly usable, since it could be applied to any variable. It would also be easier to use, since it's just another type in your code instead of something hiding in a config file.

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 tracing how the language server handles require() type hints and the Lua.runtime.special setting. Define what Require should do for literal module names, wrappers, and the shown checked_require example; done means the wrapper and direct require resolve to the same module type.

Written by the indexing model from the issue text.

Assessment

Tech stack
lua
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.