summaryrefslogtreecommitdiff
path: root/script/core/noder.lua
blob: 566a744557e7f25fe00db70ae98d0268ecf3c3d3 (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
local util      = require 'utility'
local guide     = require 'parser.guide'
local collector = require 'core.collector'
local files     = require 'files'

local SPLIT_CHAR     = '\x1F'
local LAST_REGEX     = SPLIT_CHAR .. '[^' .. SPLIT_CHAR .. ']*$'
local FIRST_REGEX    = '^[^' .. SPLIT_CHAR .. ']*'
local HEAD_REGEX    = '^' .. SPLIT_CHAR .. '?[^' .. SPLIT_CHAR .. ']*'
local ANY_FIELD_CHAR = '*'
local INDEX_CHAR     = '['
local RETURN_INDEX   = SPLIT_CHAR .. '#'
local PARAM_INDEX    = SPLIT_CHAR .. '&'
local TABLE_KEY      = SPLIT_CHAR .. '<'
local WEAK_TABLE_KEY = SPLIT_CHAR .. '<<'
local INDEX_FIELD    = SPLIT_CHAR .. INDEX_CHAR
local ANY_FIELD      = SPLIT_CHAR .. ANY_FIELD_CHAR
local WEAK_ANY_FIELD = SPLIT_CHAR .. ANY_FIELD_CHAR .. ANY_FIELD_CHAR
local URI_CHAR       = '@'
local URI_REGEX      = URI_CHAR .. '([^' .. URI_CHAR .. ']*)' .. URI_CHAR .. '(.*)'

---@class node
-- 当前节点的id
---@field id     string
-- 使用该ID的单元
---@field source parser.guide.object
-- 使用该ID的单元
---@field sources parser.guide.object[]
-- 前进的关联ID
---@field forward string
-- 第一个前进关联的tag
---@field finfo? node.info
-- 前进的关联ID
---@field forwards string[]
-- 后退的关联ID
---@field backward string
-- 第一个后退关联的tag
---@field binfo? node.info
-- 后退的关联ID
---@field backwards string[]
-- 函数调用参数信息(用于泛型)
---@field call parser.guide.object
---@field skip boolean

---@alias noders table<string, node[]>
---@alias node.filter fun(id: string, field?: string):boolean

---@class node.info
---@field reject?      string
---@field deep?        boolean
---@field filter?      node.filter
---@field filterValid? node.filter
---@field dontCross?   boolean

---创建source的链接信息
---@param noders noders
---@param id string
---@return node
local function getNode(noders, id)
    if not noders[id] then
        noders[id] = {
            id = id,
        }
    end
    return noders[id]
end

---如果对象是 arg self, 则认为 id 是 method 的 node
---@param source parser.guide.object
---@return nil
local function getMethodNode(source)
    if source.type ~= 'local' or source[1] ~= 'self' then
        return nil
    end
    if source._mnode ~= nil then
        return source._mnode or nil
    end
    source._mnode = false
    local func = guide.getParentFunction(source)
    if func.isGeneric then
        return
    end
    if source.parent.type ~= 'funcargs' then
        return
    end
    local setmethod = func.parent
    if setmethod and ( setmethod.type == 'setmethod'
                    or setmethod.type == 'setfield'
                    or setmethod.type == 'setindex') then
        source._mnode = setmethod.node
        return setmethod.node
    end
end

---获取语法树单元的key
---@param source parser.guide.object
---@return string? key
---@return parser.guide.object? node
local function getKey(source)
    if     source.type == 'local' then
        if source.parent.type == 'funcargs' then
            return 'p:' .. source.start, nil
        end
        return 'l:' .. source.start, nil
    elseif source.type == 'setlocal'
    or     source.type == 'getlocal' then
        return getKey(source.node)
    elseif source.type == 'setglobal'
    or     source.type == 'getglobal' then
        local node = source.node
        if node.tag == '_ENV' then
            return ('%q'):format(source[1] or ''), nil
        else
            return ('%q'):format(source[1] or ''), node
        end
    elseif source.type == 'getfield'
    or     source.type == 'setfield' then
        return ('%q'):format(source.field and source.field[1] or ''), source.node
    elseif source.type == 'tablefield' then
        return ('%q'):format(source.field and source.field[1] or ''), source.parent
    elseif source.type == 'getmethod'
    or     source.type == 'setmethod' then
        return ('%q'):format(source.method and source.method[1] or ''), source.node
    elseif source.type == 'setindex'
    or     source.type == 'getindex' then
        local index = source.index
        if not index then
            return INDEX_CHAR, source.node
        end
        if index.type == 'string'
        or index.type == 'boolean'
        or index.type == 'integer'
        or index.type == 'number' then
            return ('%q'):format(index[1] or ''), source.node
        else
            return INDEX_CHAR, source.node
        end
    elseif source.type == 'tableindex' then
        local index = source.index
        if not index then
            return ANY_FIELD_CHAR, source.parent
        end
        if index.type == 'string'
        or index.type == 'boolean'
        or index.type == 'integer'
        or index.type == 'number' then
            return ('%q'):format(index[1] or ''), source.parent
        elseif index.type ~= 'function'
        and    index.type ~= 'table' then
            return ANY_FIELD_CHAR, source.parent
        end
    elseif source.type == 'table' then
        return 't:' .. source.start, nil
    elseif source.type == 'label' then
        return 'l:' .. source.start, nil
    elseif source.type == 'goto' then
        if source.node then
            return 'l:' .. source.node.start, nil
        end
        return nil, nil
    elseif source.type == 'function' then
        return 'f:' .. source.start, nil
    elseif source.type == 'string' then
        return 'str:', nil
    elseif source.type == 'integer' then
        return 'int:'
    elseif source.type == 'number' then
        return 'num:'
    elseif source.type == 'boolean' then
        return 'bool:'
    elseif source.type == 'nil' then
        return 'nil:', nil
    elseif source.type == '...' then
        return 'va:' .. source.start, nil
    elseif source.type == 'varargs' then
        if source.node then
            return 'va:' .. source.node.start, nil
        end
    elseif source.type == 'select' then
        return ('s:%d%s%d'):format(source.start, RETURN_INDEX, source.sindex)
    elseif source.type == 'call' then
        local node = source.node
        if node.special == 'rawget'
        or node.special == 'rawset' then
            if not source.args then
                return nil, nil
            end
            local tbl, key = source.args[1], source.args[2]
            if not tbl or not key then
                return nil, nil
            end
            if key.type == 'string' then
                return ('%q'):format(key[1] or ''), tbl
            else
                return '', tbl
            end
        end
        return 'c:' .. source.finish, nil
    elseif source.type == 'doc.class.name'
    or     source.type == 'doc.alias.name'
    or     source.type == 'doc.extends.name' then
        local name = source[1]
        return 'dn:' .. name, nil
    elseif source.type == 'doc.type.name' then
        local name = source[1]
        if source.typeGeneric then
            return 'dg:' .. source.typeGeneric[name][1].start, nil
        else
            return 'dn:' .. name, nil
        end
    elseif source.type == 'doc.see.name' then
        local name = source[1]
        return 'dsn:' .. name, nil
    elseif source.type == 'doc.class' then
        return 'dc:' .. source.start
    elseif source.type == 'doc.type' then
        return 'dt:' .. source.start
    elseif source.type == 'doc.param' then
        return 'dp:' .. source.start
    elseif source.type == 'doc.vararg' then
        return 'dv:' .. source.start
    elseif source.type == 'doc.field.name' then
        return 'dfn:' .. source.start
    elseif source.type == 'doc.type.enum'
    or     source.type == 'doc.resume' then
        return 'de:' .. source.start
    elseif source.type == 'doc.type.table' then
        return 'dtable:' .. source.start
    elseif source.type == 'doc.type.ltable' then
        return 'dltable:' .. source.start
    elseif source.type == 'doc.type.field' then
        return 'dfield:' .. source.start
    elseif source.type == 'doc.type.array' then
        return 'darray:' .. source.finish
    elseif source.type == 'doc.type.function' then
        return 'dfun:' .. source.start, nil
    elseif source.type == 'doc.see.field' then
        return ('%q'):format(source[1]), source.parent.name
    elseif source.type == 'generic.closure' then
        return 'gc:' .. source.call.start, nil
    elseif source.type == 'generic.value' then
        local tail = ''
        if guide.getUri(source.closure.call) ~= guide.getUri(source.proto) then
            tail = URI_CHAR .. guide.getUri(source.closure.call)
        end
        return ('gv:%s|%s%s'):format(
            source.closure.call.start,
            getKey(source.proto),
            tail
        )
    end
    return nil, nil
end

local function getNodeKey(source)
    if source.type == 'getlocal'
    or source.type == 'setlocal' then
        source = source.node
    end
    local methodNode = getMethodNode(source)
    if methodNode then
        return getNodeKey(methodNode)
    end
    local key, node = getKey(source)
    if guide.isGlobal(source) then
        return 'g:' .. key, nil
    end
    return key, node
end

local IDList = {}
---获取语法树单元的字符串ID
---@param source parser.guide.object
---@return string? id
local function getID(source)
    if not source then
        return nil
    end
    if source._id ~= nil then
        return source._id or nil
    end
    if source.type == 'field'
    or source.type == 'method' then
        source._id = false
        return nil
    end
    local current = source
    local index = 0
    while true do
        if current.type == 'paren' then
            current = current.exp
            if not current then
                return nil
            end
            goto CONTINUE
        end
        local id, node = getNodeKey(current)
        if not id then
            break
        end
        index = index + 1
        IDList[index] = id
        if not node then
            break
        end
        current = node
        ::CONTINUE::
    end
    if index == 0 then
        source._id = false
        return nil
    end
    for i = index + 1, #IDList do
        IDList[i] = nil
    end
    util.revertTable(IDList)
    local id = table.concat(IDList, SPLIT_CHAR)
    source._id = id
    return id
end

---添加关联的前进ID
---@param noders    noders
---@param id        string
---@param forwardID string
---@param info?     node.info
local function pushForward(noders, id, forwardID, info)
    if not id
    or not forwardID
    or forwardID == ''
    or id == forwardID then
        return
    end
    local node = getNode(noders, id)
    if not node.forward then
        node.forward = forwardID
        node.finfo   = info
        return
    end
    if node.forward == forwardID then
        return
    end
    if not node.forwards then
        node.forwards = {}
    end
    if node.forwards[forwardID] ~= nil then
        return
    end
    node.forwards[forwardID] = info or false
    node.forwards[#node.forwards+1] = forwardID
end

---添加关联的后退ID
---@param noders     noders
---@param id         string
---@param backwardID string
---@param info?      node.info
local function pushBackward(noders, id, backwardID, info)
    if not id
    or not backwardID
    or backwardID == ''
    or id == backwardID then
        return
    end
    local node = getNode(noders, id)
    if not node.backward then
        node.backward = backwardID
        node.binfo    = info
        return
    end
    if node.backward == backwardID then
        return
    end
    if not node.backwards then
        node.backwards = {}
    end
    if node.backwards[backwardID] ~= nil then
        return
    end
    node.backwards[backwardID] = info or false
    node.backwards[#node.backwards+1] = backwardID
end

---@class noder
local m = {}

m.SPLIT_CHAR     = SPLIT_CHAR
m.RETURN_INDEX   = RETURN_INDEX
m.PARAM_INDEX    = PARAM_INDEX
m.TABLE_KEY      = TABLE_KEY
m.ANY_FIELD      = ANY_FIELD
m.URI_CHAR       = URI_CHAR
m.INDEX_FIELD    = INDEX_FIELD
m.WEAK_TABLE_KEY = WEAK_TABLE_KEY
m.WEAK_ANY_FIELD = WEAK_ANY_FIELD

--- 寻找doc的主体
---@param obj parser.guide.object
---@return parser.guide.object
local function getDocStateWithoutCrossFunction(obj)
    for _ = 1, 1000 do
        local parent = obj.parent
        if not parent then
            return obj
        end
        if parent.type == 'doc' then
            return obj
        end
        if parent.type == 'doc.type.function' then
            return nil
        end
        obj = parent
    end
    error('guide.getDocState overstack')
end

---添加关联单元
---@param noders noders
---@param source parser.guide.object
function m.pushSource(noders, source, id)
    id = id or m.getID(source)
    if not id then
        return
    end
    if id == 'str:'
    or id == 'nil:'
    or id == 'num:'
    or id == 'int:'
    or id == 'bool:' then
        return
    end
    local node = getNode(noders, id)
    if not node.source then
        node.source = source
        return
    end
    if not node.sources then
        node.sources = {}
    end
    node.sources[#node.sources+1] = source
end

local DUMMY_FUNCTION = function () end

---遍历关联单元
---@param node node
---@return fun():parser.guide.object
function m.eachSource(node)
    if not node.source then
        return DUMMY_FUNCTION
    end
    local index
    local sources = node.sources
    return function ()
        if not index then
            index = 0
            return node.source
        end
        if not sources then
            return nil
        end
        index = index + 1
        return sources[index]
    end
end

---遍历forward
---@param node node
---@return fun():string, string
function m.eachForward(node)
    if not node.forward then
        return DUMMY_FUNCTION
    end
    local index
    local forwards = node.forwards
    return function ()
        if not index then
            index = 0
            return node.forward, node.finfo
        end
        if not forwards then
            return nil
        end
        index = index + 1
        local id  = forwards[index]
        local tag = forwards[id]
        return id, tag
    end
end

---遍历backward
---@param node node
---@return fun():string, node.info
function m.eachBackward(node)
    if not node.backward then
        return DUMMY_FUNCTION
    end
    local index
    local backwards = node.backwards
    return function ()
        if not index then
            index = 0
            return node.backward, node.binfo
        end
        if not backwards then
            return nil
        end
        index = index + 1
        local id  = backwards[index]
        local tag = backwards[id]
        return id, tag
    end
end

local function bindValue(noders, source, id)
    local value = source.value
    if not value then
        return
    end
    local valueID = getID(value)
    if not valueID then
        return
    end
    if source.type == 'getlocal'
    or source.type == 'setlocal' then
        source = source.node
    end
    if source.bindDocs and value.type ~= 'table' then
        for _, doc in ipairs(source.bindDocs) do
            if doc.type == 'doc.class'
            or doc.type == 'doc.type' then
                return
            end
        end
    end
    -- x = y : x -> y
    pushForward(noders, id, valueID, {
        reject = 'set',
    })
    -- 参数/call禁止反向查找赋值
    local valueType = valueID:match '^(.-:).'
    if not valueType then
        return
    end
    if  valueType ~= 'p:'
    and valueType ~= 's:'
    and valueType ~= 'c:' then
        pushBackward(noders, valueID, id, {
            reject = 'set',
        })
    else
        pushBackward(noders, valueID, id, {
            reject = 'set',
            deep   = true,
        })
    end
end

local function compileCallParam(noders, call, sourceID)
    if not sourceID then
        return
    end
    if not call.args then
        return
    end
    local node = call.node
    local fixIndex = 0
    if call.node.special == 'pcall' then
        fixIndex = 1
        node = call.args[1]
    elseif call.node.special == 'xpcall' then
        fixIndex = 2
        node = call.args[1]
    end
    local nodeID = getID(node)
    if not nodeID then
        return
    end
    for firstIndex, callArg in ipairs(call.args) do
        firstIndex = firstIndex - fixIndex
        if firstIndex > 0 and callArg.type == 'function' then
            if callArg.args then
                for secondIndex, funcParam in ipairs(callArg.args) do
                    local paramID = ('%s%s%s%s%s'):format(
                        nodeID,
                        PARAM_INDEX,
                        firstIndex,
                        PARAM_INDEX,
                        secondIndex
                    )
                    pushForward(noders, getID(funcParam), paramID)
                end
            end
        end
    end
end

local function compileCallReturn(noders, call, sourceID, returnIndex)
    if not sourceID then
        return
    end
    local node = call.node
    local nodeID = getID(node)
    if not nodeID then
        return
    end
    local callID = getID(call)
    if not callID then
        return
    end
    -- 将setmetatable映射到 param1 以及 param2.__index 上
    if node.special == 'setmetatable' then
        local tblID  = getID(call.args and call.args[1])
        local metaID = getID(call.args and call.args[2])
        local indexID
        if metaID then
            indexID = ('%s%s%q'):format(
                metaID,
                SPLIT_CHAR,
                '__index'
            )
        end
        pushForward(noders, sourceID, tblID)
        pushForward(noders, sourceID, indexID, {
            filter = function (id, field)
                if field then
                    return true
                end
                return id:sub(1, 2) ~= 'f:'
            end,
            filterValid = function (id, field)
                return not field
            end
        })
        pushBackward(noders, tblID, sourceID)
        --pushBackward(noders, indexID, callID)
        return
    end
    if node.special == 'require' then
        local arg1 = call.args and call.args[1]
        if arg1 and arg1.type == 'string' then
            getNode(noders, sourceID).require = arg1[1]
        end
        pushBackward(noders, callID, sourceID, {
            deep = true,
        })
        return
    end
    if node.special == 'pcall'
    or node.special == 'xpcall' then
        local index = returnIndex - 1
        if index <= 0 then
            return
        end
        local funcID = call.args and getID(call.args[1])
        if not funcID then
            return
        end
        local pfuncXID = ('%s%s%s'):format(
            funcID,
            RETURN_INDEX,
            index
        )
        pushForward(noders, sourceID, pfuncXID)
        pushBackward(noders, pfuncXID, sourceID, {
            deep = true,
        })
        return
    end
    local funcXID = ('%s%s%s'):format(
        nodeID,
        RETURN_INDEX,
        returnIndex
    )
    getNode(noders, sourceID).call = call
    pushForward(noders, sourceID, funcXID)
    pushBackward(noders, funcXID, sourceID, {
        deep = true,
    })
end

function m.compileDocValue(noders, tp, id, source)
    if tp == 'doc.type' then
        if source.bindSources then
            for _, src in ipairs(source.bindSources) do
                pushForward(noders, getID(src), id)
                pushForward(noders, id, getID(src))
            end
        end
        for _, enumUnit in ipairs(source.enums) do
            pushForward(noders, id, getID(enumUnit))
        end
        for _, resumeUnit in ipairs(source.resumes) do
            pushForward(noders, id, getID(resumeUnit))
        end
        for _, typeUnit in ipairs(source.types) do
            local unitID = getID(typeUnit)
            pushForward(noders, id, unitID)
            if source.bindSources then
                for _, src in ipairs(source.bindSources) do
                    pushBackward(noders, unitID, getID(src))
                end
            end
        end
    end
    if tp == 'doc.type.table' then
        if source.tkey then
            local keyID = ('%s%s'):format(
                id,
                TABLE_KEY
            )
            pushForward(noders, keyID, getID(source.tkey))
        end
        if source.tvalue then
            local valueID = ('%s%s'):format(
                id,
                ANY_FIELD
            )
            pushForward(noders, valueID, getID(source.tvalue))
        end
    end
    if tp == 'doc.type.ltable' then
        local firstField = source.fields[1]
        if not firstField then
            return
        end
        local keyID = ('%s%s'):format(
            id,
            WEAK_TABLE_KEY
        )
        local valueID = ('%s%s'):format(
            id,
            WEAK_ANY_FIELD
        )
        pushForward(noders, keyID, 'dn:string')
        pushForward(noders, valueID, getID(firstField.extends))
        for _, field in ipairs(source.fields) do
            local extendsID = ('%s%s%q'):format(
                id,
                SPLIT_CHAR,
                field.name[1]
            )
            pushForward(noders, extendsID, getID(field))
            pushForward(noders, extendsID, getID(field.extends))
        end
    end
    if tp == 'doc.type.array' then
        if source.node then
            local nodeID = ('%s%s'):format(
                id,
                ANY_FIELD
            )
            pushForward(noders, nodeID, getID(source.node))
        end
        local keyID = ('%s%s'):format(
            id,
            TABLE_KEY
        )
        pushForward(noders, keyID, 'dn:integer')
    end
end

---@param noders noders
---@param source parser.guide.object
---@return parser.guide.object[]
function m.compileNode(noders, source)
    local id = getID(source)
    bindValue(noders, source, id)
    if source.special == 'setmetatable'
    or source.special == 'require'
    or source.special == 'dofile'
    or source.special == 'loadfile'
    or source.special == 'rawset'
    or source.special == 'rawget' then
        local node = getNode(noders, id)
        node.skip = true
    end
    if source.type == 'string' then
        pushForward(noders, id, 'str:')
    end
    if source.type == 'boolean' then
        pushForward(noders, id, 'dn:boolean')
    end
    if source.type == 'number' then
        pushForward(noders, id, 'dn:number')
    end
    if source.type == 'integer' then
        pushForward(noders, id, 'dn:integer')
    end
    if source.type == 'nil' then
        pushForward(noders, id, 'dn:nil')
    end
    -- self -> mt:xx
    if source.type == 'local' and source[1] == 'self' then
        local func = guide.getParentFunction(source)
        if func.isGeneric then
            return
        end
        if source.parent.type ~= 'funcargs' then
            return
        end
        local setmethod = func.parent
        -- guess `self`
        if setmethod and ( setmethod.type == 'setmethod'
                        or setmethod.type == 'setfield'
                        or setmethod.type == 'setindex') then
            pushForward(noders, id, getID(setmethod.node))
            pushBackward(noders, getID(setmethod.node), id, {
                deep = true,
            })
        end
    end
    -- 分解 @type
    --if source.type == 'doc.type' then
    --    if source.bindSources then
    --        for _, src in ipairs(source.bindSources) do
    --            pushForward(noders, getID(src), id)
    --            pushForward(noders, id, getID(src))
    --        end
    --    end
    --    for _, enumUnit in ipairs(source.enums) do
    --        pushForward(noders, id, getID(enumUnit))
    --    end
    --    for _, resumeUnit in ipairs(source.resumes) do
    --        pushForward(noders, id, getID(resumeUnit))
    --    end
    --    for _, typeUnit in ipairs(source.types) do
    --        local unitID = getID(typeUnit)
    --        pushForward(noders, id, unitID)
    --        if source.bindSources then
    --            for _, src in ipairs(source.bindSources) do
    --                pushBackward(noders, unitID, getID(src))
    --            end
    --        end
    --    end
    --end
    -- 分解 @alias
    if source.type == 'doc.alias' then
        pushForward(noders, getID(source.alias), getID(source.extends))
    end
    -- 分解 @class
    if source.type == 'doc.class' then
        pushForward(noders, id, getID(source.class))
        pushForward(noders, getID(source.class), id)
        if source.extends then
            for _, ext in ipairs(source.extends) do
                pushBackward(noders, id, getID(ext))
            end
        end
        if source.bindSources then
            for _, src in ipairs(source.bindSources) do
                pushForward(noders, getID(src), id)
                pushForward(noders, id, getID(src))
            end
        end
        for _, field in ipairs(source.fields) do
            local key = field.field[1]
            if key then
                local keyID = ('%s%s%q'):format(
                    id,
                    SPLIT_CHAR,
                    key
                )
                pushForward(noders, keyID, getID(field.field))
                pushForward(noders, getID(field.field), keyID)
                pushForward(noders, keyID, getID(field.extends))
                pushBackward(noders, getID(field.extends), keyID)
            end
        end
    end
    if source.type == 'doc.param' then
        pushForward(noders, id, getID(source.extends))
        for _, src in ipairs(source.bindSources) do
            if src.type == 'local' and src.parent.type == 'in' then
                pushForward(noders, getID(src), id)
            end
        end
    end
    if source.type == 'doc.vararg' then
        pushForward(noders, getID(source), getID(source.vararg))
    end
    if source.type == 'doc.see' then
        local nameID  = getID(source.name)
        local classID = nameID:gsub('^dsn:', 'dn:')
        pushForward(noders, nameID, classID)
        if source.field then
            local fieldID      = getID(source.field)
            local fieldClassID = fieldID:gsub('^dsn:', 'dn:')
            pushForward(noders, fieldID, fieldClassID)
        end
    end
    m.compileDocValue(noders, source.type, id, source)
    if source.type == 'call' then
        if source.parent.type ~= 'select' then
            compileCallReturn(noders, source, id, 1)
        end
        compileCallParam(noders, source, id)
    end
    if source.type == 'select' then
        if source.vararg.type == 'call' then
            local call = source.vararg
            compileCallReturn(noders, call, id, source.sindex)
        end
        if source.vararg.type == 'varargs' then
            pushForward(noders, id, getID(source.vararg))
        end
    end
    if source.type == 'doc.type.function' then
        if source.returns then
            for index, rtn in ipairs(source.returns) do
                local returnID = ('%s%s%s'):format(
                    id,
                    RETURN_INDEX,
                    index
                )
                pushForward(noders, returnID, getID(rtn))
            end
            for index, param in ipairs(source.args) do
                local paramID = ('%s%s%s'):format(
                    id,
                    PARAM_INDEX,
                    index
                )
                pushForward(noders, paramID, getID(param.extends))
            end
        end
        -- @type fun(x: T):T 的情况
        local docType = getDocStateWithoutCrossFunction(source)
        if docType and docType.type == 'doc.type' then
            guide.eachSourceType(source, 'doc.type.name', function (typeName)
                if typeName.typeGeneric then
                    source.isGeneric = true
                    return false
                end
            end)
        end
    end
    if source.type == 'doc.type.name' then
        local uri = guide.getUri(source)
        collector.subscribe(uri, id, getNode(noders, id))
    end
    if source.type == 'doc.class.name'
    or source.type == 'doc.alias.name' then
        local uri = guide.getUri(source)
        collector.subscribe(uri, id, getNode(noders, id))

        local defID = 'def:' .. id
        collector.subscribe(uri, defID, getNode(noders, defID))
        m.pushSource(noders, source, defID)

        local defAnyID = 'def:dn:'
        collector.subscribe(uri, defAnyID, getNode(noders, defAnyID))
        m.pushSource(noders, source, defAnyID)
    end
    if id and id:sub(1, 2) == 'g:' then
        local uri = guide.getUri(source)
        collector.subscribe(uri, id, getNode(noders, id))
        if guide.isSet(source) then

            local defID = 'def:' .. id
            collector.subscribe(uri, defID, getNode(noders, defID))
            m.pushSource(noders, source, defID)

            if guide.isGlobal(source) then
                local defAnyID = 'def:g:'
                collector.subscribe(uri, defAnyID, getNode(noders, defAnyID))
                m.pushSource(noders, source, defAnyID)
            end
        end
    end
    -- 将函数的返回值映射到具体的返回值上
    if source.type == 'function' then
        local hasDocReturn = {}
        -- 检查 luadoc
        if source.bindDocs then
            for _, doc in ipairs(source.bindDocs) do
                if doc.type == 'doc.return' then
                    for _, rtn in ipairs(doc.returns) do
                        local fullID = ('%s%s%s'):format(
                            id,
                            RETURN_INDEX,
                            rtn.returnIndex
                        )
                        pushForward(noders, fullID, getID(rtn))
                        for _, typeUnit in ipairs(rtn.types) do
                            pushBackward(noders, getID(typeUnit), fullID, {
                                deep      = true,
                                dontCross = true,
                            })
                        end
                        hasDocReturn[rtn.returnIndex] = true
                    end
                end
                if doc.type == 'doc.param' then
                    local paramName = doc.param[1]
                    if source.docParamMap then
                        local paramIndex = source.docParamMap[paramName]
                        local param = source.args[paramIndex]
                        if param then
                            pushForward(noders, getID(param), getID(doc))
                            param.docParam = doc
                            local paramID = ('%s%s%s'):format(
                                id,
                                PARAM_INDEX,
                                paramIndex
                            )
                            pushForward(noders, paramID, getID(doc.extends))
                        end
                    end
                end
                if doc.type == 'doc.vararg' then
                    if source.args then
                        for _, param in ipairs(source.args) do
                            if param.type == '...' then
                                pushForward(noders, getID(param), getID(doc))
                            end
                        end
                    end
                end
                if doc.type == 'doc.generic' then
                    source.isGeneric = true
                end
                if doc.type == 'doc.overload' then
                    pushForward(noders, id, getID(doc.overload))
                end
            end
        end
        -- 检查实体返回值
        if source.returns then
            local returns = {}
            for _, rtn in ipairs(source.returns) do
                for index, rtnObj in ipairs(rtn) do
                    if not hasDocReturn[index] then
                        if not returns[index] then
                            returns[index] = {}
                        end
                        returns[index][#returns[index]+1] = rtnObj
                    end
                end
            end
            for index, rtnObjs in ipairs(returns) do
                local returnID = ('%s%s%s'):format(
                    id,
                    RETURN_INDEX,
                    index
                )
                for _, rtnObj in ipairs(rtnObjs) do
                    pushForward(noders, returnID, getID(rtnObj))
                    pushBackward(noders, getID(rtnObj), returnID, {
                        deep      = true,
                        dontCross = true,
                    })
                end
            end
        end
    end
    if source.type == 'table' then
        local firstField = source[1]
        if firstField then
            if firstField.type == 'varargs' then
                local keyID = ('%s%s'):format(
                    id,
                    TABLE_KEY
                )
                local valueID = ('%s%s'):format(
                    id,
                    ANY_FIELD
                )
                source.array = firstField
                pushForward(noders, keyID, 'dn:integer')
                pushForward(noders, valueID, getID(firstField))
            else
                local keyID = ('%s%s'):format(
                    id,
                    WEAK_TABLE_KEY
                )
                local valueID = ('%s%s'):format(
                    id,
                    WEAK_ANY_FIELD
                )
                if firstField.type == 'tablefield' then
                    pushForward(noders, keyID, 'dn:string')
                    pushForward(noders, valueID, getID(firstField.value))
                elseif firstField.type == 'tableindex' then
                    pushForward(noders, keyID,   getID(firstField.index))
                    pushForward(noders, valueID, getID(firstField.value))
                else
                    pushForward(noders, keyID,   'dn:integer')
                    pushForward(noders, valueID, getID(firstField))
                end
            end
        end
    end
    if source.type == 'main' then
        if source.returns then
            for _, rtn in ipairs(source.returns) do
                local rtnObj = rtn[1]
                if rtnObj then
                    pushForward(noders, 'mainreturn', getID(rtnObj))
                    pushBackward(noders, getID(rtnObj), 'mainreturn', {
                        deep = true,
                    })
                end
            end
        end
    end
    if source.type == 'generic.closure' then
        for i, rtn in ipairs(source.returns) do
            local closureID = ('%s%s%s'):format(
                id,
                RETURN_INDEX,
                i
            )
            local returnID = getID(rtn)
            pushForward(noders, closureID, returnID)
        end
    end
    if source.type == 'generic.value' then
        local proto    = source.proto
        local closure  = source.closure
        local upvalues = closure.upvalues
        if proto.type == 'doc.type.name' then
            local key = proto[1]
            if upvalues[key] then
                for _, paramID in ipairs(upvalues[key]) do
                    pushForward(noders, id, paramID)
                    pushBackward(noders, paramID, id)
                end
            end
        end
        --if proto.type == 'doc.type' then
        --    for _, tp in ipairs(source.types) do
        --        pushForward(noders, id, getID(tp))
        --        pushBackward(noders, getID(tp), id)
        --    end
        --end
        m.compileDocValue(noders, proto.type, id, source)
    end
end

---根据ID来获取所有的node
---@param root parser.guide.object
---@param id string
---@return node?
function m.getNodeByID(root, id)
    root = guide.getRoot(root)
    local noders = root._noders
    if not noders then
        return nil
    end
    return noders[id]
end

---根据ID来获取第一个节点的ID
---@param id string
---@return string
function m.getFirstID(id)
    local firstID, count = id:match(FIRST_REGEX)
    if count == 0 then
        return nil
    end
    if firstID == '' then
        return nil
    end
    return firstID
end

---根据ID来获取第一个节点的ID或field
---@param id string
---@return string
function m.getHeadID(id)
    local headID, count = id:match(HEAD_REGEX)
    if count == 0 then
        return nil
    end
    if headID == '' then
        return nil
    end
    return headID
end

---根据ID来获取上个节点的ID
---@param id string
---@return string
function m.getLastID(id)
    local lastID, count = id:gsub(LAST_REGEX, '')
    if count == 0 then
        return nil
    end
    if lastID == '' then
        return nil
    end
    return lastID
end

---获取ID的长度
---@param id string
---@return integer
function m.getIDLength(id)
    if not id then
        return 0
    end
    local _, count = id:gsub(SPLIT_CHAR, SPLIT_CHAR)
    return count + 1
end

---测试id是否包含field,如果遇到函数调用则中断
---@param id string
---@return boolean
function m.hasField(id)
    local firstID = m.getFirstID(id)
    if firstID == id or not firstID then
        return false
    end
    local nextChar = id:sub(#firstID + 1, #firstID + 1)
    if nextChar ~= SPLIT_CHAR then
        return false
    end
    local next2Char = id:sub(#firstID + 2, #firstID + 2)
    if next2Char == RETURN_INDEX
    or next2Char == PARAM_INDEX then
        return false
    end
    return true
end

---把形如 `@file:\\\XXXXX@gv:1|1`拆分成uri与id
---@param id string
---@return uri? string
---@return string id
function m.getUriAndID(id)
    local uri, newID = id:match(URI_REGEX)
    return uri, newID
end

---是否是普通的field,例如数字或字符串,而不是函数返回值等
---@param field any
function m.isCommonField(field)
    if not field then
        return false
    end
    if field:sub(1, #RETURN_INDEX) == RETURN_INDEX then
        return false
    end
    if field:sub(1, #PARAM_INDEX) == PARAM_INDEX then
        return false
    end
    return true
end

---获取source的ID
---@param source parser.guide.object
---@return string
function m.getID(source)
    return getID(source)
end

---获取source的key
---@param source parser.guide.object
---@return string
function m.getKey(source)
    return getKey(source)
end

---清除临时id(用于泛型的临时对象)
---@param root parser.guide.object
---@param id string
function m.removeID(root, id)
    if not id then
        return
    end
    root = guide.getRoot(root)
    local noders = root._noders
    noders[id] = nil
end

---寻找doc的主体
---@param doc parser.guide.object
function m.getDocState(doc)
    return getDocStateWithoutCrossFunction(doc)
end

---获取对象的noders
---@param source parser.guide.object
---@return noders
function m.getNoders(source)
    local root = guide.getRoot(source)
    if not root._noders then
        root._noders = {}
    end
    return root._noders
end

---编译整个文件的node
---@param  source parser.guide.object
---@return table
function m.compileNodes(source)
    local root = guide.getRoot(source)
    local noders = m.getNoders(source)
    if next(noders) then
        return noders
    end
    log.debug('compileNodes:', guide.getUri(root))
    collector.dropUri(guide.getUri(root))
    guide.eachSource(root, function (src)
        m.pushSource(noders, src)
        m.compileNode(noders, src)
    end)
    log.debug('compileNodes finish:', guide.getUri(root))
    return noders
end

files.watch(function (ev, uri)
    uri = files.asKey(uri)
    if ev == 'update' then
        local state = files.getState(uri)
        if state then
            m.compileNodes(state.ast)
        end
    end
    if ev == 'remove' then
        collector.dropUri(uri)
    end
end)

return m