-
Notifications
You must be signed in to change notification settings - Fork 350
/
docSymbolProcesser.ts
1899 lines (1714 loc) · 69.7 KB
/
docSymbolProcesser.ts
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
// Tencent is pleased to support the open source community by making LuaPanda available.
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
// https://opensource.org/licenses/BSD-3-Clause
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
/* 本文件的作用是遍历一个文件url对应的AST树,并在遍历过程中记录一些信息
通常在三种情况下会遍历AST。
1 由AST构建定义符号表
2 已经有一个符号位置,由AST中查找其对应的符号
3 给定一个符号信息,由这个信息查询所有引用这个符号的位置
本文件还提供在构建的定义表只能中搜索符号的能力searchMatchSymbal,支持各种搜索方式
本文件的公有方法分为几部分:
+ 静态创建方法
+ 获取本url及对应AST信息
+ 功能实现接口
+ 符号查找(多种方式)
私有方法
+ 工具方法
+ AST分析后的尾处理
+ 遍历AST
+ 时序处理:分析不完整的AST
*/
import * as luaparse from 'luaparse';
import * as Tools from './codeTools';
import { Logger } from './codeLogManager';
import { CodeSymbol } from './codeSymbol';
import { Location, Range, Position, SymbolKind } from 'vscode-languageserver';
// import { isArray } from 'util';
// 遍历AST模式
enum travelMode {
BUILD = 0, //构建定义符号
GET_DEFINE = 1, //查找定义符号
FIND_REFS = 2 //查找引用符号
}
export class DocSymbolProcesser {
private docInfo: Tools.docInformation; // 记录.lua文本中的所有信息
// 下面是临时记录信息的变量
// refs 引用相关
private searchInfo; //记录被查找的符号信息
private refsLink; //引用符号队列
// 按位置查找符号
private searchPosition: Position; // 记录搜索符号所在的Position
private posSearchRet: Tools.searchRet; // 记录按配置查找的结果
//解析相关
public parseError = false; // 记录解析失败
public static tempSaveInstance; // 临时记录实例
//build 相关
private docCommentType; //注释(等号)类型表 | 符号标记类型 记录标记的类型信息。标记来源于 1.用户注释 2.元表 3. 等号
private funcReturnRecoder; // 用来记录每个函数符号的返回值,并放入符号列表的 chunk 结构中
private callFunctionRecoder; //用来记录函数调用
// 静态创建方法,创建文件的 定义符号列表(定义符号tools.docInformation 数组)
public static create(luaText: string, uri: string, path?: string) {
let instance: DocSymbolProcesser = new DocSymbolProcesser();
if(!path){
path = Tools.uriToPath(uri);
}
try {
let AST = luaparse.parse(luaText, { locations: true, scope: true, comments: true});
instance.docInfo = new Tools.docInformation(AST, uri, path);
instance.buildDocDefineSymbols();
instance.parseError = false;
return instance;
} catch (error) {
Logger.ErrorLog("[Error] 解析文件 " + uri + " AST的过程中出错:");
Logger.ErrorLog("[error stack]:" + error.stack );
//建立空文件(没有AST)
instance.docInfo = new Tools.docInformation(new Object, uri, path);
DocSymbolProcesser.tempSaveInstance = instance;
//解析
try {
luaparse.parse(luaText, { locations: true, scope: true, onCreateNode: instance.onCreateNode});
}catch{}
instance.parseError = true;
return instance;
}
}
//-----------------------------------------------------------------------------
//-- get/set 获取本文件的基础信息
//-----------------------------------------------------------------------------
// 获取本文件uri
public getUri() {
return this.docInfo.docUri;
}
// 获取本文件 [所有符号列表] (kv)
public getAllSymbolsDic() {
return this.docInfo.defineSymbols.allSymbols;
}
// 获取本文件 [全局符号列表] (kv)
public getGlobalSymbolsDic() {
return this.docInfo.defineSymbols.globalSymbols;
}
// 获取本文件 [局部符号列表] (kv)
public getLocalSymbolsDic() {
return this.docInfo.defineSymbols.localSymbols;
}
// 获取本文件 [chunk信息列表] (kv)
public getChunksDic(){
return this.docInfo.defineSymbols.chunks;
}
// 因为符号kv dic中存在冲突,所以新增了返回array接口
public getAllSymbolsArray() {
return this.docInfo.defineSymbols.allSymbolsArray;
}
// 获取本文件 [全局符号列表] (array)
public getGlobalSymbolsArray() {
return this.docInfo.defineSymbols.globalSymbolsArray;
}
// 获取本文件 [局部符号列表] (array)
public getLocalSymbolsArray() {
return this.docInfo.defineSymbols.localSymbolsArray;
}
// 获取本文件 [chunk信息列表] (array)
public getChunksArray(){
return this.docInfo.defineSymbols.chunksArray;
}
// 获取本文件 [返回值列表] (array)
public getFileReturnArray(){
let chunks = this.docInfo.defineSymbols.chunks;
return chunks[this.docInfo.docPath].returnSymbol;
}
// 获取本文件 [require列表] (array)
public getRequiresArray(){
return this.docInfo.requires;
}
// 获取本文件的[被引用信息] (array)
public getReferencesArray() {
return this.docInfo.references;
}
// 设置本文件的被引用信息
public setReferences(references: string[]) {
return this.docInfo.references = references;
}
//-----------------------------------------------------------------------------
//-- 主要对外接口
//-----------------------------------------------------------------------------
// 构建文件的 [定义符号表]
public buildDocDefineSymbols() {
let deepLayer: Array<Tools.chunkClass> = new Array<Tools.chunkClass>();
this.docCommentType = new Array();
this.callFunctionRecoder = new Array();
// 由AST建立符号表
this.traversalAST(this.docInfo["docAST"], travelMode.BUILD, deepLayer);
// 符号表后处理,记录comment和文件/函数返回值
this.buildSymbolTag();
this.buildSymbolReturns(); // 构建 B = require("A") , 记录B的类型
// Debug info 查看序列化的AST
// let tempStr = JSON.stringify(this.docInfo["docAST"]);
// DebugInfo
// console.log(tempStr)
}
// 根据 VSCode 传来的 Position 信息从文件 AST 中查找对应符号
// 这里可以考虑从AST中或者从luaText中查找。使用AST的优点是可以查询到更多的信息,包括isLocal,container。使用 text查找比较快,但只有文本信息。
// 使用luaText查找的好处是可以搜索未完成的代码
// 目前 定义查找使用 AST, 代码补全使用 luaText
public searchDocSymbolfromPosition(pos) {
this.searchPosition = pos;
let container = new Array<Tools.chunkClass>();
this.posSearchRet = new Tools.searchRet();
this.traversalAST(this.docInfo["docAST"], travelMode.GET_DEFINE, container);
return { sybinfo: this.posSearchRet.retSymbol, container: container };
}
// 查找一个符号的引用
public searchDocSymbolReference(info) {
//先清空数组
this.searchInfo = info;
this.refsLink = new Array(); // 引用符号队列
this.traversalAST(this.docInfo["docAST"], travelMode.FIND_REFS, new Array());
return this.refsLink;
}
// 按 position 搜索符号是否是文件名(用于点击require文件名跳转)
public searchDocRequireFileNameFromPosition(pos):string {
let reqFiles = this.getRequiresArray();
for (let index = 0; index < reqFiles.length; index++) {
const element = reqFiles[index];
let res = this.isInASTLoc(element.loc, pos);
if(res){
return element.reqName;
}
}
}
// 在当前 文件的定义符号表中查找符号(提供多种查找方式,查找范围)
// @symbalName 符号名
// @matchMode 搜索方式
// @searchRange 0:all 1 global 2 display
public searchMatchSymbal(symbalName: string, matchMode: Tools.SearchMode, searchRange?: Tools.SearchRange ): Tools.SymbolInformation[] {
searchRange = searchRange || Tools.SearchRange.AllSymbols ;
let retSymbols = [];
let SymbolArrayForSearch;
// let reg = /[A-Z]/;
//精确查找。直接使用字典匹配
if (matchMode === Tools.SearchMode.ExactlyEqual) {
if( searchRange == Tools.SearchRange.AllSymbols ){
SymbolArrayForSearch = this.getAllSymbolsDic();
}else if( searchRange == Tools.SearchRange.GlobalSymbols){
SymbolArrayForSearch = this.getGlobalSymbolsDic() ;
}else if( searchRange == Tools.SearchRange.LocalSymbols){
SymbolArrayForSearch = this.getLocalSymbolsDic();
}
//精确匹配 searchName
let tgtSymbol = SymbolArrayForSearch[symbalName];
if(tgtSymbol){
if(Array.isArray(tgtSymbol)){
retSymbols = tgtSymbol;
}else{
retSymbols.push(tgtSymbol);
}
}else{
//把: 替换成.尝试再次匹配
symbalName = symbalName.replace(/:/g,".");
let tgtSymbol = SymbolArrayForSearch[symbalName];
if(!tgtSymbol){
symbalName = symbalName.replace(/\./g,":");
tgtSymbol = SymbolArrayForSearch[symbalName];
}
if(tgtSymbol){
if(Array.isArray(tgtSymbol)){
retSymbols = tgtSymbol;
}else{
retSymbols.push(tgtSymbol);
}
}
}
}else{
if( searchRange == Tools.SearchRange.AllSymbols ){
SymbolArrayForSearch = this.getAllSymbolsArray();
}else if( searchRange == Tools.SearchRange.GlobalSymbols){
SymbolArrayForSearch = this.getGlobalSymbolsArray();
}else if( searchRange == Tools.SearchRange.LocalSymbols){
SymbolArrayForSearch = this.getLocalSymbolsArray();
}
// let hasUpper = symbalName.match(reg);
for (let idx in SymbolArrayForSearch){
let sym = SymbolArrayForSearch[idx];
if (matchMode === Tools.SearchMode.ContinuousMatching) {
//连续查找 name
let res = sym.name.match(symbalName);
if (res != null) {
retSymbols.push(sym);
}
} else if (matchMode === Tools.SearchMode.FuzzyMatching) {
//模糊查找 当前只用于 @ # 的符号查找,所以搜索 name
let inputArray = symbalName.split('');
let pattStr = inputArray.join('.*?');
let pattRegExp = new RegExp(pattStr, "i");
let res = sym.name.match(pattRegExp);
if (res != null) {
retSymbols.push(sym);
}
} else if (matchMode === Tools.SearchMode.FirstLetterContinuousMatching) {
//在这种模式中,如果用户输入的字符串中有大写字母,则大小写敏感。否则大小写不敏感
let searchName = sym.searchName;
if(searchName){
let reg1 = new RegExp( /[\.:]/, 'g')
let symbalName_dot = symbalName.replace( reg1 , '.' );
let reg = new RegExp( '^' + symbalName_dot ,'i');
let hit = searchName.match(reg);
if(hit){
retSymbols.push(sym);
}
//首字母起始连续查找 searchName
// searchName = searchName.replace(/:/g,".");
// symbalName = symbalName.replace(/:/g,".");
}
}
}
}
return retSymbols;
}
//-----------------------------------------------------------------------------
//-- 以下是遍历AST的私有方法
//-- 工具方法
//-----------------------------------------------------------------------------
// loc2是否在loc1之中
private isInLocation(loc1, loc2: Position): boolean {
if (loc1.range.start.line <= loc2.line && loc1.range.end.line >= loc2.line) {
if (loc1.range.start.line === loc2.line) {
let character = loc1.range.start.character || loc1.range.start.column;
//start > pos
if (character > loc2.character) return false;
}
if (loc1.range.end.line === loc2.line) {
let character = loc1.range.end.character || loc1.range.end.column;
if (character < loc2.character) return false;
}
return true;
}
return false;
}
//list2是否是list1的子集
// private listContainer(list1, list2): boolean {
// if(list2.length > list1.length) return false;
// for(let idx = 0, len = list2.length ; idx < len; idx++){
// if(list1[idx] != list2[idx]){
// return false;
// }
// }
// return true;
// }
// 判断 loc2 是否被包含在 loc1 之中
private isInASTLoc(loc1, loc2: Position): boolean {
if (loc1["start"].line <= loc2.line && loc1["end"].line >= loc2.line) {
if (loc1.start.line === loc2.line) {
let character = loc1.start.character || loc1.start.column;
//start > pos
if (character > loc2.character) return false;
}
if (loc1.end.line === loc2.line) {
let character = loc1.end.character || loc1.end.column;
if (character < loc2.character) return false;
}
return true;
}
return false;
}
// 创建一个符号的信息
private createSymbolInfo(name: string, searchName:string, originalName:string,
kind:SymbolKind, location:Location, isLocal:boolean,
containerName?:string, containerList?:Array<Tools.chunkClass>, funcParamArray?:Array<string>, tagType? :string, reason?: Tools.TagReason): Tools.SymbolInformation{
let showName = name;
if(isLocal){
showName = "local " + showName;
}
return{
name: showName,
searchName: searchName,
originalName: originalName,
kind: kind,
location: location,
isLocal: isLocal,
containerURI: this.docInfo["docUri"],
containerPath: this.docInfo["docPath"],
containerName: containerName,
containerList: containerList,
funcParamArray:funcParamArray,
// alreadyAddDisplay: false,
tagType:tagType,
tagReason:reason
};
}
// 检查符号是否已经在符号表中存在
// @name 符号名
private checkIsSymbolExist(name) {
if (this.getAllSymbolsDic()[name] != undefined){
return true;
}
return false;
}
//-------查到符号后的填充
private pushToAllList(symbol:Tools.SymbolInformation){
if(this.docInfo.defineSymbols.allSymbols[symbol.searchName]){
let travlSymbol = this.docInfo.defineSymbols.allSymbols[symbol.searchName];
//判断是否数组
if ( Array.isArray(travlSymbol) ){
travlSymbol.push(symbol);
}else{
//只有一个元素,还不是数组
let newArray = new Array();
newArray.push(travlSymbol);
newArray.push(symbol);
this.docInfo.defineSymbols.allSymbols[symbol.searchName] = newArray;
}
}else{
this.docInfo.defineSymbols.allSymbols[symbol.searchName] = symbol;
}
//放入array队列
this.docInfo.defineSymbols.allSymbolsArray.push(symbol);
}
private pushToLocalList(symbol:Tools.SymbolInformation){
if(this.docInfo.defineSymbols.localSymbols[symbol.searchName]){
let travlSymbol = this.docInfo.defineSymbols.localSymbols[symbol.searchName];
if ( Array.isArray(travlSymbol) ){
travlSymbol.push(symbol);
}else{
let newArray = new Array();
newArray.push(travlSymbol);
newArray.push(symbol);
this.docInfo.defineSymbols.localSymbols[symbol.searchName] = newArray;
}
}else{
this.docInfo.defineSymbols.localSymbols[symbol.searchName] = symbol;
}
//放入array队列
this.docInfo.defineSymbols.localSymbolsArray.push(symbol);
}
// 把symbol信息放入 docGlobalSymbols | 注意这里是 kv 形式
private pushToGlobalList(symbol:Tools.SymbolInformation){
if(this.docInfo.defineSymbols.globalSymbols[symbol.searchName]){
let travlSymbol = this.docInfo.defineSymbols.globalSymbols[symbol.searchName];
if ( Array.isArray(travlSymbol) ){
travlSymbol.push(symbol);
}else{
let newArray = new Array();
newArray.push(travlSymbol);
newArray.push(symbol);
this.docInfo.defineSymbols.globalSymbols[symbol.searchName] = newArray;
}
}else{
this.docInfo.defineSymbols.globalSymbols[symbol.searchName] = symbol;
}
//放入array队列
this.docInfo.defineSymbols.globalSymbolsArray.push(symbol);
}
// 根据符号自动识别应该放入哪个列表
private pushToAutoList(symbol:Tools.SymbolInformation){
if(symbol.isLocal){
this.pushToLocalList(symbol);
}else{
this.pushToGlobalList(symbol);
}
this.pushToAllList(symbol);
}
private pushToChunkList(name, chunk){
if(this.docInfo.defineSymbols["chunks"][name]){
let travlSymbol = this.docInfo.defineSymbols["chunks"][name];
if ( Array.isArray(travlSymbol) ){
travlSymbol.push(chunk);
}else{
let newArray = new Array();
newArray.push(travlSymbol);
newArray.push(chunk);
this.docInfo.defineSymbols["chunks"][name] = newArray;
}
}else{
this.docInfo.defineSymbols["chunks"][name] = chunk;
}
//放入array队列
this.docInfo.defineSymbols.chunksArray.push(chunk);
}
private pushToCommentList(cmt:Tools.commentTypeInfo){
this.docCommentType.push(cmt);
}
// 记录函数调用
private recordFuncCall(cmt:Tools.functionRetInfo){
this.callFunctionRecoder.push(cmt);
}
//------------
//-----------------------------------------------------------------------------
//-- 遍历AST
//-----------------------------------------------------------------------------
// 遍历AST
// @node AST 当前节点
// @type : travelMode.BUILD / travelMode.FIND_DEFINE / travel.FIND_REFS
// @deepLayer 深度队列。用来指示当前symbol所在的chunk
// @prefix 前缀。用来指示当前symbol所在chunk (此信息直接展示给用户)
// @isBody ?
private traversalAST(node, type : travelMode, deepLayer: Array <Tools.chunkClass>, prefix?: string, isBody?:boolean) {
//传入的node是一个数组的时候,traversalAST递归其中每一个元素
if (Array.isArray(node) === true) {
let ASTArray = Array.prototype.slice.call(node);
for (let idx = 0, len = ASTArray.length; idx < len; idx++) {
this.traversalAST(ASTArray[idx], type, deepLayer, prefix, isBody);
if (this.posSearchRet && this.posSearchRet.isFindout) return;
}
} else {
let nodeType = node["type"];
switch (nodeType) {
//container
case 'Chunk': this.processChunk(node, type, deepLayer, prefix); break;
case 'LocalStatement': this.LocalStatement(node, type, deepLayer, prefix); break;
case 'FunctionDeclaration': this.processFunction(node, type, deepLayer, prefix); break;
case 'AssignmentStatement': this.processAssignment(node, type, deepLayer, prefix); break;
case 'CallExpression': this.processCallExpression(node, type, deepLayer, prefix); break;
case 'StringCallExpression': this.processStringCallExpression(node, type, deepLayer, prefix); break;
case 'CallStatement': this.processCallStatement(node, type, deepLayer, prefix); break;
//循环结构,其中可能有定义,也可能有查找的符号
case 'WhileStatement': this.processWhileStatement(node, type, deepLayer, prefix); break;
case 'RepeatStatement': this.processRepeatStatement(node, type, deepLayer, prefix); break;
case 'IfStatement': this.processIfStatement(node, type, deepLayer, prefix); break;
case 'ReturnStatement': this.processReturnStatement(node, type, deepLayer, prefix, isBody); break;
case 'ForNumericStatement': this.processForNumericStatement(node, type, deepLayer, prefix); break;
case 'ForGenericStatement': this.processForGenericStatement(node, type, deepLayer, prefix); break;
//二进制表达式 a == b
case 'BinaryExpression': this.processBinaryExpression(node, type, deepLayer, prefix); break;
case 'UnaryExpression': this.processUnaryExpression(node, type, deepLayer, prefix); break;
// case 'TableConstructorExpression': retsyb = this.processTableConstructorExpression(ASTNode, type, deepLayer, prefix); break;
case 'MemberExpression': this.processMemberExpression(node, type, deepLayer, prefix); break;
case 'IndexExpression': this.processIndexExpression(node, type, deepLayer, prefix); break;
// Terminal
case 'Identifier': this.processIdentifier(node, type, deepLayer, prefix); break;
}
}
if (this.posSearchRet && this.posSearchRet.isFindout) return;
}
// ------异常处理
//分析不完全AST时的回调,这里只处理有限的情况
// 把symbol信息放入docSymbols
// luaparse.parse 方法创建AST Node时的回调。这里只处理有限的接口
private onCreateNode(node){
//require
let deepLayer: Array<Tools.chunkClass> = new Array<Tools.chunkClass>();
if(node['type'] == 'CallExpression' || node['type'] == 'StringCallExpression'){
DocSymbolProcesser.tempSaveInstance.traversalAST(node, travelMode.BUILD, deepLayer);
}
//定义 | 可以处理,但是失去了深度信息
if(node['type'] == "LocalStatement"){
DocSymbolProcesser.tempSaveInstance.traversalAST(node, travelMode.BUILD, deepLayer);
}
//function 定义
if(node['type'] == "FunctionDeclaration"){
DocSymbolProcesser.tempSaveInstance.traversalAST(node, travelMode.BUILD, deepLayer);
}
}
//---------前处理和后处理
// 处理注释. 基本思路是在注释中查询 -@type
// 用一个结构体记录位置和类型,并放入CommentList中
private processComments(commentArray){
for (let idx = 0, len = commentArray.length; idx < len; idx++) {
let comValue = commentArray[idx].value;
let strArr = comValue.split(' ')
for (let j = 0; j < strArr.length; j++) {
const element = strArr[j];
if(element.match('-@type')){
let info = {
reason: Tools.TagReason.UserTag,
newType: strArr[j + 1],
location : commentArray[idx].loc
}
this.pushToCommentList(info);
}
}
}
}
/**
* 记录反向引用关系
* @param requireName require语句中的文件名
* @param fileUri 调用require语句的文件的uri
*/
private recordReference(fileUri: string, requireName: string) {
let requireFileUri = Tools.transFileNameToUri(requireName);
if (requireFileUri == "") {
// 未找到require的文件
return;
}
// 被require的文件还没有处理,先创建符号
if (CodeSymbol.docSymbolMap.has(requireFileUri) == false) {
CodeSymbol.createCertainDocSymbols(requireFileUri);
}
let references = CodeSymbol.docSymbolMap.get(requireFileUri).getReferencesArray();
if (references.includes(fileUri)) {
return;
}
references.push(fileUri);
}
private createRetBase(baseName, baseLocal, identifer?): Tools.searchRet {
let retBase: Tools.baseInfo = {
name: baseName,
isLocal: baseLocal,
identiferStr:identifer
};
let ret: Tools.searchRet = { isFindout: false, baseinfo: retBase };
return ret;
}
private createRetSymbol(sybName, sybisLocal, sybLocation?, sybPath?){
sybPath = sybPath || this.docInfo["docPath"];
let retSymbol: Tools.searchSymbolRet = {
name: sybName,
isLocal: sybisLocal,
location: sybLocation,
containerURI: sybPath
};
let ret: Tools.searchRet = { isFindout: true, retSymbol: retSymbol };
return ret;
}
// 记录一个符号的标记和标记原因(准备删除)
private setTagTypeToSymbolInfo(symbol: Tools.SymbolInformation, tagType, tagReason){
symbol.tagType = tagType;
symbol.tagReason = tagReason;
}
//---文件尾处理(生成符号表后,对一些有注释类型的符号,进行添加tag信息)
// 根据docCommentType记录的信息,在符号中标记tag
private buildSymbolTag(){
let tagArray = this.docCommentType;
for(var key in tagArray) {
let tagInfo = tagArray[key];
let loc = tagInfo.location;
let reason = tagInfo.reason;
//从allSymbols中遍历location和tag相符合的符号
for (let index = 0; index < this.getAllSymbolsArray().length; index++) {
const elm = this.getAllSymbolsArray()[index];
//用户标记
if(reason == Tools.TagReason.UserTag && elm.location.range.start.line + 1 === loc['end'].line)
{
this.setTagTypeToSymbolInfo(elm, tagInfo.newType, tagInfo.reason);
break;
}
//相等符号
if(reason == Tools.TagReason.Equal && elm.location.range.start.line + 1 === loc['end'].line)
{
// name : 被赋值符号名
if(tagInfo.name && tagInfo.name == elm.searchName){
this.setTagTypeToSymbolInfo(elm, tagInfo.newType, tagInfo.reason);
break;
}
}
//元表标记
if(reason == Tools.TagReason.MetaTable && elm.searchName == tagInfo.oldType){
this.setTagTypeToSymbolInfo(elm, tagInfo.newType, tagInfo.reason);
break;
}
}
}
}
// 构建文件返回和函数返回
private buildSymbolReturns(){
//设置符号的 requireFile
let reqArray = this.getRequiresArray();
reqArray.forEach(element => {
let loc = element.loc;
let reqName = element.reqName;
for (let index = 0; index < this.getAllSymbolsArray().length; index++) {
const elm = this.getAllSymbolsArray()[index];
let aling = elm.location.range.start.line + 1;
let bling = loc['start'].line;
if(aling == bling )
{
elm.requireFile = reqName;
}
}
});
//设置符号的 function Return
// let retArray = this.callFunctionRecoder;
for (const key in this.callFunctionRecoder ) {
const element = this.callFunctionRecoder[key];
let loc = element.loc;
let funcName = element.functionName;
for (let index = 0; index < this.getAllSymbolsArray().length; index++) {
const elm = this.getAllSymbolsArray()[index];
//用户标记
let aling = elm.location.range.start.line + 1;
let bling = loc['start'].line;
if(aling == bling )
{
elm.funcRets = funcName;
}
}
}
}
//-------尾处理
//-----------------------------------------------------------------------------
//-- 遍历AST主方法
//-----------------------------------------------------------------------------
//base处理,主要工作是拼接变量名 a.b.c.d,并返回base的isLocal (子元素的isLocal跟随base)
private baseProcess(baseNode) {
if (baseNode['type'] == 'MemberExpression') {
let ret = this.baseProcess(baseNode['base']);
if(!ret){
// let ret = this.baseProcess(baseNode['base']);
return;
}
let str = ret.name;
let isLocal = ret.isLocal;
let retStr = str + baseNode['indexer'] + baseNode['identifier']['name'];
let retObj = { name: retStr, isLocal: isLocal, origion: baseNode['identifier']['name'] };
return retObj;
}
else if (baseNode['type'] == 'Identifier') {
return { name: baseNode['name'], isLocal: baseNode['isLocal'] };
}
else if (baseNode['type'] == 'StringLiteral') {
return { name: baseNode['value'], isLocal: false };
}
else if (baseNode['type'] == 'NumericLiteral') {
return { name: baseNode['value'], isLocal: false };
}
else if (baseNode['type'] == 'IndexExpression') {
let ret = this.baseProcess(baseNode['base']);
let str = ret.name;
let isLocal = ret.isLocal;
let retObj;
if(baseNode['index']['type'] == "NumericLiteral"){
let retStr = str + '[' + baseNode['index']['raw'] + ']';
retObj = { name: retStr, isLocal: isLocal, origion: baseNode['index']['raw'] };
}
if(baseNode['index']['type'] == "Identifier"){
let retStr = str + '[' + baseNode['index']['name'] + ']';
retObj = { name: retStr, isLocal: isLocal, origion: baseNode['index']['name'] };
}
if(baseNode['index']['type'] == "MemberExpression"){
let ret = this.baseProcess(baseNode['index']);
let retStr = str + '[' + ret.name + ']';
retObj = { name: retStr, isLocal: isLocal, origion: ret.name };
}
if(baseNode['index']['type'] == "IndexExpression"){
let ret = this.baseProcess(baseNode['index']);
let retStr = str + '[' + ret.name + ']';
retObj = { name: retStr, isLocal: isLocal, origion: ret.name };
}
if(baseNode['index']['type'] == "StringLiteral"){
let ret = this.baseProcess(baseNode['index']);
let retStr = str + '["' + ret.name + '"]';
retObj = { name: retStr, isLocal: isLocal, origion: ret.name };
}
//index 中是一个表达式
if(baseNode['index']['type'] == "BinaryExpression"){
let retL = this.baseProcess(baseNode['index']['left']);
let retR = this.baseProcess(baseNode['index']['right']);
let retStr = str + '[' + retL.name + baseNode['index'].operator + retR.name + ']';
retObj = { name: retStr, isLocal: isLocal, origion: ret.name };
}
return retObj;
}
return { name: '', isLocal: false };
}
//base处理,function a.b.c.d. 当用户点击b的时候返回a.b
private MemberExpressionFind(baseNode) {
if(baseNode == null){
Logger.log("baseNode == null");
}
if (baseNode['type'] == 'MemberExpression') {
//递归向内部取base
let ret = this.MemberExpressionFind(baseNode['base']);
// if(ret && ret.isFindout){
// return ret;
// }
if(ret == null || ret.isInStat == undefined){
ret.isInStat = 0;
}
//判断identifier是否符合?一旦符合,后面的基层及全部加上
let nodeLoc = Location.create(this.docInfo["docUri"], baseNode['identifier']['loc']);
let isIn = this.isInLocation(nodeLoc, this.searchPosition);
if (isIn === true && ret.isInStat === 0) {
ret.isInStat = 1;
}
if (isIn === false && ret.isInStat === 1) {
//stop
return ret;
}
let str = ret.name;
let isLocal = ret.isLocal;
let retStr = str + baseNode['indexer'] + baseNode['identifier']['name'];
return { name: retStr, isLocal: isLocal, isInStat: ret.isInStat };
}
else if (baseNode['type'] == 'IndexExpression') {
//getindex
let ret = this.MemberExpressionFind(baseNode['base']);
// if(ret && ret.isFindout){
// return ret;
// }
if(ret == null || ret.isInStat == undefined){
ret.isInStat = 0;
}
//判断identifier是否符合?一旦符合,后面的基层及全部加上
let nodeLoc = Location.create(this.docInfo["docUri"], baseNode['index']['loc']);
let isIn = this.isInLocation(nodeLoc, this.searchPosition);
if (isIn === true && ret.isInStat === 0) {
ret.isInStat = 1;
}
if (isIn === false && ret.isInStat === 1) {
//stop
return ret;
}
let str = ret.name;
let isLocal = ret.isLocal;
let retStr;
if(baseNode['index']['value']){
retStr = str + '.' + baseNode['index']['value'];
}
if(baseNode['index']['name']){
retStr = this.MemberExpressionFind(baseNode['index']).name;
}
return { name: retStr, isLocal: isLocal, isInStat: ret.isInStat };
}
else if (baseNode['type'] == 'CallExpression') {
this.processCallExpression(baseNode, travelMode.GET_DEFINE , null, "call EXp");
if (this.posSearchRet && this.posSearchRet.isFindout) {
// return retSymbol;
return {name: this.posSearchRet.retSymbol.name, isLocal:this.posSearchRet.retSymbol.isLocal, isInStat:1}
}
else{
return { name: '', isLocal: true, isInStat: 0 };
}
}
else if (baseNode['type'] == 'StringCallExpression') {
this.processStringCallExpression(baseNode, travelMode.GET_DEFINE , null, "call EXp");
if (this.posSearchRet && this.posSearchRet.isFindout) {
// return retSymbol;
return {name: this.posSearchRet.retSymbol.name, isLocal:this.posSearchRet.retSymbol.isLocal, isInStat:1}
}
else{
return { name: '', isLocal: true, isInStat: 0 };
}
}
else if (baseNode['type'] == 'Identifier') {
//base的基层级
let nodeLoc = Location.create(this.docInfo["docUri"], baseNode['loc']);
let isIn = this.isInLocation(nodeLoc, this.searchPosition);
if (isIn === true) {
return { name: baseNode['name'], isLocal: baseNode['isLocal'], isInStat: 1 };
}
else {
return { name: baseNode['name'], isLocal: baseNode['isLocal'], isInStat: 0 };
}
}
}
//处理chunk, 通常是遍历AST的第一步
private processChunk(node, type, deepLayer, prefix){
if (type === travelMode.BUILD) {
this.processComments(node['comments']); //整理记录comment(---@type)
// 把当前文件压入chunk
let newChunk = new Tools.chunkClass(this.docInfo["docPath"] , this.docInfo.docAST.loc);
this.pushToChunkList(this.docInfo["docPath"], newChunk);
// 压入deep layer
deepLayer.push( newChunk ); //记录chunk名(文件名和起始结束行)
this.traversalAST(node["body"], type, deepLayer, prefix, true); // 遍历body
}
if (type === travelMode.GET_DEFINE){
let newChunk = new Tools.chunkClass(this.docInfo["docPath"] , this.docInfo.docAST.loc);
deepLayer.push( newChunk ); //记录chunk名(文件名和起始结束行)
this.traversalAST(node["body"], type, deepLayer, prefix);
if (this.posSearchRet && this.posSearchRet.isFindout) return;
}
if (type === travelMode.FIND_REFS){
this.traversalAST(node["body"], type, deepLayer, prefix);
}
}
// 处理function
private processFunction(node, type, deepLayer: Array<Tools.chunkClass>, prefix?: string) {
let searchRes = false; //整体检查位置是否在 function 中
let paraRecoder = new Array();
// GET_DEFINE 先判断搜索位置是否在 函数location中
if (type === travelMode.GET_DEFINE) {
let nodeLoc = Location.create(this.docInfo["docUri"], node["loc"]);
searchRes = this.isInLocation(nodeLoc, this.searchPosition);
// 用户点搜索的位置不在本function范围内, 清空数据,返回
if(searchRes == false) {
this.posSearchRet = new Tools.searchRet();
}
}
// 1. 记录函数参数
let searchHitPara = false;
let searchHitParaIdx = 0;
let paramArray = new Array();
for (let idx = 0; idx < node["parameters"].length; idx++) {
let paraNode = node["parameters"][idx];
if(paraNode.type == 'VarargLiteral'){
//可变参数
paramArray.push(paraNode['value']);
}else{
paramArray.push(paraNode['name']);
}
//搜索模式,且之前未命中
if (type === travelMode.GET_DEFINE && searchRes === true && searchHitPara === false) {
let nodeLoc1 = Location.create(this.docInfo["docUri"], node["parameters"][idx]["loc"]);
searchHitPara = this.isInLocation(nodeLoc1, this.searchPosition);
if(searchHitPara === true){
searchHitParaIdx = idx;
continue;
}
}
if (type === travelMode.BUILD) {
let loc = paraNode["loc"];
let name;
if(paraNode.type == 'VarargLiteral'){
name = paraNode.value;
}else{
name = paraNode["name"];
}
let isLocal = true; //参数全部是local
let loct = Location.create(this.docInfo["docUri"], Range.create(Position.create(loc["start"]["line"] - 1, loc["start"]["column"]), Position.create(loc["end"]["line"] - 1, loc["end"]["column"])));
let smbInfo = this.createSymbolInfo(name, name, name, SymbolKind.Variable, loct, isLocal, prefix, deepLayer.concat());
paraRecoder.push(smbInfo);
}
}
let paramString = "(" + paramArray.join(", ") + ")";
// 2. 处理函数名,BUILD时记录 chunk 。 并把信息压入 deepLayer
let newChunk; // 临时记录保存在数据结构中的chunk
let functionName; //函数名(name)
let functionSearchName = "NONAME"; //函数searchName
// 有名函数 普通函数的情况 function a()
if (node["identifier"] && node["identifier"]['type'] == 'Identifier') {
let loc = node["identifier"]["loc"];
functionSearchName = node["identifier"]["name"];
functionName = "function " + functionSearchName + paramString;
if (type === travelMode.GET_DEFINE && searchRes === true) {
let nodeLoc1 = Location.create(this.docInfo["docUri"], loc);
let res1 = this.isInLocation(nodeLoc1, this.searchPosition);
if (res1 === true){
this.posSearchRet = this.createRetSymbol(node["identifier"].name, node["identifier"].isLocal);
return;
}
}
if (type === travelMode.FIND_REFS) {
if (functionSearchName == this.searchInfo.originalName){
let loc = node["identifier"]["loc"];
let nodeLoc1 = Location.create(this.docInfo["docUri"], loc);
this.refsLink.push(nodeLoc1);
}
}
if (type === travelMode.BUILD) {
let loct = Location.create(this.docInfo["docUri"], Range.create(Position.create(loc["start"]["line"] - 1, loc["start"]["column"]), Position.create(loc["end"]["line"] - 1, loc["end"]["column"])));
let pushObj = this.createSymbolInfo(functionSearchName, functionSearchName, functionSearchName, SymbolKind.Function, loct, node["identifier"]["isLocal"], prefix, deepLayer.concat(), paramArray);
newChunk = new Tools.chunkClass(functionSearchName, node.loc);
this.pushToChunkList(newChunk.chunkName, newChunk);
pushObj.chunk = newChunk;
this.pushToAutoList(pushObj);
}
//有名函数 成员函数的情况 function a.b()
} else if (node["identifier"] && node["identifier"]['type'] == 'MemberExpression') {
let baseInfo = this.baseProcess(node["identifier"]);
functionSearchName = baseInfo.name;
functionName = 'function ' + functionSearchName + paramString;
if (type === travelMode.GET_DEFINE && searchRes === true) {
let bname = this.MemberExpressionFind(node["identifier"]);
if (bname.isInStat && bname.isInStat > 0) {
this.posSearchRet = this.createRetSymbol(bname.name, bname.isLocal);
return;
}
}