summaryrefslogtreecommitdiff
path: root/script/core/hover/args.lua
blob: c485d9b91987fe2085d4aaaee1abe7f64d593ec0 (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
66
67
68
69
70
71
72
73
local guide = require 'parser.guide'
local vm    = require 'vm'

local function asFunction(source)
    local args = {}
    local methodDef
    local parent = source.parent
    if parent and parent.type == 'setmethod' then
        methodDef = true
    end
    if methodDef then
        args[#args+1] = ('self: %s'):format(vm.getInfer(parent.node):view 'any')
    end
    if source.args then
        for i = 1, #source.args do
            local arg = source.args[i]
            if arg.type == 'self' then
                goto CONTINUE
            end
            local name = arg.name or guide.getKeyName(arg)
            if name then
                local argNode = vm.compileNode(arg)
                local optional
                if argNode:isOptional() then
                    optional = true
                    argNode = argNode:copy()
                    argNode:removeOptional()
                end
                args[#args+1] = ('%s%s: %s'):format(
                    name,
                    optional and '?' or '',
                    vm.getInfer(argNode):view('any', guide.getUri(source))
                )
            elseif arg.type == '...' then
                args[#args+1] = ('%s: %s'):format(
                    '...',
                    vm.getInfer(arg):view 'any'
                )
            else
                args[#args+1] = ('%s'):format(vm.getInfer(arg):view 'any')
            end
            ::CONTINUE::
        end
    end
    return args
end

local function asDocFunction(source)
    if not source.args then
        return ''
    end
    local args = {}
    for i = 1, #source.args do
        local arg = source.args[i]
        local name = arg.name[1]
        args[i] = ('%s%s: %s'):format(
            name,
            arg.optional and '?' or '',
            arg.extends and vm.getInfer(arg.extends):view 'any' or 'any'
        )
    end
    return args
end

return function (source)
    if source.type == 'function' then
        return asFunction(source)
    end
    if source.type == 'doc.type.function' then
        return asDocFunction(source)
    end
    return {}
end