summaryrefslogtreecommitdiff
path: root/script/core/diagnostics/lowercase-global.lua
blob: d03e8c706fc53e99b056b9fa626e60b15bb6b346 (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
56
57
58
59
60
61
62
63
64
65
local files     = require 'files'
local guide     = require 'parser.guide'
local lang      = require 'language'
local config    = require 'config'
local vm        = require 'vm'

local function isDocClass(source)
    if not source.bindDocs then
        return false
    end
    for _, doc in ipairs(source.bindDocs) do
        if doc.type == 'doc.class' then
            return true
        end
    end
    return false
end

-- 不允许定义首字母小写的全局变量(很可能是拼错或者漏删)
return function (uri, callback)
    local ast = files.getState(uri)
    if not ast then
        return
    end

    local definedGlobal = {}
    for name in pairs(config.get(uri, 'Lua.diagnostics.globals')) do
        definedGlobal[name] = true
    end

    guide.eachSourceType(ast.ast, 'setglobal', function (source)
        local name = guide.getKeyName(source)
        if not name or definedGlobal[name] then
            return
        end
        local first = name:match '%w'
        if not first then
            return
        end
        if not first:match '%l' then
            return
        end
        -- 如果赋值被标记为 doc.class ,则认为是允许的
        if isDocClass(source) then
            return
        end
        if definedGlobal[name] == nil then
            definedGlobal[name] = false
            local global = vm.getGlobal('variable', name)
            if global then
                for _, set in ipairs(global:getSets(uri)) do
                    if vm.isMetaFile(guide.getUri(set)) then
                        definedGlobal[name] = true
                        return
                    end
                end
            end
        end
        callback {
            start   = source.start,
            finish  = source.finish,
            message = lang.script.DIAG_LOWERCASE_GLOBAL,
        }
    end)
end