summaryrefslogtreecommitdiff
path: root/script/core/diagnostics/duplicate-index.lua
blob: 5e63d39edb444e5f9197cb371fc9cd66c39da28f (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
local files   = require 'files'
local guide   = require 'core.guide'
local lang    = require 'language'
local define  = require 'proto.define'
local vm      = require 'vm'

return function (uri, callback)
    local ast = files.getAst(uri)
    if not ast then
        return
    end

    guide.eachSourceType(ast.ast, 'table', function (source)
        local mark = {}
        for _, obj in ipairs(source) do
            if obj.type == 'tablefield'
            or obj.type == 'tableindex' then
                local name = vm.getKeyName(obj)
                if name then
                    if not mark[name] then
                        mark[name] = {}
                    end
                    mark[name][#mark[name]+1] = obj.field or obj.index
                end
            end
        end

        for name, defs in pairs(mark) do
            if #defs > 1 and name then
                local related = {}
                for i = 1, #defs do
                    local def = defs[i]
                    related[i] = {
                        start  = def.start,
                        finish = def.finish,
                        uri    = uri,
                    }
                end
                for i = 1, #defs - 1 do
                    local def = defs[i]
                    callback {
                        start   = def.start,
                        finish  = def.finish,
                        related = related,
                        message = lang.script('DIAG_DUPLICATE_INDEX', name),
                        level   = define.DiagnosticSeverity.Hint,
                        tags    = { define.DiagnosticTag.Unnecessary },
                    }
                end
                for i = #defs, #defs do
                    local def = defs[i]
                    callback {
                        start   = def.start,
                        finish  = def.finish,
                        related = related,
                        message = lang.script('DIAG_DUPLICATE_INDEX', name),
                    }
                end
            end
        end
    end)
end