summaryrefslogtreecommitdiff
path: root/script/core/diagnostics/undefined-global.lua
blob: 5ac5106dd567e9b9389375219572372fbfa22b87 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
local files     = require 'files'
local vm        = require 'vm'
local lang      = require 'language'
local config    = require 'config'
local guide     = require 'parser.guide'
local noder     = require 'core.noder'
local collector = require 'core.collector' 'searcher'
local await     = require 'await'

local requireLike = {
    ['include'] = true,
    ['import']  = true,
    ['require'] = true,
    ['load']    = true,
}

---@async
return function (uri, callback)
    local ast = files.getState(uri)
    if not ast then
        return
    end

    -- 遍历全局变量,检查所有没有 set 模式的全局变量
    guide.eachSourceType(ast.ast, 'getglobal', function (src) ---@async
        local key = src[1]
        if not key then
            return
        end
        if config.get(uri, 'Lua.diagnostics.globals')[key] then
            return
        end
        if config.get(uri, 'Lua.runtime.special')[key] then
            return
        end
        local node = src.node
        if node.tag ~= '_ENV' then
            return
        end
        await.delay()
        local id = 'def:' .. noder.getID(src)
        if not collector:has(id) then
            local message = lang.script('DIAG_UNDEF_GLOBAL', key)
            if requireLike[key:lower()] then
                message = ('%s(%s)'):format(message, lang.script('DIAG_REQUIRE_LIKE', key))
            end
            callback {
                start   = src.start,
                finish  = src.finish,
                message = message,
            }
            return
        end
    end)
end