LuaLS / lua-language-server

A language server that offers Lua language support - programmed in Lua
https://luals.github.io
MIT License
3.21k stars 297 forks source link

require path with custom package.loaders #2644

Open Gerark opened 3 months ago

Gerark commented 3 months ago

In my project I'm adding new package.loaders which means I'm able to import things that are not real files.

local bindings = require "bindings.core" -- This is not a real file

Any path starting with bindings. is treated differently. Is there a way to instruct the Lua Language Server to treat those specific requires in a special way and have them returning the right type annotation? I'd like to not specify the @type every time I'm requiring these special packages.

---@type CoreBindings  <---- I'm forced to specify the type
local bindings = require "bindings.core" 

If there's a valid solution I'd need it to work outside of VS code. I'm running LuaLS as a standalone check.

CppCXY commented 3 months ago

By design there should be --@module "xxx.fff", It may not be in effect for luals

Gerark commented 3 months ago

By design there should be --@module "xxx.fff", It may not be in effect for luals

I'm not sure what the module annotation simulates tho. ( I saw the example but still a bit lost about it ) I need to tell what's the type returned by the module. Can that be done with --@module

tomlau10 commented 2 months ago

As far as I know ---@module is used to annotate the variable that follows, such that the variable is the same as the return value of requiring the package specified by ---@module.

For example:

---@module "xxx.fff"
local bindings = require "bindings.core" -- This is not a real file

I'd like to not specify the @type every time I'm requiring these special packages.

As you can imagine now, even with ---@module annotation, you still need to specify it every time when you require these special packages. So another approach is that you create those fake files (as meta definition files) and return the correct type in each of them.

For example in your workspace:

  1. Create a new folder meta/, and set workspace.library setting to include this folder
    "workspace.library": [
    "meta/"
    ],
  2. Now luals will try to look into this meta/ folder when you require files (‼️ remember that it will still follow the "runtime.path" pattern setting when searching this folder). You can add this bindings.core fake file using the standard lua package file strucutre: meta/bindings/core.lua
  3. Inside this meta/bindings/core.lua, write the definition of the package and return it with your specified type:
    ---@meta
    return {}  ---@type CoreBindings
  4. In this way luals will know that the return type of require "bindgins.core" is CoreBindings, once and for all 😄 (If you wish you might as well move the definition of CoreBindings into this new fake file, which is actually a pure meta definition file)