summaryrefslogtreecommitdiff
path: root/script/core/completion/completion.lua
blob: 3a76472a0f3e58048793446a1801a4490d62ac6d (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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
local define       = require 'proto.define'
local files        = require 'files'
local matchKey     = require 'core.matchkey'
local vm           = require 'vm'
local getName      = require 'core.hover.name'
local getArgs      = require 'core.hover.args'
local getHover     = require 'core.hover'
local config       = require 'config'
local util         = require 'utility'
local markdown     = require 'provider.markdown'
local parser       = require 'parser'
local keyWordMap   = require 'core.completion.keyword'
local workspace    = require 'workspace'
local furi         = require 'file-uri'
local rpath        = require 'workspace.require-path'
local lang         = require 'language'
local lookBackward = require 'core.look-backward'
local guide        = require 'parser.guide'
local await        = require 'await'
local postfix      = require 'core.completion.postfix'
local diag         = require 'proto.diagnostic'
local wssymbol     = require 'core.workspace-symbol'
local findSource   = require 'core.find-source'
local diagnostic   = require 'provider.diagnostic'
local autoRequire  = require 'core.completion.auto-require'

local diagnosticModes = {
    'disable-next-line',
    'disable-line',
    'disable',
    'enable',
}

local stackID = 0
local stacks = {}

---@param callback async fun(newSource: parser.object): table
local function stack(oldSource, callback)
    stackID = stackID + 1
    local uri = guide.getUri(oldSource)
    local pos = oldSource.start
    local tp  = oldSource.type
    ---@async
    stacks[stackID] = function ()
        local state = files.getState(uri)
        if not state then
            return
        end
        local newSource = findSource(state, pos, { [tp] = true })
        if not newSource then
            return
        end
        return callback(newSource)
    end
    return stackID
end

local function clearStack()
    stacks = {}
end

---@async
local function resolveStack(id)
    local callback = stacks[id]
    if not callback then
        log.warn('Unknown resolved id', id)
        return nil
    end

    return callback()
end

local function trim(str)
    return str:match '^%s*(%S+)%s*$'
end

local function findNearestSource(state, position)
    ---@type parser.object
    local source
    guide.eachSourceContain(state.ast, position, function (src)
        source = src
    end)
    return source
end

local function findNearestTable(state, position)
    local uri  = state.uri
    local text = files.getText(uri)
    if not text then
        return nil
    end
    local offset  = guide.positionToOffset(state, position)
    local soffset = lookBackward.findAnyOffset(text, offset)
    if not soffset then
        return nil
    end
    local symbol = text:sub(soffset, soffset)
    if symbol == '}' then
        return nil
    end
    local sposition = guide.offsetToPosition(state, soffset)
    local source
    guide.eachSourceContain(state.ast, sposition, function (src)
        if src.type == 'table' then
            source = src
        end
    end)

    if not source then
        return nil
    end

    for _, field in ipairs(source) do
        if field.start <= position and (field.range or field.finish) >= position then
            if field.type == 'tableexp' then
                if field.value.type == 'getlocal'
                or field.value.type == 'getglobal' then
                    if field.finish >= position then
                        return source
                    else
                        return nil
                    end
                end
            end
            if field.type == 'tablefield' then
                if field.finish >= position then
                    return source
                else
                    return nil
                end
            end
            if field.type == 'tableindex' then
                if field.index and field.index.type == 'string' then
                    if field.index.finish >= position then
                        return source
                    else
                        return nil
                    end
                end
            end
            return nil
        end
    end

    return source
end

local function findParent(state, position)
    local text = state.lua
    if not text then
        return
    end
    local offset = guide.positionToOffset(state, position)
    for i = offset, 1, -1 do
        local char = text:sub(i, i)
        if lookBackward.isSpace(char) then
            goto CONTINUE
        end
        local oop
        if     char == '.' then
            -- `..` 的情况
            if text:sub(i - 1, i - 1) == '.' then
                return nil, nil
            end
            oop = false
        elseif char == ':' then
            oop = true
        else
            return nil, nil
        end
        local anyOffset = lookBackward.findAnyOffset(text, i - 1)
        if not anyOffset then
            return nil, nil
        end
        local anyPos = guide.offsetToPosition(state, anyOffset)
        local parent = guide.eachSourceContain(state.ast, anyPos, function (source)
            if source.finish == anyPos then
                return source
            end
        end)
        if parent then
            return parent, oop
        end
        ::CONTINUE::
    end
    return nil, nil
end

local function findParentInStringIndex(state, position)
    local near, nearStart
    guide.eachSourceContain(state.ast, position, function (source)
        local start = guide.getStartFinish(source)
        if not start then
            return
        end
        if not nearStart or nearStart < start then
            near = source
            nearStart = start
        end
    end)
    if not near or near.type ~= 'string' then
        return
    end
    local parent = near.parent
    if not parent or parent.index ~= near then
        return
    end
    -- index不可能是oop模式
    return parent.node, false
end

local function buildFunctionSnip(source, value, oop)
    local name = (getName(source) or ''):gsub('^.+[$.:]', '')
    local args = getArgs(value)
    if oop then
        table.remove(args, 1)
    end

    local snipArgs = {}
    for id, arg in ipairs(args) do
        local str, count = arg:gsub('^(%s*)(%.%.%.)(.+)', function (sp, word)
            return ('%s${%d:%s}'):format(sp, id, word)
        end)
        if count == 0 then
            str = arg:gsub('^(%s*)([^:]+)(.+)', function (sp, word)
                return ('%s${%d:%s}'):format(sp, id, word)
            end)
        end
        table.insert(snipArgs, str)
    end
    return ('%s(%s)'):format(name, table.concat(snipArgs, ', '))
end

local function buildDetail(source)
    local types = vm.getInfer(source):view(guide.getUri(source))
    local literals = vm.getInfer(source):viewLiterals()
    if literals then
        return types .. ' = ' .. literals
    else
        return types
    end
end

local function getSnip(source)
    local context = config.get(guide.getUri(source), 'Lua.completion.displayContext')
    if context <= 0 then
        return nil
    end
    local defs = vm.getDefs(source)
    for _, def in ipairs(defs) do
        if def ~= source and def.type == 'function' then
            local uri = guide.getUri(def)
            local text = files.getText(uri)
            local state = files.getState(uri)
            if not state then
                goto CONTINUE
            end
            local lines = state.lines
            if not text then
                goto CONTINUE
            end
            if vm.isMetaFile(uri) then
                goto CONTINUE
            end
            local firstRow   = guide.rowColOf(def.start)
            local lastRow    = math.min(guide.rowColOf(def.finish) + 1, firstRow + context)
            local lastOffset = lines[lastRow] and (lines[lastRow] - 1) or #text
            local snip       = text:sub(lines[firstRow], lastOffset)
            return snip
        end
        ::CONTINUE::
    end
end

---@async
local function buildDesc(source)
    local desc = markdown()
    local hover = getHover.get(source)
    desc:add('md', hover)
    desc:splitLine()
    desc:add('lua', getSnip(source))
    return desc
end

local function buildFunction(results, source, value, oop, data)
    local snipType = config.get(guide.getUri(source), 'Lua.completion.callSnippet')
    if snipType == 'Disable' or snipType == 'Both' then
        results[#results+1] = data
    end
    if snipType == 'Both' or snipType == 'Replace' then
        local snipData = util.deepCopy(data)

        snipData.kind             = snipType == 'Both'
                                    and define.CompletionItemKind.Snippet
                                    or  data.kind
        snipData.insertText       = buildFunctionSnip(source, value, oop)
        snipData.insertTextFormat = 2
        snipData.command          = {
            title = 'trigger signature',
            command = 'editor.action.triggerParameterHints',
        }
        snipData.id               = stack(source, function (newSource) ---@async
            return {
                detail      = buildDetail(newSource),
                description = buildDesc(newSource),
            }
        end)

        results[#results+1] = snipData
    end
end

local function isSameSource(state, source, pos)
    if guide.getUri(source) ~= guide.getUri(state.ast) then
        return false
    end
    if source.type == 'field'
    or source.type == 'method' then
        source = source.parent
    end
    return source.start <= pos and source.finish >= pos
end

local function getParams(func, oop)
    if not func.args then
        return '()'
    end
    local args = {}
    for _, arg in ipairs(func.args) do
        if     arg.type == '...' then
            args[#args+1] = '...'
        elseif arg.type == 'doc.type.arg' then
            args[#args+1] = arg.name[1]
        else
            args[#args+1] = arg[1]
        end
    end
    if oop and args[1] ~= '...' then
        table.remove(args, 1)
    end
    return '(' .. table.concat(args, ', ') .. ')'
end

local function checkLocal(state, word, position, results)
    local locals = guide.getVisibleLocals(state.ast, position)
    for name, source in util.sortPairs(locals) do
        if isSameSource(state, source, position) then
            goto CONTINUE
        end
        if not matchKey(word, name) then
            goto CONTINUE
        end
        if name:sub(1, 1) == '@' then
            goto CONTINUE
        end
        if vm.getInfer(source):hasFunction(state.uri) then
            local defs = vm.getDefs(source)
            -- make sure `function` is before `doc.type.function`
            local orders = {}
            for i, def in ipairs(defs) do
                if def.type == 'function' then
                    orders[def] = i - 20000
                elseif def.type == 'doc.type.function' then
                    orders[def] = i - 10000
                else
                    orders[def] = i
                end
            end
            table.sort(defs, function (a, b)
                return orders[a] < orders[b]
            end)
            for _, def in ipairs(defs) do
                if (def.type == 'function' and not vm.isVarargFunctionWithOverloads(def))
                or def.type == 'doc.type.function' then
                    local funcLabel = name .. getParams(def, false)
                    buildFunction(results, source, def, false, {
                        label      = funcLabel,
                        match      = name,
                        insertText = name,
                        kind       = define.CompletionItemKind.Function,
                        id         = stack(source, function (newSource) ---@async
                            return {
                                detail      = buildDetail(newSource),
                                description = buildDesc(newSource),
                            }
                        end),
                    })
                end
            end
        else
            results[#results+1] = {
                label  = name,
                kind   = define.CompletionItemKind.Variable,
                id     = stack(source, function (newSource) ---@async
                    return {
                        detail      = buildDetail(newSource),
                        description = buildDesc(newSource),
                    }
                end),
            }
        end
        ::CONTINUE::
    end
end

local function checkModule(state, word, position, results)
    if not config.get(state.uri, 'Lua.completion.autoRequire') then
        return
    end
    autoRequire.check(state, word, position, function (uri, stemName, targetSource)
        results[#results+1] = {
            label            = stemName,
            kind             = define.CompletionItemKind.Variable,
            commitCharacters = { '.' },
            command          = {
                title     = 'autoRequire',
                command   = 'lua.autoRequire',
                arguments = {
                    {
                        uri    = guide.getUri(state.ast),
                        target = uri,
                        name   = stemName,
                    },
                },
            },
            id               = stack(targetSource, function (newSource) ---@async
                local md = markdown()
                md:add('md', lang.script('COMPLETION_IMPORT_FROM', ('[%s](%s)'):format(
                    workspace.getRelativePath(uri),
                    uri
                )))
                md:add('md', buildDesc(newSource))
                return {
                    detail      = buildDetail(newSource),
                    description = md,
                    --additionalTextEdits = buildInsertRequire(state, originUri, stemName),
                }
            end)
        }
    end)
end

local function checkFieldFromFieldToIndex(state, name, src, parent, word, startPos, position)
    if name:match(guide.namePatternFull) then
        if not name:match '[\x80-\xff]'
        or config.get(state.uri, 'Lua.runtime.unicodeName') then
            return nil
        end
        name = ('%q'):format(name)
    end
    local textEdit, additionalTextEdits
    local startOffset = guide.positionToOffset(state, startPos)
    local offset      = guide.positionToOffset(state, position)
    local wordStartOffset
    if word == '' then
        wordStartOffset = state.lua:match('()%S', startOffset + 1)
        if wordStartOffset then
            wordStartOffset = wordStartOffset - 1
        else
            wordStartOffset = offset
        end
    else
        wordStartOffset = offset - #word
    end
    local wordStartPos = guide.offsetToPosition(state, wordStartOffset)
    local newText = ('[%s]'):format(name)
    textEdit = {
        start   = wordStartPos,
        finish  = position,
        newText = newText,
    }
    local nxt = parent.next
    if nxt then
        local dotStart, dotFinish
        if     nxt.type == 'setfield'
        or     nxt.type == 'getfield'
        or     nxt.type == 'tablefield' then
            dotStart = nxt.dot.start
            dotFinish = nxt.dot.finish
        elseif nxt.type == 'setmethod'
        or     nxt.type == 'getmethod' then
            dotStart = nxt.colon.start
            dotFinish = nxt.colon.finish
        end
        if dotStart then
            additionalTextEdits = {
                {
                    start   = dotStart,
                    finish  = dotFinish,
                    newText = '',
                }
            }
        end
    else
        if config.get(state.uri, 'Lua.runtime.version') == 'Lua 5.1'
        or config.get(state.uri, 'Lua.runtime.version') == 'LuaJIT' then
            textEdit.newText = '_G' .. textEdit.newText
        else
            textEdit.newText = '_ENV' .. textEdit.newText
        end
    end
    return textEdit, additionalTextEdits
end

local function checkFieldThen(state, name, src, word, startPos, position, parent, oop, results)
    local value = vm.getObjectFunctionValue(src) or src
    local kind = define.CompletionItemKind.Field
    if (value.type == 'function' and not vm.isVarargFunctionWithOverloads(value))
    or value.type == 'doc.type.function' then
        local isMethod = value.parent.type == 'setmethod'
        if isMethod then
            kind = define.CompletionItemKind.Method
        else
            kind = define.CompletionItemKind.Function
        end
        buildFunction(results, src, value, oop, {
            label      = name,
            kind       = kind,
            isMethod   = isMethod,
            match      = name:match '^[^(]+',
            insertText = name:match '^[^(]+',
            deprecated = vm.getDeprecated(src) and true or nil,
            id         = stack(src, function (newSrc) ---@async
                return {
                    detail      = buildDetail(newSrc),
                    description = buildDesc(newSrc),
                }
            end),
        })
        return
    end
    if oop and not vm.getInfer(src):hasFunction(state.uri) then
        return
    end
    local literal = guide.getLiteral(value)
    if literal ~= nil then
        kind = define.CompletionItemKind.Enum
    end
    local textEdit, additionalTextEdits
    if parent.next and parent.next.index then
        local str = parent.next.index
        textEdit = {
            start   = str.start + #str[2],
            finish  = position,
            newText = name:sub(#str[2] + 1, - #str[2] - 1),
        }
    else
        textEdit, additionalTextEdits = checkFieldFromFieldToIndex(state, name, src, parent, word, startPos, position)
    end
    results[#results+1] = {
        label      = name,
        kind       = kind,
        deprecated = vm.getDeprecated(src) and true or nil,
        textEdit   = textEdit,
        id         = stack(src, function (newSrc) ---@async
            return {
                detail      = buildDetail(newSrc),
                description = buildDesc(newSrc),
            }
        end),

        additionalTextEdits = additionalTextEdits,
    }
end

---@async
local function checkFieldOfRefs(refs, state, word, startPos, position, parent, oop, results, locals, isGlobal)
    local fields = {}
    local funcs  = {}
    local count  = 0
    for _, src in ipairs(refs) do
        if count > 100 then
            results.incomplete = true
            break
        end
        local _, name = vm.viewKey(src, state.uri)
        if not name then
            goto CONTINUE
        end
        if isSameSource(state, src, startPos) then
            goto CONTINUE
        end
        name = tostring(name)
        if isGlobal and locals and locals[name] then
            goto CONTINUE
        end
        if not matchKey(word, name:gsub([=[^['"]]=], ''), count >= 100) then
            goto CONTINUE
        end
        if not vm.isVisible(parent, src) then
            goto CONTINUE
        end
        local funcLabel
        if config.get(state.uri, 'Lua.completion.showParams') then
            --- TODO determine if getlocal should be a function here too
            local value = vm.getObjectFunctionValue(src) or src
            if value.type == 'function'
            or value.type == 'doc.type.function' then
                if not vm.isVarargFunctionWithOverloads(value) then
                    funcLabel = name .. getParams(value, oop)
                    fields[funcLabel] = src
                    count = count + 1
                end
                if value.type == 'function' and value.bindDocs then
                    for _, doc in ipairs(value.bindDocs) do
                        if doc.type == 'doc.overload' then
                            funcLabel = name .. getParams(doc.overload, oop)
                            fields[funcLabel] = doc.overload
                        end
                    end
                end
                funcs[name] = true
                if fields[name] and not guide.isAssign(fields[name]) then
                    fields[name] = nil
                end
                goto CONTINUE
            end
        end
        local last = fields[name]
        if last == nil and not funcs[name] then
            fields[name] = src
            count = count + 1
            goto CONTINUE
        end
        if vm.getDeprecated(src) then
            goto CONTINUE
        end
        if guide.isAssign(src) then
            fields[name] = src
            goto CONTINUE
        end
        ::CONTINUE::
    end

    local fieldResults = {}
    for name, src in util.sortPairs(fields) do
        if src then
            checkFieldThen(state, name, src, word, startPos, position, parent, oop, fieldResults)
            await.delay()
        end
    end

    local scoreMap = {}
    for i, res in ipairs(fieldResults) do
        scoreMap[res] = i
    end
    table.sort(fieldResults, function (a, b)
        local score1 = scoreMap[a]
        local score2 = scoreMap[b]
        if oop then
            if not a.isMethod then
                score1 = score1 + 10000
            end
            if not b.isMethod then
                score2 = score2 + 10000
            end
        else
            if a.isMethod then
                score1 = score1 + 10000
            end
            if b.isMethod then
                score2 = score2 + 10000
            end
        end
        return score1 < score2
    end)

    for _, res in ipairs(fieldResults) do
        results[#results+1] = res
    end
end

---@async
local function checkGlobal(state, word, startPos, position, parent, oop, results)
    local locals = guide.getVisibleLocals(state.ast, position)
    local globals = vm.getGlobalSets(state.uri, 'variable')
    checkFieldOfRefs(globals, state, word, startPos, position, parent, oop, results, locals, 'global')
end

---@async
---@param parent parser.object
local function checkField(state, word, start, position, parent, oop, results)
    if parent.tag == '_ENV' or parent.special == '_G' then
        local globals = vm.getGlobalSets(state.uri, 'variable')
        checkFieldOfRefs(globals, state, word, start, position, parent, oop, results)
    else
        local refs = vm.getFields(parent)
        checkFieldOfRefs(refs, state, word, start, position, parent, oop, results)
    end
end

local function checkTableField(state, word, start, results)
    local source = guide.eachSourceContain(state.ast, start, function (source)
        if  source.start == start
        and source.parent
        and source.parent.type == 'table' then
            return source
        end
    end)
    if not source then
        return
    end
    local used = {}
    guide.eachSourceType(state.ast, 'tablefield', function (src)
        if not src.field then
            return
        end
        local key = src.field[1]
        if  not used[key]
        and matchKey(word, key)
        and src ~= source then
            used[key] = true
            results[#results+1] = {
                label = key,
                kind  = define.CompletionItemKind.Property,
            }
        end
    end)
end

local function checkCommon(state, word, position, results)
    local myUri = state.uri
    local showWord = config.get(state.uri, 'Lua.completion.showWord')
    if showWord == 'Disable' then
        return
    end
    results.enableCommon = true
    if showWord == 'Fallback' and #results ~= 0 then
        return
    end
    local used = {}
    for _, result in ipairs(results) do
        used[result.label:match '^[^(]*'] = true
    end
    for _, data in ipairs(keyWordMap) do
        used[data[1]] = true
    end
    if config.get(state.uri, 'Lua.completion.workspaceWord') and #word >= 2 then
        local myHead = word:sub(1, 2)
        for uri in files.eachFile(state.uri) do
            if #results >= 100 then
                results.incomplete = true
                break
            end
            if myUri == uri then
                goto CONTINUE
            end
            local words = files.getWordsOfHead(uri, myHead)
            if not words then
                goto CONTINUE
            end
            for _, str in ipairs(words) do
                if #results >= 100 then
                    break
                end
                if  not used[str]
                and str ~= word then
                    used[str] = true
                    if matchKey(word, str) then
                        results[#results+1] = {
                            label = str,
                            kind  = define.CompletionItemKind.Text,
                        }
                    end
                end
            end
            ::CONTINUE::
        end
        for uri in files.eachDll() do
            if #results >= 100 then
                break
            end
            local words = files.getDllWords(uri) or {}
            for _, str in ipairs(words) do
                if #results >= 100 then
                    break
                end
                if #str >= 3 and not used[str] and str ~= word then
                    used[str] = true
                    if matchKey(word, str) then
                        results[#results+1] = {
                            label = str,
                            kind  = define.CompletionItemKind.Text,
                        }
                    end
                end
            end
        end
    end
    for str, offset in state.lua:gmatch('(' .. guide.namePattern .. ')()') do
        if #results >= 100 then
            results.incomplete = true
            break
        end
        if  #str >= 3
        and not used[str]
        and guide.offsetToPosition(state, offset - 1) ~= position then
            used[str] = true
            if matchKey(word, str) then
                results[#results+1] = {
                    label = str,
                    kind  = define.CompletionItemKind.Text,
                }
            end
        end
    end
end

local function checkKeyWord(state, start, position, word, hasSpace, afterLocal, results)
    local text = state.lua
    local snipType = config.get(state.uri, 'Lua.completion.keywordSnippet')
    local symbol = lookBackward.findSymbol(text, guide.positionToOffset(state, start))
    local isExp = symbol == '(' or symbol == ',' or symbol == '=' or symbol == '[' or symbol == '{'
    local info = {
        hasSpace = hasSpace,
        isExp    = isExp,
        text     = text,
        start    = start,
        uri      = guide.getUri(state.ast),
        position = position,
        state    = state,
    }
    for _, data in ipairs(keyWordMap) do
        local key = data[1]
        local eq
        if hasSpace then
            eq = word == key
        else
            eq = matchKey(word, key)
        end
        if afterLocal and key ~= 'function' then
            eq = false
        end
        if not eq then
            goto CONTINUE
        end
        if isExp then
            if  key ~= 'nil'
            and key ~= 'true'
            and key ~= 'false'
            and key ~= 'function' then
                goto CONTINUE
            end
        end
        local replaced
        local extra
        if snipType == 'Both' or snipType == 'Replace' then
            local func = data[2]
            if func then
                replaced = func(info, results)
                extra = true
            end
        end
        if snipType == 'Both' then
            replaced = false
        end
        if not replaced then
            if not hasSpace then
                local item = {
                    label = key,
                    kind  = define.CompletionItemKind.Keyword,
                }
                if #results > 0 and extra then
                    table.insert(results, #results, item)
                else
                    results[#results+1] = item
                end
            end
        end
        local checkStop = data[3]
        if checkStop then
            local stop = checkStop(info)
            if stop then
                return true
            end
        end
        ::CONTINUE::
    end
end

local function checkProvideLocal(state, word, start, results)
    local block
    guide.eachSourceContain(state.ast, start, function (source)
        if source.type == 'function'
        or source.type == 'main' then
            block = source
        end
    end)
    if not block then
        return
    end
    local used = {}
    guide.eachSourceType(block, 'getglobal', function (source)
        if source.start > start
        and not used[source[1]]
        and matchKey(word, source[1]) then
            used[source[1]] = true
            results[#results+1] = {
                label = source[1],
                kind  = define.CompletionItemKind.Variable,
            }
        end
    end)
    guide.eachSourceType(block, 'getlocal', function (source)
        if source.start > start
        and not used[source[1]]
        and matchKey(word, source[1]) then
            used[source[1]] = true
            results[#results+1] = {
                label = source[1],
                kind  = define.CompletionItemKind.Variable,
            }
        end
    end)
end

local function checkFunctionArgByDocParam(state, word, startPos, results)
    local func = guide.eachSourceContain(state.ast, startPos, function (source)
        if source.type == 'function' then
            return source
        end
    end)
    if not func then
        return
    end
    local docs = func.bindDocs
    if not docs then
        return
    end
    local params = {}
    for _, doc in ipairs(docs) do
        if doc.type == 'doc.param' then
            params[#params+1] = doc
        end
    end
    local firstArg = func.args and func.args[1]
    if not firstArg
    or firstArg.start <= startPos and firstArg.finish >= startPos then
        local firstParam = params[1]
        if firstParam and matchKey(word, firstParam.param[1]) then
            local label = {}
            for _, param in ipairs(params) do
                label[#label+1] = param.param[1]
            end
            results[#results+1] = {
                label = table.concat(label, ', '),
                match = firstParam.param[1],
                kind  = define.CompletionItemKind.Snippet,
            }
        end
    end
    for _, doc in ipairs(params) do
        if matchKey(word, doc.param[1]) then
            results[#results+1] = {
                label = doc.param[1],
                kind  = define.CompletionItemKind.Interface,
            }
        end
    end
end

local function isAfterLocal(state, text, startPos)
    local offset = guide.positionToOffset(state, startPos)
    local pos    = lookBackward.skipSpace(text, offset)
    local word   = lookBackward.findWord(text, pos)
    return word == 'local'
end

local function collectRequireNames(mode, myUri, literal, source, smark, position, results)
    local collect = {}
    local source_start   = source and smark and (source.start + #smark) or position
    local source_finish  = source and smark and (source.finish - #smark) or position
    if mode == 'require' then
        for uri in files.eachFile(myUri) do
            if myUri == uri then
                goto CONTINUE
            end
            local path = furi.decode(uri)
            local infos = rpath.getVisiblePath(myUri, path)
            local relative = workspace.getRelativePath(path)
            for _, info in ipairs(infos) do
                if matchKey(literal, info.name) then
                    if not collect[info.name] then
                        collect[info.name] = {
                            textEdit = {
                                start   = source_start,
                                finish  = source_finish,
                                newText = smark and info.name or util.viewString(info.name),
                            },
                            path = relative,
                        }
                    end
                    if vm.isMetaFile(uri) then
                        collect[info.name][#collect[info.name]+1] = ('* [[meta]](%s)'):format(uri)
                    else
                        collect[info.name][#collect[info.name]+1] = ([=[* [%s](%s) %s]=]):format(
                            relative,
                            uri,
                            lang.script('HOVER_USE_LUA_PATH', info.searcher)
                        )
                    end
                end
            end
            ::CONTINUE::
        end
        for uri in files.eachDll() do
            local opens = files.getDllOpens(uri) or {}
            local path = workspace.getRelativePath(uri)
            for _, open in ipairs(opens) do
                if matchKey(literal, open) then
                    if not collect[open] then
                        collect[open] = {
                            textEdit = {
                                start   = source_start,
                                finish  = source_finish,
                                newText = smark and open or util.viewString(open),
                            },
                            path = path,
                        }
                    end
                    collect[open][#collect[open]+1] = ([=[* [%s](%s)]=]):format(
                        path,
                        uri
                    )
                end
            end
        end
    else
        for uri in files.eachFile(myUri) do
            if myUri == uri then
                goto CONTINUE
            end
            if vm.isMetaFile(uri) then
                goto CONTINUE
            end
            local path = workspace.getRelativePath(uri)
            path = path:gsub('\\', '/')
            if matchKey(literal, path) then
                if not collect[path] then
                    collect[path] = {
                        textEdit = {
                            start   = source_start,
                            finish  = source_finish,
                            newText = smark and path or util.viewString(path),
                        }
                    }
                end
                collect[path][#collect[path]+1] = ([=[[%s](%s)]=]):format(
                    path,
                    uri
                )
            end
            ::CONTINUE::
        end
    end
    for label, infos in util.sortPairs(collect) do
        local mark = {}
        local des  = {}
        for _, info in ipairs(infos) do
            if not mark[info] then
                mark[info] = true
                des[#des+1] = info
            end
        end
        results[#results+1] = {
            label       = label,
            detail      = infos.path,
            kind        = define.CompletionItemKind.File,
            description = table.concat(des, '\n'),
            textEdit    = infos.textEdit,
        }
    end
end

local function checkUri(state, position, results)
    local myUri = guide.getUri(state.ast)
    guide.eachSourceContain(state.ast, position, function (source)
        if source.type ~= 'string' then
            return
        end
        local callargs = source.parent
        if not callargs or callargs.type ~= 'callargs' then
            return
        end
        if callargs[1] ~= source then
            return
        end
        local call = callargs.parent
        local func = call.node
        local literal = guide.getLiteral(source)
        local libName = vm.getLibraryName(func)
        if not libName then
            return
        end
        if libName == 'require'
        or libName == 'dofile'
        or libName == 'loadfile' then
            collectRequireNames(libName, myUri, literal, source, source[2], position, results)
        end
    end)
end

local function checkLenPlusOne(state, position, results)
    local text = state.lua
    if not text then
        return
    end
    guide.eachSourceContain(state.ast, position, function (source)
        if source.type == 'getindex'
        or source.type == 'setindex' then
            local finish = guide.positionToOffset(state, source.node.finish)
            local _, offset = text:find('%s*%[%s*%#', finish)
            if not offset then
                return
            end
            local start = guide.positionToOffset(state, source.node.start) + 1
            local nodeText = text:sub(start, finish)
            local writingText = trim(text:sub(offset + 1, guide.positionToOffset(state, position))) or ''
            if not matchKey(writingText, nodeText) then
                return
            end
            local offsetPos = guide.offsetToPosition(state, offset) - 1
            if source.parent == guide.getParentBlock(source) then
                local sourceFinish = guide.positionToOffset(state, source.finish)
                -- state
                local label = text:match('%#[ \t]*', offset) .. nodeText .. '+1'
                local eq = text:find('^%s*%]?%s*%=', sourceFinish)
                local newText = label .. ']'
                if not eq then
                    newText = newText .. ' = '
                end
                results[#results+1] = {
                    label    = label,
                    match    = nodeText,
                    kind     = define.CompletionItemKind.Snippet,
                    textEdit = {
                        start   = offsetPos,
                        finish  = source.finish,
                        newText = newText,
                    },
                }
            else
                -- exp
                local label = text:match('%#[ \t]*', offset) .. nodeText
                local newText = label .. ']'
                results[#results+1] = {
                    label    = label,
                    kind     = define.CompletionItemKind.Snippet,
                    textEdit = {
                        start   = offsetPos,
                        finish  = source.finish,
                        newText = newText,
                    },
                }
            end
        end
    end)
end

local function tryLabelInString(label, source)
    if not source or source.type ~= 'string' then
        return label
    end
    local state = parser.compile(label, 'String')
    if not state or not state.ast then
        return label
    end
    if not matchKey(source[1], state.ast[1]--[[@as string]]) then
        return nil
    end
    return util.viewString(state.ast[1], source[2])
end

local function cleanEnums(enums, source)
    for i = #enums, 1, -1 do
        local enum = enums[i]
        local label = tryLabelInString(enum.label, source)
        if label then
            enum.label    = label
            enum.textEdit = source and {
                start   = source.start,
                finish  = source.finish,
                newText = enum.insertText or label,
            }
        end
    end
    return enums
end

---@param state     parser.state
---@param pos       integer
---@param doc       vm.node.object
---@param enums     table[]
---@return table[]?
local function insertDocEnum(state, pos, doc, enums)
    local tbl = doc.bindSource
    if not tbl then
        return nil
    end
    local parent = tbl.parent
    local parentName
    if vm.getGlobalNode(parent) then
        parentName = vm.getGlobalNode(parent):getCodeName()
    else
        local locals = guide.getVisibleLocals(state.ast, pos)
        for _, loc in pairs(locals) do
            if util.arrayHas(vm.getDefs(loc), tbl) then
                parentName = loc[1]
                break
            end
        end
    end
    local valueEnums = {}
    for _, field in ipairs(tbl) do
        if field.type == 'tablefield'
        or field.type == 'tableindex' then
            if not field.value then
                goto CONTINUE
            end
            local key = guide.getKeyName(field)
            if not key then
                goto CONTINUE
            end
            if parentName then
                enums[#enums+1] = {
                    label  = parentName .. '.' .. key,
                    kind   = define.CompletionItemKind.EnumMember,
                    id     = stack(field, function (newField) ---@async
                        return {
                            detail      = buildDetail(newField),
                            description = buildDesc(newField),
                        }
                    end),
                }
            end
            for nd in vm.compileNode(field.value):eachObject() do
                if nd.type == 'boolean'
                or nd.type == 'number'
                or nd.type == 'integer'
                or nd.type == 'string' then
                    valueEnums[#valueEnums+1] = {
                        label  = util.viewLiteral(nd[1]),
                        kind   = define.CompletionItemKind.EnumMember,
                        id     = stack(field, function (newField) ---@async
                            return {
                                detail      = buildDetail(newField),
                                description = buildDesc(newField),
                            }
                        end),
                    }
                end
            end
            ::CONTINUE::
        end
    end
    for _, enum in ipairs(valueEnums) do
        enums[#enums+1] = enum
    end
    return enums
end

---@param state     parser.state
---@param pos       integer
---@param doc       vm.node.object
---@param enums     table[]
---@return table[]?
local function insertDocEnumKey(state, pos, doc, enums)
    local tbl = doc.bindSource
    if not tbl then
        return nil
    end
    local keyEnums = {}
    for _, field in ipairs(tbl) do
        if field.type == 'tablefield'
        or field.type == 'tableindex' then
            if not field.value then
                goto CONTINUE
            end
            local key = guide.getKeyName(field)
            if not key then
                goto CONTINUE
            end
            enums[#enums+1] = {
                label  = ('%q'):format(key),
                kind   = define.CompletionItemKind.EnumMember,
                id     = stack(field, function (newField) ---@async
                    return {
                        detail      = buildDetail(newField),
                        description = buildDesc(newField),
                    }
                end),
            }
            ::CONTINUE::
        end
    end
    for _, enum in ipairs(keyEnums) do
        enums[#enums+1] = enum
    end
    return enums
end

local function buildInsertDocFunction(doc)
    local args = {}
    for i, arg in ipairs(doc.args) do
        args[i] = ('${%d:%s}'):format(i, arg.name[1])
    end
    return ("\z
function (%s)\
\t$0\
end"):format(table.concat(args, ', '))
end

---@param state     parser.state
---@param pos       integer
---@param src       vm.node.object
---@param enums     table[]
---@param isInArray boolean?
---@param mark      table?
local function insertEnum(state, pos, src, enums, isInArray, mark)
    mark = mark or {}
    if mark[src] then
        return
    end
    mark[src] = true
    if src.type == 'doc.type.string'
    or src.type == 'doc.type.integer'
    or src.type == 'doc.type.boolean' then
        ---@cast src parser.object
        enums[#enums+1] = {
            label       = vm.getInfer(src):view(state.uri),
            description = src.comment,
            kind        = define.CompletionItemKind.EnumMember,
        }
    elseif src.type == 'doc.type.code' then
        enums[#enums+1] = {
            label       = src[1],
            description = src.comment,
            kind        = define.CompletionItemKind.EnumMember,
        }
    elseif src.type == 'doc.type.function' then
        ---@cast src parser.object
        local insertText = buildInsertDocFunction(src)
        local description
        if src.comment then
            description = src.comment
        else
            local descText = insertText:gsub('%$%{%d+:([^}]+)%}', function (val)
                return val
            end):gsub('%$%{?%d+%}?', '')
            description = markdown()
                : add('lua', descText)
                : string()
        end
        enums[#enums+1] = {
            label       = vm.getInfer(src):view(state.uri),
            description = description,
            kind        = define.CompletionItemKind.Function,
            insertText  = insertText,
        }
    elseif src.type == 'doc.enum' then
        ---@cast src parser.object
        if vm.docHasAttr(src, 'key') then
            insertDocEnumKey(state, pos, src, enums)
        else
            insertDocEnum(state, pos, src, enums)
        end
    elseif isInArray and src.type == 'doc.type.array' then
        for i, d in ipairs(vm.getDefs(src.node)) do
            insertEnum(state, pos, d, enums, isInArray, mark)
        end
    elseif src.type == 'global' and src.cate == 'type' then
        for _, set in ipairs(src:getSets(state.uri)) do
            if set.type == 'doc.enum' then
                insertEnum(state, pos, set, enums, isInArray, mark)
            end
        end
    end
end

local function checkTypingEnum(state, position, defs, str, results, isInArray)
    local enums = {}
    for _, def in ipairs(defs) do
        insertEnum(state, position, def, enums, isInArray)
    end
    cleanEnums(enums, str)
    for _, res in ipairs(enums) do
        results[#results+1] = res
    end
end

local function checkEqualEnumLeft(state, position, source, results, isInArray)
    if not source then
        return
    end
    local str = guide.eachSourceContain(state.ast, position, function (src)
        if src.type == 'string' then
            return src
        end
    end)
    local defs = vm.getDefs(source)
    checkTypingEnum(state, position, defs, str, results, isInArray)
end

local function checkEqualEnum(state, position, results)
    local text  = state.lua
    if not text then
        return
    end
    local start = lookBackward.findTargetSymbol(text, guide.positionToOffset(state, position), '=')
    if not start then
        return
    end
    local eqOrNeq
    if text:sub(start - 1, start - 1) == '='
    or text:sub(start - 1, start - 1) == '~' then
        start = start - 1
        eqOrNeq = true
    end
    start = lookBackward.skipSpace(text, start - 1)
    local source = findNearestSource(state, guide.offsetToPosition(state, start))
    if not source then
        return
    end
    if source.type == 'callargs' then
        source = source.parent
    end
    if source.type == 'call' and not eqOrNeq then
        return
    end
    checkEqualEnumLeft(state, position, source, results)
end

local function checkEqualEnumInString(state, position, results)
    local source = findNearestSource(state, position)
    local parent = source.parent
    if parent.type == 'binary' then
        if source ~= parent[2] then
            return
        end
        if not parent.op then
            return
        end
        if parent.op.type ~= '==' and parent.op.type ~= '~=' then
            return
        end
        checkEqualEnumLeft(state, position, parent[1], results)
    end
    if (parent.type == 'tableexp') then
        checkEqualEnumLeft(state, position, parent.parent.parent, results, true)
        return
    end
    if parent.type == 'local' then
        checkEqualEnumLeft(state, position, parent, results)
    end

    if parent.type == 'setlocal'
    or parent.type == 'setglobal'
    or parent.type == 'setfield'
    or parent.type == 'setindex' then
        checkEqualEnumLeft(state, position, parent.node, results)
    end
    if parent.type == 'tablefield'
    or parent.type == 'tableindex' then
        checkEqualEnumLeft(state, position, parent, results)
    end
end

local function isFuncArg(state, position)
    return guide.eachSourceContain(state.ast, position, function (source)
        if source.type == 'funcargs' then
            return true
        end
    end)
end

local function trySpecial(state, position, results)
    if guide.isInString(state.ast, position) then
        checkUri(state, position, results)
        checkEqualEnumInString(state, position, results)
        return
    end
    -- x[#x+1]
    checkLenPlusOne(state, position, results)
    -- type(o) ==
    checkEqualEnum(state, position, results)
end

---@async
local function tryIndex(state, position, results)
    local parent, oop = findParentInStringIndex(state, position)
    if not parent then
        return
    end
    local word = parent.next and parent.next.index and parent.next.index[1]
    if not word then
        return
    end
    checkField(state, word, position, position, parent, oop, results)
end

---@async
local function tryWord(state, position, triggerCharacter, results)
    if triggerCharacter == '('
    or triggerCharacter == '#'
    or triggerCharacter == ','
    or triggerCharacter == '{' then
        return
    end
    local text = state.lua
    if not text then
        return
    end
    local offset = guide.positionToOffset(state, position)
    local finish = lookBackward.skipSpace(text, offset)
    local word, start = lookBackward.findWord(text, offset)
    local startPos
    if not word then
        word = ''
        startPos = position
    else
        startPos = guide.offsetToPosition(state, start - 1)
    end
    local hasSpace = triggerCharacter ~= nil and finish ~= offset
    if guide.isInString(state.ast, position) then
        if not hasSpace then
            if #results == 0 then
                checkCommon(state, word, position, results)
            end
        end
    else
        local parent, oop = findParent(state, startPos)
        if     parent then
            checkField(state, word, startPos, position, parent, oop, results)
        elseif isFuncArg(state, position) then
            checkProvideLocal(state, word, startPos, results)
            checkFunctionArgByDocParam(state, word, startPos, results)
        else
            local afterLocal = isAfterLocal(state, text, startPos)
            local stop = checkKeyWord(state, startPos, position, word, hasSpace, afterLocal, results)
            if stop then
                return
            end
            if not hasSpace then
                if afterLocal then
                    checkProvideLocal(state, word, startPos, results)
                else
                    checkLocal(state, word, startPos, results)
                    checkTableField(state, word, startPos, results)
                    local env = guide.getENV(state.ast, startPos)
                    if env then
                        checkGlobal(state, word, startPos, position, env, false, results)
                        checkModule(state, word, startPos, results)
                    end
                end
            end
        end
        if not hasSpace and (#results == 0 or word ~= '') then
            checkCommon(state, word, position, results)
        end
    end
end

---@async
local function trySymbol(state, position, results)
    local text = state.lua
    local symbol, start = lookBackward.findSymbol(text, guide.positionToOffset(state, position))
    if not symbol then
        return nil
    end
    if guide.isInString(state.ast, position) then
        return nil
    end
    local startPos = guide.offsetToPosition(state, start)
    --if symbol == '.'
    --or symbol == ':' then
    --    local parent, oop = findParent(state, startPos)
    --    if parent then
    --        tracy.ZoneBeginN 'completion.trySymbol'
    --        checkField(state, '', startPos, position, parent, oop, results)
    --        tracy.ZoneEnd()
    --    end
    --end
    if symbol == '(' then
        checkFunctionArgByDocParam(state, '', startPos, results)
    end
end

local function findCall(state, position)
    local call
    guide.eachSourceContain(state.ast, position, function (src)
        if src.type == 'call' and src.node.finish <= position then
            if not call or call.start < src.start  then
                call = src
            end
        end
    end)
    return call
end

local function getCallArgInfo(call, position)
    if not call.args then
        return 1, nil
    end
    for index, arg in ipairs(call.args) do
        if arg.start <= position and arg.finish >= position then
            return index, arg
        end
    end
    return #call.args + 1, nil
end

local function checkTableLiteralField(state, position, tbl, fields, results)
    local text = state.lua
    if not text then
        return
    end
    local mark = {}
    for _, field in ipairs(tbl) do
        if field.type == 'tablefield'
        or field.type == 'tableindex'
        or field.type == 'tableexp' then
            local name = guide.getKeyName(field)
            if name then
                mark[name] = true
            end
        end
    end
    table.sort(fields, function (a, b)
        return tostring(guide.getKeyName(a)) < tostring(guide.getKeyName(b))
    end)
    -- {$}
    local left = lookBackward.findWord(text, guide.positionToOffset(state, position))
    if not left then
        local pos = lookBackward.findAnyOffset(text, guide.positionToOffset(state, position))
        if pos then
            local char = text:sub(pos, pos)
            if char == '{' or char == ',' or char == ';' then
                left = ''
            end
        end
    end
    if left then
        local fieldResults = {}
        for _, field in ipairs(fields) do
            local name = guide.getKeyName(field)
            if  name
            and not mark[name]
            and matchKey(left, tostring(name)) then
                local res = {
                    label      = guide.getKeyName(field),
                    kind       = define.CompletionItemKind.Property,
                    id         = stack(field, function (newField) ---@async
                        return {
                            detail      = buildDetail(newField),
                            description = buildDesc(newField),
                        }
                    end),
                }
                if field.optional
                or vm.compileNode(field):isNullable() then
                    res.insertText = res.label
                    res.label      = res.label.. '?'
                end
                fieldResults[#fieldResults+1] = res
            end
        end
        util.sortByScore(fieldResults, {
            function (r) return r.insertText and 0 or 1 end,
            util.sortCallbackOfIndex(fieldResults),
        })
        util.arrayMerge(results, fieldResults)
        return #fieldResults > 0
    end
end

local function tryCallArg(state, position, results)
    local call = findCall(state, position)
    if not call then
        return
    end
    local argIndex, arg = getCallArgInfo(call, position)
    if arg and arg.type == 'function' then
        return
    end
    ---@diagnostic disable-next-line: missing-fields
    local node = vm.compileCallArg({ type = 'dummyarg', uri = state.uri }, call, argIndex)
    if not node then
        return
    end

    local enums = {}
    for src in node:eachObject() do
        insertEnum(state, position, src, enums, arg and arg.type == 'table')
    end
    cleanEnums(enums, arg)
    for _, enum in ipairs(enums) do
        results[#results+1] = enum
    end
end

local function tryTable(state, position, results)
    local tbl = findNearestTable(state, position)
    if not tbl then
        return false
    end
    if  tbl.type ~= 'table' then
        return
    end
    local mark = {}
    local fields = {}

    local defs = vm.getFields(tbl)
    for _, field in ipairs(defs) do
        local name = guide.getKeyName(field)
        if name and not mark[name] then
            mark[name] = true
            fields[#fields+1] = field
        end
    end
    if checkTableLiteralField(state, position, tbl, fields, results) then
        return true
    end
    return false
end

local function tryArray(state, position, results)
    local source = findNearestSource(state, position)
    if not source then
        return
    end
    if source.type ~= 'table' and (not source.parent or source.parent.type ~= 'table') then
        return
    end
    local tbl = source
    if source.type ~= 'table' then
        tbl = source.parent
    end
    if source.parent.type == 'callargs' and source.parent.parent.type == 'call' then
        return
    end
    -- {  } inside when enum
    checkEqualEnumLeft(state, position, tbl, results, true)
end

local function getComment(state, position)
    local offset = guide.positionToOffset(state, position)
    local symbolOffset = lookBackward.findAnyOffset(state.lua, offset, true)
    if not symbolOffset then
        return
    end
    local symbolPosition = guide.offsetToPosition(state, symbolOffset)
    for _, comm in ipairs(state.comms) do
        if symbolPosition > comm.start and symbolPosition <= comm.finish then
            return comm
        end
    end
    return nil
end

local function getLuaDoc(state, position)
    local offset = guide.positionToOffset(state, position)
    local symbolOffset = lookBackward.findAnyOffset(state.lua, offset, true)
    if not symbolOffset then
        return
    end
    local symbolPosition = guide.offsetToPosition(state, symbolOffset)
    for _, doc in ipairs(state.ast.docs) do
        if symbolPosition >= doc.start and symbolPosition <= doc.range then
            return doc
        end
    end
    return nil
end

local function tryluaDocCate(word, results)
    for _, docType in ipairs {
        'class',
        'type',
        'alias',
        'param',
        'return',
        'field',
        'generic',
        'vararg',
        'overload',
        'deprecated',
        'meta',
        'version',
        'see',
        'diagnostic',
        'module',
        'async',
        'nodiscard',
        'cast',
        'operator',
        'source',
        'enum',
        'package',
        'private',
        'protected'
    } do
        if matchKey(word, docType) then
            results[#results+1] = {
                label       = docType,
                kind        = define.CompletionItemKind.Event,
                description = lang.script('LUADOC_DESC_' .. docType:upper())
            }
        end
    end
end

local function getluaDocByContain(state, position)
    local result
    local range = math.huge
    guide.eachSourceContain(state.ast.docs, position, function (src)
        if not src.start then
            return
        end
        if  range >= position - src.start
        and position <= src.finish then
            range = position - src.start
            result = src
        end
    end)
    return result
end

---@return parser.state.err?, parser.object?
local function getluaDocByErr(state, start, position)
    local targetError
    for _, err in ipairs(state.errs) do
        if  err.finish <= position
        and err.start >= start  then
            if not state.lua:sub(err.finish + 1, position):find '%S' then
                targetError = err
                break
            end
        end
    end
    if not targetError then
        return nil
    end
    local targetDoc
    for i = #state.ast.docs, 1, -1 do
        local doc = state.ast.docs[i]
        if doc.finish <= targetError.start then
            targetDoc = doc
            break
        end
    end
    return targetError, targetDoc
end

---@async
local function tryluaDocBySource(state, position, source, results)
    if     source.type == 'doc.extends.name' then
        if source.parent.type == 'doc.class' then
            local used = {}
            for _, doc in ipairs(vm.getDocSets(state.uri)) do
                local name = doc.type == 'doc.class' and doc.class[1]
                if  name
                and name ~= source.parent.class[1]
                and not used[name]
                and matchKey(source[1], name) then
                    used[name] = true
                    results[#results+1] = {
                        label       = name,
                        kind        = define.CompletionItemKind.Class,
                        textEdit    = name:find '[^%w_]' and {
                            start   = source.start,
                            finish  = position,
                            newText = name,
                        },
                    }
                end
            end
        end
        return true
    elseif source.type == 'doc.type.name' then
        local used = {}
        for _, doc in ipairs(vm.getDocSets(state.uri)) do
            local name = (doc.type == 'doc.class' and doc.class[1])
                    or   (doc.type == 'doc.alias' and doc.alias[1])
                    or   (doc.type == 'doc.enum'  and doc.enum[1])
            if  name
            and not used[name]
            and matchKey(source[1], name) then
                used[name] = true
                results[#results+1] = {
                    label       = name,
                    kind        = define.CompletionItemKind.Class,
                    textEdit    = name:find '[^%w_]' and {
                        start   = source.start,
                        finish  = position,
                        newText = name,
                    },
                }
            end
        end
        return true
    elseif source.type == 'doc.param.name' then
        local funcs = {}
        guide.eachSourceBetween(state.ast, position, math.huge, function (src)
            if src.type == 'function' and src.start > position then
                funcs[#funcs+1] = src
            end
        end)
        table.sort(funcs, function (a, b)
            return a.start < b.start
        end)
        local func = funcs[1]
        if not func or not func.args then
            return
        end
        for _, arg in ipairs(func.args) do
            if arg[1] and matchKey(source[1], arg[1]) then
                results[#results+1] = {
                    label  = arg[1],
                    kind   = define.CompletionItemKind.Interface,
                }
            end
        end
        return true
    elseif source.type == 'doc.diagnostic' then
        for _, mode in ipairs(diagnosticModes) do
            if matchKey(source.mode, mode) then
                results[#results+1] = {
                    label    = mode,
                    kind     = define.CompletionItemKind.Enum,
                    textEdit = {
                        start   = source.start,
                        finish  = source.start + #source.mode - 1,
                        newText = mode,
                    },
                }
            end
        end
        return true
    elseif source.type == 'doc.diagnostic.name' then
        for name in util.sortPairs(define.DiagnosticDefaultSeverity) do
            if matchKey(source[1], name) then
                results[#results+1] = {
                    label    = name,
                    kind     = define.CompletionItemKind.Value,
                    textEdit = {
                        start   = source.start,
                        finish  = source.start + #source[1] - 1,
                        newText = name,
                    },
                }
            end
        end
        return true
    elseif source.type == 'doc.module' then
        collectRequireNames('require', state.uri, source.module or '', source, source.smark, position, results)
        return true
    elseif source.type == 'doc.cast.name' then
        local locals = guide.getVisibleLocals(state.ast, position)
        for name, loc in util.sortPairs(locals) do
            if matchKey(source[1], name) then
                results[#results+1] = {
                    label = name,
                    kind  = define.CompletionItemKind.Variable,
                    id    = stack(loc, function (newLoc) ---@async
                        return {
                            detail      = buildDetail(newLoc),
                            description = buildDesc(newLoc),
                        }
                    end),
                }
            end
        end
        return true
    elseif source.type == 'doc.operator.name' then
        for _, name in ipairs(vm.UNARY_OP) do
            if matchKey(source[1], name) then
                results[#results+1] = {
                    label       = name,
                    kind        = define.CompletionItemKind.Operator,
                    description = ('```lua\n%s\n```'):format(vm.OP_UNARY_MAP[name]),
                }
            end
        end
        for _, name in ipairs(vm.BINARY_OP) do
            if matchKey(source[1], name) then
                results[#results+1] = {
                    label       = name,
                    kind        = define.CompletionItemKind.Operator,
                    description = ('```lua\n%s\n```'):format(vm.OP_BINARY_MAP[name]),
                }
            end
        end
        for _, name in ipairs(vm.OTHER_OP) do
            if matchKey(source[1], name) then
                results[#results+1] = {
                    label       = name,
                    kind        = define.CompletionItemKind.Operator,
                    description = ('```lua\n%s\n```'):format(vm.OP_OTHER_MAP[name]),
                }
            end
        end
        return true
    elseif source.type == 'doc.see.name' then
        local symbolds = wssymbol(source[1], state.uri)
        table.sort(symbolds, function (a, b)
            return a.name < b.name
        end)
        for _, symbol in ipairs(symbolds) do
            results[#results+1] = {
                label = symbol.name,
                kind  = symbol.ckind,
                id    = stack(symbol.source, function (newSource) ---@async
                    return {
                        detail      = buildDetail(newSource),
                        description = buildDesc(newSource),
                    }
                end),
                textEdit = {
                    start   = source.start,
                    finish  = source.finish,
                    newText = symbol.name,
                },
            }
        end
    end
    return false
end

---@async
local function tryluaDocByErr(state, position, err, docState, results)
    if     err.type == 'LUADOC_MISS_CLASS_EXTENDS_NAME' then
        local used = {}
        for _, doc in ipairs(vm.getDocSets(state.uri)) do
            if  doc.type == 'doc.class'
            and not used[doc.class[1]]
            and docState and doc.class[1] ~= docState.class[1] then
                used[doc.class[1]] = true
                results[#results+1] = {
                    label       = doc.class[1],
                    kind        = define.CompletionItemKind.Class,
                }
            end
        end
    elseif err.type == 'LUADOC_MISS_TYPE_NAME' then
        local used = {}
        for _, doc in ipairs(vm.getDocSets(state.uri)) do
            if  doc.type == 'doc.class'
            and not used[doc.class[1]] then
                used[doc.class[1]] = true
                results[#results+1] = {
                    label       = doc.class[1],
                    kind        = define.CompletionItemKind.Class,
                }
            end
            if  doc.type == 'doc.alias'
            and not used[doc.alias[1]] then
                used[doc.alias[1]] = true
                results[#results+1] = {
                    label       = doc.alias[1],
                    kind        = define.CompletionItemKind.Class,
                }
            end
            if  doc.type == 'doc.enum'
            and not used[doc.enum[1]] then
                used[doc.enum[1]] = true
                results[#results+1] = {
                    label       = doc.enum[1],
                    kind        = define.CompletionItemKind.Enum,
                }
            end
        end
    elseif err.type == 'LUADOC_MISS_PARAM_NAME' then
        local funcs = {}
        guide.eachSourceBetween(state.ast, position, math.huge, function (src)
            if src.type == 'function' and src.start > position then
                funcs[#funcs+1] = src
            end
        end)
        table.sort(funcs, function (a, b)
            return a.start < b.start
        end)
        local func = funcs[1]
        if not func or not func.args then
            return
        end
        local label = {}
        local insertText = {}
        for i, arg in ipairs(func.args) do
            if arg[1] and arg.type ~= 'self' then
                label[#label+1] = arg[1]
                if #label == 1 then
                    insertText[#insertText+1] = ('%s ${%d:any}'):format(arg[1], #label)
                else
                    insertText[#insertText+1] = ('---@param %s ${%d:any}'):format(arg[1], #label)
                end
            end
        end
        results[#results+1] = {
            label            = table.concat(label, ', '),
            kind             = define.CompletionItemKind.Snippet,
            insertTextFormat = 2,
            insertText       = table.concat(insertText, '\n'),
        }
        for i, arg in ipairs(func.args) do
            if arg[1] then
                results[#results+1] = {
                    label  = arg[1],
                    kind   = define.CompletionItemKind.Interface,
                }
            end
        end
    elseif err.type == 'LUADOC_MISS_DIAG_MODE' then
        for _, mode in ipairs(diagnosticModes) do
            results[#results+1] = {
                label = mode,
                kind  = define.CompletionItemKind.Enum,
            }
        end
    elseif err.type == 'LUADOC_MISS_DIAG_NAME' then
        for name in util.sortPairs(diag.getDiagAndErrNameMap()) do
            results[#results+1] = {
                label = name,
                kind  = define.CompletionItemKind.Value,
            }
        end
    elseif err.type == 'LUADOC_MISS_MODULE_NAME' then
        collectRequireNames('require', state.uri, '', docState, nil, position, results)
    elseif err.type == 'LUADOC_MISS_LOCAL_NAME' then
        local locals = guide.getVisibleLocals(state.ast, position)
        for name, loc in util.sortPairs(locals) do
            if name ~= '_ENV' then
                results[#results+1] = {
                    label = name,
                    kind   = define.CompletionItemKind.Variable,
                    id     = stack(loc, function (newLoc) ---@async
                        return {
                            detail      = buildDetail(newLoc),
                            description = buildDesc(newLoc),
                        }
                    end),
                }
            end
        end
    elseif err.type == 'LUADOC_MISS_OPERATOR_NAME' then
        for _, name in ipairs(vm.UNARY_OP) do
            results[#results+1] = {
                label       = name,
                kind        = define.CompletionItemKind.Operator,
                description = ('```lua\n%s\n```'):format(vm.OP_UNARY_MAP[name]),
            }
        end
        for _, name in ipairs(vm.BINARY_OP) do
            results[#results+1] = {
                label       = name,
                kind        = define.CompletionItemKind.Operator,
                description = ('```lua\n%s\n```'):format(vm.OP_BINARY_MAP[name]),
            }
        end
        for _, name in ipairs(vm.OTHER_OP) do
            results[#results+1] = {
                label       = name,
                kind        = define.CompletionItemKind.Operator,
                description = ('```lua\n%s\n```'):format(vm.OP_OTHER_MAP[name]),
            }
        end
    elseif err.type == 'LUADOC_MISS_SEE_NAME' then
        local symbolds = wssymbol('', state.uri)
        table.sort(symbolds, function (a, b)
            return a.name < b.name
        end)
        for _, symbol in ipairs(symbolds) do
            results[#results+1] = {
                label = symbol.name,
                kind  = symbol.ckind,
                id    = stack(symbol.source, function (newSource) ---@async
                    return {
                        detail      = buildDetail(newSource),
                        description = buildDesc(newSource),
                    }
                end),
            }
        end
    end
end

local function buildluaDocOfFunction(func, pad)
    local index = 1
    local buf = {}
    buf[#buf+1] = '${1:comment}'
    local args = {}
    local returns = {}
    if func.args then
        for _, arg in ipairs(func.args) do
            args[#args+1] = vm.getInfer(arg):view(guide.getUri(func))
        end
    end
    if func.returns then
        for _, rtns in ipairs(func.returns) do
            for n = 1, #rtns do
                if not returns[n] then
                    returns[n] = vm.getInfer(rtns[n]):view(guide.getUri(func))
                end
            end
        end
    end
    for n, arg in ipairs(args) do
        local funcArg = func.args[n]
        if funcArg[1] and funcArg.type ~= 'self' then
            index = index + 1
            buf[#buf+1] = ('---%s@param %s ${%d:%s}'):format(
                pad and ' ' or '',
                funcArg[1],
                index,
                arg
            )
        end
    end
    for _, rtn in ipairs(returns) do
        index = index + 1
        buf[#buf+1] = ('---%s@return ${%d:%s}'):format(
            pad and ' ' or '',
            index,
            rtn
        )
    end
    local insertText = table.concat(buf, '\n')
    return insertText
end

local function tryluaDocOfFunction(doc, results, pad)
    if not doc.bindSource then
        return
    end
    local func = (doc.bindSource.type == 'function' and doc.bindSource)
              or (doc.bindSource.value and doc.bindSource.value.type == 'function' and doc.bindSource.value)
              or nil
    if not func then
        return
    end
    for _, otherDoc in ipairs(doc.bindGroup) do
        if otherDoc.type == 'doc.return' then
            return
        end
    end
    if func.args then
        for _, param in ipairs(func.args) do
            if param.bindDocs then
                return
            end
        end
    end
    local insertText = buildluaDocOfFunction(func, pad)
    results[#results+1] = {
        label            = '@param;@return',
        kind             = define.CompletionItemKind.Snippet,
        insertTextFormat = 2,
        filterText       = '---',
        insertText       = insertText
    }
end

---Checks for a lua symbol reference in comment
---@async
local function trySymbolReference(state, position, results)
    local doc = getLuaDoc(state, position)
    if not doc then
        return
    end

    local line = doc.originalComment.text ---@type string
    local col = select(2, guide.rowColOf(position)) - 2 ---@type integer

    -- User will ask for completion at end of symbol name so we need to perform a reverse match to see if they are in a symbol reference
    -- Matching in reverse allows the symbol to be of any length and we can still match all the way back to `](lua://` from right to left
    local symbol = string.match(string.reverse(line), "%)?([%w%s-_.*]*)//:aul%(%]", #line - col)

    if symbol then
        -- flip it back the right way around
        symbol = string.reverse(symbol)

        for _, match in ipairs(wssymbol(symbol)) do
            results[#results+1] = {
                label = match.name,
                kind = define.CompletionItemKind.Class,
                insertText = match.name
            }
        end
    end
end

---@async
local function tryLuaDoc(state, position, results)
    local doc = getLuaDoc(state, position)
    if not doc then
        return
    end
    if doc.type == 'doc.comment' then
        local line = doc.originalComment.text
        -- 尝试 '---$' or '--- $'
        if line == '-' or line == '- ' then
            tryluaDocOfFunction(doc, results, line == '- ')
            return
        end
        -- 尝试 ---@$
        local cate = line:match('^-+%s*@(%a*)$')
        if cate then
            tryluaDocCate(cate, results)
            return
        end
    end
    -- 根据输入中的source来补全
    local source = getluaDocByContain(state, position)
    if source then
        local suc = tryluaDocBySource(state, position, source, results)
        if suc then
            return
        end
    end
    -- 根据附近的错误消息来补全
    local err, expectDoc = getluaDocByErr(state, doc.start, position)
    if err then
        tryluaDocByErr(state, position, err, expectDoc, results)
        return
    end
end

local function tryComment(state, position, results)
    if #results > 0 then
        return
    end
    local word = lookBackward.findWord(state.lua, guide.positionToOffset(state, position))
    local doc  = getLuaDoc(state, position)
    if not word then
        local comment = getComment(state, position)
        if not comment then
            return
        end
        if comment.type == 'comment.short'
        or comment.type == 'comment.cshort' then
            if comment.text == '' then
                results[#results+1] = {
                    label = '#region',
                    kind  = define.CompletionItemKind.Snippet,
                }
                results[#results+1] = {
                    label = '#endregion',
                    kind  = define.CompletionItemKind.Snippet,
                }
            end
        end
        return
    end
    if doc and doc.type ~= 'doc.comment' then
        return
    end
    checkCommon(state, word, position, results)
end

---@async
local function tryCompletions(state, position, triggerCharacter, results)
    if getComment(state, position) then
        trySymbolReference(state, position, results)
        tryLuaDoc(state, position, results)
        tryComment(state, position, results)
        return
    end
    if postfix(state, position, results) then
        return
    end
    if tryTable(state, position, results) then
        return
    end
    trySpecial(state, position, results)
    tryCallArg(state, position, results)
    tryArray(state, position, results)
    tryWord(state, position, triggerCharacter, results)
    tryIndex(state, position, results)
    trySymbol(state, position, results)
end

---@async
local function completion(uri, position, triggerCharacter)
    local state = files.getLastState(uri) or files.getState(uri)
    if not state then
        return nil
    end
    clearStack()
    diagnostic.pause()
    local _ <close> = diagnostic.resume
    local results = {}
    tracy.ZoneBeginN 'completion #2'
    tryCompletions(state, position, triggerCharacter, results)
    tracy.ZoneEnd()

    if #results == 0 then
        return nil
    end

    return results
end

---@async
local function resolve(id)
    local item = resolveStack(id)
    return item
end

return {
    completion   = completion,
    resolve      = resolve,
}