summaryrefslogtreecommitdiff
path: root/script/vm/infer.lua
blob: 3a89c4c865870e0cdafcb4b5661270ae5ea75535 (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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
local util     = require 'utility'
local config   = require 'config'
local guide    = require 'parser.guide'
---@class vm
local vm       = require 'vm.vm'

---@class vm.infer
---@field views table<string, boolean>
---@field cachedView? string
---@field node? vm.node
---@field _drop table
local mt = {}
mt.__index = mt
mt._hasTable       = false
mt._hasClass       = false
mt._hasFunctionDef = false
mt._hasDocFunction = false
mt._isParam        = false
mt._isLocal        = false

vm.NULL = setmetatable({}, mt)

local LOCK = {}

local inferSorted = {
    ['boolean']  = - 100,
    ['string']   = - 99,
    ['number']   = - 98,
    ['integer']  = - 97,
    ['function'] = - 96,
    ['table']    = - 95,
    ['true']     = 1,
    ['false']    = 2,
    ['nil']      = 100,
}

local viewNodeSwitch;viewNodeSwitch = util.switch()
    : case 'nil'
    : case 'boolean'
    : case 'string'
    : case 'integer'
    : call(function (source, infer)
        return source.type
    end)
    : case 'number'
    : call(function (source, infer)
        return source.type
    end)
    : case 'table'
    : call(function (source, infer, uri)
        if source.type == 'table' then
            if #source == 1 and source[1].type == 'varargs' then
                local node = vm.getInfer(source[1]):view(uri)
                return ('%s[]'):format(node)
            end
        end

        infer._hasTable = true
    end)
    : case 'function'
    : call(function (source, infer)
        local parent = source.parent
        if guide.isSet(parent) then
            infer._hasFunctionDef = true
        end
        return source.type
    end)
    : case 'local'
    : call(function (source, infer)
        if source.parent == 'funcargs' then
            infer._isParam = true
        else
            infer._isLocal = true
        end
    end)
    : case 'global'
    : call(function (source, infer)
        if source.cate == 'type' then
            if not guide.isBasicType(source.name) then
                infer._hasClass = true
            end
            return source.name
        end
    end)
    : case 'doc.type'
    : call(function (source, infer, uri)
        local buf = {}
        for _, tp in ipairs(source.types) do
            buf[#buf+1] = viewNodeSwitch(tp.type, tp, infer, uri)
        end
        return table.concat(buf, '|')
    end)
    : case 'doc.type.name'
    : call(function (source, infer, uri)
        if source.signs then
            local buf = {}
            for i, sign in ipairs(source.signs) do
                buf[i] = vm.getInfer(sign):view(uri)
            end
            return ('%s<%s>'):format(source[1], table.concat(buf, ', '))
        else
            return source[1]
        end
    end)
    : case 'generic'
    : call(function (source, infer, uri)
        return vm.getInfer(source.proto):view(uri)
    end)
    : case 'doc.generic.name'
    : call(function (source, infer, uri)
        local resolved = vm.getGenericResolved(source)
        if resolved then
            return vm.getInfer(resolved):view(uri)
        end
        if source.generic and source.generic.extends then
            return ('<%s:%s>'):format(source[1], vm.getInfer(source.generic.extends):view(uri))
        else
            return ('<%s>'):format(source[1])
        end
    end)
    : case 'doc.type.array'
    : call(function (source, infer, uri)
        infer._hasClass = true
        local view = vm.getInfer(source.node):view(uri)
        if source.node.type == 'doc.type' then
            view = '(' .. view .. ')'
        end
        return view .. '[]'
    end)
    : case 'doc.type.sign'
    : call(function (source, infer, uri)
        infer._hasClass = true
        local buf = {}
        for i, sign in ipairs(source.signs) do
            buf[i] = vm.getInfer(sign):view(uri)
        end
        local node = vm.compileNode(source)
        for c in node:eachObject() do
            if guide.isLiteral(c) then
                local view = vm.viewObject(c, uri)
                if view then
                    infer._drop[view] = true
                end
            end
        end
        return ('%s<%s>'):format(source.node[1], table.concat(buf, ', '))
    end)
    : case 'doc.type.table'
    : call(function (source, infer, uri)
        if #source.fields == 0 then
            infer._hasTable = true
            return
        end
        infer._hasClass = true
        local buf = {}
        buf[#buf+1] = '{ '
        for i, field in ipairs(source.fields) do
            if i > 1 then
                buf[#buf+1] = ', '
            end
            local key = field.name
            if key.type == 'doc.type' then
                buf[#buf+1] = ('[%s]: '):format(vm.getInfer(key):view(uri))
            elseif type(key[1]) == 'string' then
                buf[#buf+1] = key[1] .. ': '
            else
                buf[#buf+1] = ('[%q]: '):format(key[1])
            end
            buf[#buf+1] = vm.getInfer(field.extends):view(uri)
        end
        buf[#buf+1] = ' }'
        return table.concat(buf)
    end)
    : case 'doc.type.string'
    : call(function (source, infer)
        return util.viewString(source[1], source[2])
    end)
    : case 'doc.type.integer'
    : case 'doc.type.boolean'
    : call(function (source, infer)
        return ('%q'):format(source[1])
    end)
    : case 'doc.type.code'
    : call(function (source, infer)
        return ('`%s`'):format(source[1])
    end)
    : case 'doc.type.function'
    : call(function (source, infer, uri)
        infer._hasDocFunction = true
        local args = {}
        local rets = {}
        local argView = ''
        local regView = ''
        for i, arg in ipairs(source.args) do
            local argNode = vm.compileNode(arg)
            local isOptional = argNode:isOptional()
            if isOptional then
                argNode = argNode:copy()
                argNode:removeOptional()
            end
            args[i] = string.format('%s%s%s%s'
                , arg.name[1]
                , isOptional and '?' or ''
                , arg.name[1] == '...' and '' or ': '
                , vm.getInfer(argNode):view(uri)
            )
        end
        if #args > 0 then
            argView = table.concat(args, ', ')
        end
        local needReturnParen
        for i, ret in ipairs(source.returns) do
            local retType = vm.getInfer(ret):view(uri)
            if ret.name then
                if ret.name[1] == '...' then
                    rets[i] = ('%s%s'):format(ret.name[1], retType)
                else
                    needReturnParen = true
                    rets[i] = ('%s: %s'):format(ret.name[1], retType)
                end
            else
                rets[i] = retType
            end
        end
        if #rets > 0 then
            if needReturnParen then
                regView = (':(%s)'):format(table.concat(rets, ', '))
            else
                regView = (':%s'):format(table.concat(rets, ', '))
            end
        end
        return ('fun(%s)%s'):format(argView, regView)
    end)
    : case 'doc.field.name'
    : call(function (source, infer, uri)
        return vm.viewKey(source, uri)
    end)

---@class vm.node
---@field lastInfer? vm.infer

---@param source vm.object | vm.node
---@return vm.infer
function vm.getInfer(source)
    ---@type vm.node
    local node
    if source.type == 'vm.node' then
        ---@cast source vm.node
        node = source
    else
        ---@cast source vm.object
        node = vm.compileNode(source)
    end
    if node.lastInfer then
        return node.lastInfer
    end
    local infer = setmetatable({
        node  = node,
        _drop = {},
    }, mt)
    node.lastInfer = infer

    return infer
end

function mt:_trim()
    if self._hasDocFunction then
        if self._hasFunctionDef then
            for view in pairs(self.views) do
                if view:sub(1, 4) == 'fun(' then
                    self.views[view] = nil
                end
            end
        else
            self.views['function'] = nil
        end
    end
    if self._hasTable and not self._hasClass then
        self.views['table'] = true
    end
    if self.views['number'] then
        self.views['integer'] = nil
    end
    if self.views['boolean'] then
        self.views['true'] = nil
        self.views['false'] = nil
    end
end

---@param uri uri
function mt:_eraseAlias(uri)
    local expandAlias = config.get(uri, 'Lua.hover.expandAlias')
    for n in self.node:eachObject() do
        if n.type == 'global' and n.cate == 'type' then
            if LOCK[n.name] then
                goto CONTINUE
            end
            LOCK[n.name] = true
            for _, set in ipairs(n:getSets(uri)) do
                if set.type == 'doc.alias' then
                    if expandAlias then
                        self._drop[n.name] = true
                        local newInfer = setmetatable({
                            _drop = {},
                        }, mt)
                        for _, ext in ipairs(set.extends.types) do
                            viewNodeSwitch(ext.type, ext, newInfer, uri)
                        end
                        if newInfer._hasTable then
                            self.views['table'] = true
                        end
                    else
                        for _, ext in ipairs(set.extends.types) do
                            local view = viewNodeSwitch(ext.type, ext, {}, uri)
                            if view and view ~= n.name then
                                self._drop[view] = true
                            end
                        end
                    end
                end
            end
            LOCK[n.name] = nil
            ::CONTINUE::
        end
    end
end

---@param uri uri
---@param tp string
---@return boolean
function mt:hasType(uri, tp)
    self:_computeViews(uri)
    return self.views[tp] == true
end

---@param uri uri
function mt:hasUnknown(uri)
    self:_computeViews(uri)
    return not next(self.views)
        or self.views['unknown'] == true
end

---@param uri uri
function mt:hasAny(uri)
    self:_computeViews(uri)
    return self.views['any'] == true
end

---@param uri uri
---@return boolean
function mt:hasClass(uri)
    self:_computeViews(uri)
    return self._hasClass == true
end

---@param uri uri
---@return boolean
function mt:hasFunction(uri)
    self:_computeViews(uri)
    return self.views['function'] == true
        or self._hasDocFunction   == true
end

---@param uri uri
function mt:_computeViews(uri)
    if self.views then
        return
    end

    self.views = {}

    for n in self.node:eachObject() do
        local view = viewNodeSwitch(n.type, n, self, uri)
        if view then
            self.views[view] = true
        end
    end

    self:_trim()
end

---@param uri uri
---@param default? string
---@return string
function mt:view(uri, default)
    self:_computeViews(uri)

    if self.views['any'] then
        return 'any'
    end

    if self._hasClass then
        self:_eraseAlias(uri)
    end

    local array = {}
    for view in pairs(self.views) do
        if not self._drop[view] then
            array[#array+1] = view
        end
    end

    table.sort(array, function (a, b)
        local sa = inferSorted[a] or 0
        local sb = inferSorted[b] or 0
        if sa == sb then
            return a < b
        end
        return sa < sb
    end)

    local max   = #array
    local limit = config.get(uri, 'Lua.hover.enumsLimit')

    local view
    if #array == 0 then
        view = default or 'unknown'
    else
        if max > limit then
            view = string.format('%s...(+%d)'
                , table.concat(array, '|', 1, limit)
                , max - limit
            )
        else
            view = table.concat(array, '|')
        end
    end

    if self.node:isOptional() then
        if #array == 0 then
            view = 'nil'
        else
            if max > 1 then
                view = '(' .. view .. ')?'
            else
                view = view .. '?'
            end
        end
    end

    return view
end

---@param uri uri
function mt:eachView(uri)
    self:_computeViews(uri)
    return next, self.views
end

---@param other vm.infer
---@return vm.infer
function mt:merge(other)
    if self == vm.NULL then
        return other
    end
    if other == vm.NULL then
        return self
    end

    local infer = setmetatable({
        node  = vm.createNode(self.node, other.node),
    }, mt)

    return infer
end

---@return string?
function mt:viewLiterals()
    if not self.node then
        return nil
    end
    local mark     = {}
    local literals = {}
    for n in self.node:eachObject() do
        if n.type == 'string'
        or n.type == 'number'
        or n.type == 'integer'
        or n.type == 'boolean' then
            local literal = util.viewLiteral(n[1])
            if literal and not mark[literal] then
                literals[#literals+1] = literal
                mark[literal] = true
            end
        end
    end
    if #literals == 0 then
        return nil
    end
    table.sort(literals, function (a, b)
        local sa = inferSorted[a] or 0
        local sb = inferSorted[b] or 0
        if sa == sb then
            return a < b
        end
        return sa < sb
    end)
    return table.concat(literals, '|')
end

---@return string?
function mt:viewClass()
    if not self.node then
        return nil
    end
    local mark  = {}
    local class = {}
    for n in self.node:eachObject() do
        if n.type == 'global' and n.cate == 'type' then
            local name = n.name
            if not mark[name] then
                class[#class+1] = name
                mark[name] = true
            end
        end
    end
    if #class == 0 then
        return nil
    end
    table.sort(class)
    return table.concat(class, '|')
end

---@param source vm.node.object
---@param uri uri
---@return string?
function vm.viewObject(source, uri)
    local infer = setmetatable({
        _drop = {},
    }, mt)
    return viewNodeSwitch(source.type, source, infer, uri)
end

---@param source parser.object
---@param uri uri
---@return string?
---@return string|number|boolean|nil
function vm.viewKey(source, uri)
    if source.type == 'doc.type' then
        if #source.types == 1 then
            return vm.viewKey(source.types[1], uri)
        else
            local key = vm.viewObject(source, uri)
            return '[' .. key .. ']'
        end
    end
    if source.type == 'tableindex' then
        local index = source.index
        local name = vm.getKeyName(index)
        if not name then
            return nil
        end
        local key
        if index.type == 'string' then
            key = util.viewString(name, index[2])
        else
            key = util.viewLiteral(name)
        end
        return ('[%s]'):format(key), name
    end
    if source.type == 'tableexp' then
        return ('[%d]'):format(source.tindex), source.tindex
    end
    if source.type == 'doc.field' then
        return vm.viewKey(source.field, uri)
    end
    if source.type == 'doc.type.field' then
        return vm.viewKey(source.name, uri)
    end
    if source.type == 'doc.type.name' then
        return '[' .. source[1] .. ']'
    end
    local key = vm.getKeyName(source)
    if key == nil then
        return nil
    end
    if type(key) == 'string' then
        return key, key
    else
        return ('[%s]'):format(key), key
    end
end