forked from genericptr/pascal-language-server
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdocumentSymbol.pas
1492 lines (1295 loc) · 42.4 KB
/
documentSymbol.pas
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
// Pascal Language Server
// Copyright 2020 Ryan Joseph
// This file is part of Pascal Language Server.
// Pascal Language Server is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
// Pascal Language Server is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Pascal Language Server. If not, see
// <https://www.gnu.org/licenses/>.
unit documentSymbol;
{$mode objfpc}{$H+}
{define NSYMBOL_DEBUG}
interface
uses
Classes, Contnrs, URIParser, fpjson, fpjsonrpc, //SQLite3,
CodeToolManager, CodeCache, CodeTree, LinkScanner,
lsp, basic, codeUtils,fileprocs;
type
TSymbolKind = (
SymbolKindFile = 1,
SymbolKindModule = 2,
SymbolKindNamespace = 3,
SymbolKindPackage = 4,
SymbolKindClass = 5,
SymbolKindMethod = 6,
SymbolKindProperty = 7,
SymbolKindField = 8,
SymbolKindConstructor = 9,
SymbolKindEnum = 10,
SymbolKindInterface = 11,
SymbolKindFunction = 12,
SymbolKindVariable = 13,
SymbolKindConstant = 14,
SymbolKindString = 15,
SymbolKindNumber = 16,
SymbolKindBoolean = 17,
SymbolKindArray = 18,
SymbolKindObject = 19,
SymbolKindKey = 20,
SymbolKindNull = 21,
SymbolKindEnumMember = 22,
SymbolKindStruct = 23,
SymbolKindEvent = 24,
SymbolKindOperator = 25,
SymbolKindTypeParameter = 26
);
{ TDocumentSymbol }
{ Represents programming constructs like variables, classes, interfaces etc. that
appear in a document. Document symbols can be hierarchical and they have two ranges:
one that encloses its definition and one that points to its most interesting range,
e.g. the range of an identifier. }
TDocumentSymbol = class;
TDocumentSymbolItems = specialize TGenericCollection<TDocumentSymbol>;
TDocumentSymbol = class(TCollectionItem)
private
fName: string;
fDetail: string;
fKind: TSymbolKind;
fDeprecated: boolean;
fRange: TRange;
fSelectionRange: TRange;
fChildren: TDocumentSymbolItems;
published
// The name of this symbol. Will be displayed in the user interface and therefore must not be
// an empty string or a string only consisting of white spaces.
property name: string read fName write fName;
// More detail for this symbol, e.g the signature of a function.
property detail: string read fDetail write fDetail;
// The kind of this symbol.
property kind: TSymbolKind read fKind write fKind;
// Indicates if this symbol is deprecated.
property deprecated: boolean read fDeprecated write fDeprecated;
// The range enclosing this symbol not including leading/trailing whitespace but everything else
// like comments. This information is typically used to determine if the clients cursor is
// inside the symbol to reveal in the symbol in the UI.
property range: TRange read fRange write fRange;
// The range that should be selected and revealed when this symbol is being picked, e.g the name of a function.
// Must be contained by the `range`.
property selectionRange: TRange read fSelectionRange write fSelectionRange;
// Children of this symbol, e.g. properties of a class.
property children: TDocumentSymbolItems read fChildren write fChildren;
end;
{ TSymbolInformation }
{ Represents information about programming constructs like variables, classes, interfaces etc. }
TSymbolInformation = class(TCollectionItem)
private
fName: string;
fKind: TSymbolKind;
fDeprecated: TOptionalBoolean;
fLocation: TLocation;
fContainerName: string;
published
// The name of this symbol.
property name: string read fName write fName;
// The kind of this symbol.
property kind: TSymbolKind read fKind write fKind;
// Indicates if this symbol is deprecated.
property deprecated: TOptionalBoolean read fDeprecated write fDeprecated;
// The location of this symbol. The location's range is used by a tool
// to reveal the location in the editor. If the symbol is selected in the
// tool the range's start information is used to position the cursor. So
// the range usually spans more then the actual symbol's name and does
// normally include things like visibility modifiers.
//
// The range doesn't have to denote a node range in the sense of a abstract
// syntax tree. It can therefore not be used to re-construct a hierarchy of
// the symbols.
property location: TLocation read fLocation write fLocation;
// The name of the symbol containing this symbol. This information is for
// user interface purposes (e.g. to render a qualifier in the user interface
// if necessary). It can't be used to re-infer a hierarchy for the document
// symbols.
property containerName: string read fContainerName write fContainerName;
end;
TSymbolInformationItems = specialize TGenericCollection<TSymbolInformation>;
{ TDocumentSymbolParams }
TDocumentSymbolParams = class(TPersistent)
private
fTextDocument: TTextDocumentIdentifier;
published
// The text document.
property textDocument: TTextDocumentIdentifier read fTextDocument write fTextDocument;
end;
{ TDocumentSymbolRequest }
{ The document symbol request is sent from the client to the server. The returned result is either:
* SymbolInformation[] which is a flat list of all symbols found in a given text document.
Then neither the symbol’s location range nor the symbol’s container name should be used to infer a hierarchy.
* DocumentSymbol[] which is a hierarchy of symbols found in a given text document. }
TDocumentSymbolRequest = class(specialize TLSPRequest<TDocumentSymbolParams, TPersistent>)
function DoExecute(const Params: TJSONData; AContext: TJSONRPCCallContext): TJSONData; override;
end;
{ TSymbol }
type
TSymbolFlag = (ForwardClassDefinition);
TSymbolFlags = set of TSymbolFlag;
{ Extra symbol container for storage }
TSymbol = class(TSymbolInformation)
private
function GetFullName: String;
public
RawJSON: String;
Flags: TSymbolFlags;
OverloadCount: integer;
//location: TLocation;
//containerName: String;
function Path: String;
function IsGlobal: boolean;
property FullName: String read GetFullName;
constructor Create; overload;
end;
TSymbolItems = specialize TGenericCollection<TSymbol>;
{ TSymbolTableEntry }
TSymbolTableEntry = class
private
Key: ShortString;
Symbols: TSymbolItems;
Code: TCodeBuffer;
fRawJSON: String;
function GetRawJSON: String; inline;
public
Modified: Boolean;
public
constructor Create(_Code: TCodeBuffer);
destructor Destroy; override;
procedure Clear;
procedure SerializeSymbols;
procedure SerialzeToDocSymbols;
function AddSymbol(Name: String; Kind: TSymbolKind; FileName: String; Line, Column, endLine,endCol: Integer): TSymbol;
function RequestReload: boolean;
function Count: integer; inline;
property RawJSON: String read GetRawJSON;
end;
{ TSymbolExtractor }
TSymbolExtractor = class
private
Code: TCodeBuffer;
Tool: TCodeTool;
Entry: TSymbolTableEntry;
OverloadMap: TFPHashList;
RelatedFiles: TFPHashList;
IndentLevel: integer;
CodeSection: TCodeTreeNodeDesc;
private
procedure PrintNodeDebug(Node: TCodeTreeNode; Deep: boolean = false);
function AddSymbol(Node: TCodeTreeNode; Kind: TSymbolKind): TSymbol; overload;
function AddSymbol(Node: TCodeTreeNode; Kind: TSymbolKind; Name: String; Container: String = ''): TSymbol; overload;
procedure ExtractCodeSection(Node: TCodeTreeNode);
function ExtractProcedure(ParentNode, Node: TCodeTreeNode):TSymbol;
procedure ExtractTypeDefinition(TypeDefNode, Node: TCodeTreeNode);
procedure ExtractObjCClassMethods(ClassNode, Node: TCodeTreeNode);
public
constructor Create(_Entry: TSymbolTableEntry; _Code: TCodeBuffer; _Tool: TCodeTool);
destructor Destroy; override;
end;
{$IFDEF SQLDB}
{ TSQLiteDatabase }
TSQLiteDatabase = class
protected
Database: psqlite3;
function SingleQuery(Stat: String): boolean;
function Exec(Stat: String): boolean;
procedure LogError(errmsg: pansichar); virtual;
end;
{ TSymbolDatabase }
TSymbolDatabase = class(TSQLiteDatabase)
private
procedure LogError(errmsg: pansichar); override;
public
constructor Create(Path: String);
{ Symbols }
function FindAllSymbols(Path: String): TJSONSerializedArray;
function FindSymbols(Query: String): TJSONSerializedArray;
procedure ClearSymbols(Path: String);
procedure InsertSymbol(Symbol: TSymbol);
procedure InsertSymbols(Collection: TSymbolItems; StartIndex, EndIndex: Integer);
{ Files }
procedure TouchFile(Path: String);
function FileModified(Path: String): boolean;
procedure InsertFile(Path: String);
end;
{$ENDIF}
{ TSymbolManager }
TSymbolManager = class
private
SymbolTable: TFPHashObjectList;
ErrorList: TStringList;
{$IFDEF SQLDB}
fDatabase: TSymbolDatabase;
{$ENDIF}
function Load(Path: String): TCodeBuffer;
procedure RemoveFile(FileName: String);
procedure AddError(Message: String);
function GetEntry(Code: TCodeBuffer): TSymbolTableEntry;
{$IFDEF SQLDB}
function GetDatabase: TSymbolDatabase; inline;
property Database: TSymbolDatabase read GetDatabase;
{$ENDIF}
public
{ Constructors }
constructor Create;
destructor Destroy; override;
{ Searching }
function FindDocumentSymbols(Path: String): TJSONSerializedArray;
function FindWorkspaceSymbols(Query: String): TJSONSerializedArray;
function CollectSerializedSymbols: TJSONSerializedArray;
{ Errors }
procedure ClearErrors;
{ Loading }
procedure Reload(Code: TCodeBuffer; Always: Boolean = false); overload;
procedure Reload(Path: String; Always: Boolean = false); overload;
procedure Scan(Path: String; SearchSubDirs: Boolean);
procedure FileModified(Code: TCodeBuffer);
end;
var
SymbolManager: TSymbolManager = nil;
function SymbolKindToString(kind: TSymbolKind): ShortString;
function SymbolKindFromString(kind: ShortString): TSymbolKind;
implementation
uses
SysUtils, FileUtil, DateUtils, fpjsonrtti,
CodeToolsConfig, IdentCompletionTool, CodeAtom,
BasicCodeTools, FindDeclarationTool, PascalParserTool, KeywordFuncLists,
settings, diagnostics;
function SymbolKindToString(kind: TSymbolKind): ShortString;
begin
case kind of
SymbolKindFile: result := 'File';
SymbolKindModule: result := 'Module';
SymbolKindNamespace: result := 'Namespace';
SymbolKindPackage: result := 'Package';
SymbolKindClass: result := 'Class';
SymbolKindMethod: result := 'Method';
SymbolKindProperty: result := 'Property';
SymbolKindField: result := 'Field';
SymbolKindConstructor: result := 'Constructor';
SymbolKindEnum: result := 'Enum';
SymbolKindInterface: result := 'Interface';
SymbolKindFunction: result := 'Function';
SymbolKindVariable: result := 'Variable';
SymbolKindConstant: result := 'Constant';
SymbolKindString: result := 'String';
SymbolKindNumber: result := 'Number';
SymbolKindBoolean: result := 'Boolean';
SymbolKindArray: result := 'Array';
SymbolKindObject: result := 'Object';
SymbolKindKey: result := 'Key';
SymbolKindNull: result := 'Null';
SymbolKindEnumMember: result := 'EnumMember';
SymbolKindStruct: result := 'Struct';
SymbolKindEvent: result := 'Event';
SymbolKindOperator: result := 'Operator';
SymbolKindTypeParameter: result := 'TypeParameter'
end;
end;
function SymbolKindFromString(kind: ShortString): TSymbolKind;
begin
if (kind = 'File') then result := SymbolKindFile
else if (kind = 'Module') then result := SymbolKindModule
else if (kind = 'Namespace') then result := SymbolKindNamespace
else if (kind = 'Package') then result := SymbolKindPackage
else if (kind = 'Class') then result := SymbolKindClass
else if (kind = 'Method') then result := SymbolKindMethod
else if (kind = 'Property') then result := SymbolKindProperty
else if (kind = 'Field') then result := SymbolKindField
else if (kind = 'Constructor') then result := SymbolKindConstructor
else if (kind = 'Enum') then result := SymbolKindEnum
else if (kind = 'Interface') then result := SymbolKindInterface
else if (kind = 'Function') then result := SymbolKindFunction
else if (kind = 'Variable') then result := SymbolKindVariable
else if (kind = 'Constant') then result := SymbolKindConstant
else if (kind = 'String') then result := SymbolKindString
else if (kind = 'Number') then result := SymbolKindNumber
else if (kind = 'Boolean') then result := SymbolKindBoolean
else if (kind = 'Array') then result := SymbolKindArray
else if (kind = 'Object') then result := SymbolKindObject
else if (kind = 'Key') then result := SymbolKindKey
else if (kind = 'Null') then result := SymbolKindNull
else if (kind = 'EnumMember') then result := SymbolKindEnumMember
else if (kind = 'Struct') then result := SymbolKindStruct
else if (kind = 'Event') then result := SymbolKindEvent
else if (kind = 'Operator') then result := SymbolKindOperator
else if (kind = 'TypeParameter') then result := SymbolKindTypeParameter
end;
function GetFileKey(Path: String): ShortString;
begin
result := ExtractFileName(Path);
end;
function IndentLevelString(level: integer): ShortString;
var
i: integer;
begin
result := '';
for i := 0 to level - 1 do
result += ' ';
end;
{ TSymbol }
function TSymbol.Path: String;
begin
UriToFilename(location.uri,Result);
end;
function TSymbol.IsGlobal: boolean;
begin
result := containerName <> '';
end;
function TSymbol.GetFullName: String;
begin
if containerName <> '' then
Result := containerName+'.'+Name
else
Result := Name;
end;
constructor TSymbol.Create;
begin
// we need this dummy constructor for serializing
Create(nil);
end;
{ TSymbolTableEntry }
function TSymbolTableEntry.GetRawJSON: String;
var
JSON: TJSONSerializedArray;
begin
{$IFDEF SQLDB}
if (fRawJSON = '') and (SymbolManager.Database <> nil) then
begin
JSON := SymbolManager.Database.FindAllSymbols(Code.FileName);
fRawJSON := JSON.AsJson;
JSON.Free;
end;
{$ENDIF}
Result := fRawJSON;
end;
function TSymbolTableEntry.Count: integer;
begin
result := Symbols.Count;
end;
function TSymbolTableEntry.RequestReload: boolean;
var
{$IFDEF SQLDB}Database: TSymbolDatabase;{$ENDIF}
Path: String;
JSON: TJSONSerializedArray;
begin
if Modified then
exit(true);
{$IFDEF SQLDB}
Database := SymbolManager.Database;
Path := Code.FileName;
Result := false;
if Database <> nil then
begin
Database.InsertFile(Path);
if Database.FileModified(Path) then
begin
Database.TouchFile(Path);
Result := true;
end;
end
else
{$ENDIF}
Result := true;
end;
function TSymbolTableEntry.AddSymbol(Name: String; Kind: TSymbolKind; FileName: String; Line, Column, endline,endCol: Integer): TSymbol;
var
Symbol: TSymbol;
begin
Symbol := TSymbol(Symbols.Add);
Symbol.name := Name;
Symbol.kind := Kind;
Symbol.location := TLocation.Create(FileName, Line - 1, Column - 1, EndLine-1,EndCol-1);
result := Symbol;
end;
procedure TSymbolTableEntry.SerializeSymbols;
const
BATCH_COUNT = 1000;
var
SerializedItems: TJSONArray;
i, Start, Next, Total: Integer;
Symbol: TSymbol;
begin
SerializedItems := specialize TLSPStreaming<TSymbolItems>.ToJSON(Symbols) as TJSONArray;
//writeln(stderr, 'serialize ', key, ': ', SerializedItems.count);flush(stderr);
for i := 0 to SerializedItems.Count - 1 do
begin
Symbol := TSymbol(Symbols.Items[i]);
Symbol.RawJSON := SerializedItems[i].AsJson;
end;
// if a database is available then insert serialized symbols in batches
{$IFDEF SQLDB}
if SymbolManager.Database <> nil then
begin
Next := 0;
Start := 0;
Total := SerializedItems.Count;
while Start < Total do
begin
Next := Start + BATCH_COUNT;
if Next >= Total then
Next := Total - 1;
SymbolManager.Database.InsertSymbols(Symbols, Start, Next);
Start := Next + 1;
end;
end;
{$ENDIF}
fRawJSON := SerializedItems.AsJSON;
SerializedItems.Free;
Symbols.Clear;
end;
procedure TSymbolTableEntry.SerialzeToDocSymbols;
const
BATCH_COUNT = 1000;
var
SerializedItems: TJSONArray;
i, Start, Next, Total,idx: Integer;
Symbol: TSymbol;
DocSymbols:TDocumentSymbolItems;
DocSymbol:TDocumentSymbol;
dict:TStringList;
begin
dict:=TStringList.Create;
dict.Sorted:=true;
DocSymbols:=TDocumentSymbolItems.Create;
try
for i:=0 to Symbols.Count-1 do
begin
Symbol:=TSymbol(Symbols.Items[i]);
if Symbol.containerName <> '' then
begin
if dict.Find(symbol.containerName,idx) then
begin
DocSymbol:=TDocumentSymbol(dict.Objects[idx]);
if DocSymbol.range.&end.line<symbol.location.range.&end.line then
DocSymbol.range.&end:=symbol.location.range.&end;
if DocSymbol.range.start.line>symbol.location.range.start.line then
DocSymbol.range.start:=symbol.location.range.start;
if not Assigned(DocSymbol.children) then
begin
DocSymbol.children:=TDocumentSymbolItems.Create;
DocSymbol.range:=symbol.location.range;
end;
DocSymbol.selectionRange:=DocSymbol.range;
DocSymbol:=TDocumentSymbol(DocSymbol.children.Add);
end
else
begin
DocSymbol:=TDocumentSymbol(DocSymbols.Add);
end;
end
else
begin
DocSymbol:=TDocumentSymbol(DocSymbols.Add);
dict.AddObject(symbol.name,DocSymbol);
end;
DocSymbol.name:=Symbol.name;//.Substring(length(symbol.containerName)+1);
DocSymbol.kind:=Symbol.kind;
DocSymbol.range:=Symbol.location.range;
DocSymbol.selectionRange:=DocSymbol.range;
end;
SerializedItems := specialize TLSPStreaming<TDocumentSymbolItems>.ToJSON(DocSymbols) as TJSONArray;
fRawJSON := SerializedItems.AsJSON;
SerializedItems.Free;
Symbols.Clear;
finally
DocSymbols.Free;
dict.Free;
end;
end;
procedure TSymbolTableEntry.Clear;
begin
Modified := false;
Symbols.Clear;
{$IFDEF SQLDB}
if SymbolManager.Database <> nil then
SymbolManager.Database.ClearSymbols(Code.FileName);
{$ENDIF}
end;
destructor TSymbolTableEntry.Destroy;
begin
FreeAndNil(Symbols);
inherited;
end;
constructor TSymbolTableEntry.Create(_Code: TCodeBuffer);
begin
Code := _Code;
Key := ExtractFileName(Code.FileName);
Symbols := TSymbolItems.Create;
end;
{ TSymbolExtractor }
procedure TSymbolExtractor.PrintNodeDebug(Node: TCodeTreeNode; Deep: boolean);
var
Child: TCodeTreeNode;
begin
{$ifdef SYMBOL_DEBUG}
debugln([IndentLevelString(IndentLevel), Node.DescAsString, ' (', GetIdentifierAtPos(Tool, Node.StartPos, true, true), ') -> ', Node.ChildCount]);
if Deep then
begin
Child := Node.FirstChild;
Inc(IndentLevel);
while Child <> nil do
begin
if Child.ChildCount > 0 then
PrintNodeDebug(Child.FirstChild, true)
else
PrintNodeDebug(Child);
Child := Child.NextBrother;
end;
Dec(IndentLevel);
end;
{$endif}
end;
function TSymbolExtractor.AddSymbol(Node: TCodeTreeNode; Kind: TSymbolKind): TSymbol;
begin
AddSymbol(Node, Kind, GetIdentifierAtPos(Tool, Node.StartPos, true, true));
end;
function TSymbolExtractor.AddSymbol(Node: TCodeTreeNode; Kind: TSymbolKind; Name: String; Container: String): TSymbol;
var
CodePos,endPos: TCodeXYPosition;
FileName: String;
begin
{$ifdef SYMBOL_DEBUG}
DebugLn([IndentLevelString(IndentLevel + 1), '* ',SymbolKindToString(Kind),' ', Name]);
{$endif}
Tool.CleanPosToCaret(Node.StartPos, CodePos);
Tool.CleanPosToCaret(Node.EndPos, endPos);
// clear existing symbols in symbol database
// we don't know which include files are associated
// with each unit so we need to check each time
// a symbol is added
{$IFDEF SQLDB}
if SymbolManager.Database <> nil then
begin
FileName := ExtractFileName(CodePos.Code.FileName);
if RelatedFiles.Find(FileName) = nil then
begin
SymbolManager.Database.ClearSymbols(CodePos.Code.FileName);
RelatedFiles.Add(FileName, @CodePos);
end;
end;
{$ENDIF}
Result := Entry.AddSymbol(Name, Kind, CodePos.Code.FileName, CodePos.Y, CodePos.X, endpos.Y,endPos.X);
end;
procedure TSymbolExtractor.ExtractObjCClassMethods(ClassNode, Node: TCodeTreeNode);
var
Child: TCodeTreeNode;
ExternalClass: boolean = false;
TypeName: String;
begin
while Node <> nil do
begin
PrintNodeDebug(Node);
case Node.Desc of
ctnClassExternal:
begin
ExternalClass := true;
Tool.MoveCursorToCleanPos(Node.EndPos);
Tool.ReadNextAtom;
// objective-c forward class definition, i.e:
// ACAccount = objcclass external;
if Tool.CurPos.Flag = cafSemicolon then
begin
// todo: we need to assign this to the symbol so we don't show it in indexes
//Include(ClassSymbol.Flags, TSymbolFlag.ForwardClassDefinition);
break;
end;
end;
ctnProcedure:
begin
AddSymbol(Node, SymbolKindMethod, Tool.ExtractProcName(Node, []));
end;
ctnClassPublic,ctnClassPublished,ctnClassPrivate,ctnClassProtected,
ctnClassRequired,ctnClassOptional:
if ExternalClass then
begin
// if the class is external then search methods
//if ExternalClass then
// ExtractObjCClassMethods(ClassNode, Node.FirstChild);
TypeName := GetIdentifierAtPos(Tool, ClassNode.StartPos, true, true);
Child := Node.FirstChild;
while Child <> nil do
begin
PrintNodeDebug(Child);
AddSymbol(Node, SymbolKindMethod, TypeName+'.'+Tool.ExtractProcName(Child, []));
Child := Child.NextBrother;
end;
end;
end;
Node := Node.NextBrother;
end;
end;
procedure TSymbolExtractor.ExtractTypeDefinition(TypeDefNode, Node: TCodeTreeNode);
var
Child: TCodeTreeNode;
begin
while Node <> nil do
begin
PrintNodeDebug(Node);
case Node.Desc of
ctnClass,ctnClassHelper,ctnRecordHelper,ctnTypeHelper:
begin
AddSymbol(TypeDefNode, SymbolKindClass);
end;
ctnObject,ctnRecordType:
begin
AddSymbol(TypeDefNode, SymbolKindStruct);
end;
ctnObjCClass,ctnObjCCategory,ctnObjCProtocol:
begin
// todo: ignore forward defs!
AddSymbol(TypeDefNode, SymbolKindClass);
Inc(IndentLevel);
ExtractObjCClassMethods(TypeDefNode, Node.FirstChild);
Dec(IndentLevel);
end;
ctnSpecialize:
begin
// todo: is this a class/record???
PrintNodeDebug(Node.FirstChild, true);
AddSymbol(TypeDefNode, SymbolKindClass);
end;
ctnEnumerationType:
begin
AddSymbol(TypeDefNode, SymbolKindEnum);
Child := Node.FirstChild;
while Child <> nil do
begin
PrintNodeDebug(Child);
// todo: make an option to show enum members in doc symbols
//AddSymbol(Child, SymbolKindEnumMember, TypeName+'.'+GetIdentifierAtPos(Child.StartPos, true, true));
Child := Child.NextBrother;
end;
end;
otherwise
begin
AddSymbol(TypeDefNode, SymbolKindTypeParameter);
end;
end;
Node := Node.NextBrother;
end;
end;
function TSymbolExtractor.ExtractProcedure(ParentNode, Node: TCodeTreeNode):TSymbol;
var
Child: TCodeTreeNode;
Name, containerName,key: ShortString;
Symbol: TSymbol;
begin
result:=Nil;;
PrintNodeDebug(Node);
//if ParentNode <> nil then
// Name := Tool.ExtractProcName(ParentNode, [])+'.'+Tool.ExtractProcName(Node, [])
containerName:=Tool.ExtractClassNameOfProcNode(Node);
//if ParentNode <> nil then
// containerName:=Tool.ExtractClassName(ParentNode,False,true,false);
Name := Tool.ExtractProcName(Node, [phpWithoutClassName]);
key:=IntToStr(CodeSection)+'.'+containerName+'.'+Name;
Symbol := TSymbol(OverloadMap.Find(key));
if Symbol <> nil then
begin
// TODO: when newest LSP version is released on package control
// we can include the container name to be implementation
// and at least make this an option
// if the overloaded name is found in the implementation section
// then just ignore it so we have only function in the list
if CodeSection = ctnImplementation then
exit;
Inc(Symbol.overloadCount);
case ServerSettings.overloadPolicy of
TOverloadPolicy.Duplicates:
;
TOverloadPolicy.Suffix:
Name := Name+'$'+IntToStr(Symbol.OverloadCount);
TOverloadPolicy.Ignore:
exit;
end;
end;
Symbol := AddSymbol(Node, SymbolKindFunction, Name);
Symbol.containerName:=containerName;
OverloadMap.Add(key, Symbol);
// recurse into procedures to find nested procedures
if not Tool.ProcNodeHasSpecifier(Node, psForward) and
not Tool.ProcNodeHasSpecifier(Node, psExternal) then
begin
Child := Node.FirstChild;
while Child <> nil do
begin
if Child.Desc = ctnProcedure then
begin
Inc(IndentLevel);
ExtractProcedure(Node, Child);
Dec(IndentLevel);
end;
Child := Child.NextBrother;
end;
end;
result:=Symbol;
end;
procedure TSymbolExtractor.ExtractCodeSection(Node: TCodeTreeNode);
var
Symbol,lastClassSymbol: TSymbol;
Child: TCodeTreeNode;
Scanner: TLinkScanner;
LinkIndex: Integer;
isImplementation:Boolean;
begin
isImplementation:=(node.Parent<>nil) and (node.Parent.Desc=ctnImplementation);
lastClassSymbol:=nil;
while Node <> nil do
begin
PrintNodeDebug(Node);
// ignore nodes from include files
// for main code files ignore include nodes
// for include files ignore main code nodes
Scanner := Tool.Scanner;
LinkIndex := Scanner.LinkIndexAtCleanPos(Node.StartPos);
if (LinkIndex >= 0) and (Scanner.LinkP[LinkIndex]^.Code <> nil) and
not (Node.Desc in AllCodeSections) and
(Code.FileName <> TCodeBuffer(Scanner.LinkP[LinkIndex]^.Code).FileName) then
begin
Node := Node.NextBrother;
continue;
end;
// recurse into code sections
if (Node.Desc in AllCodeSections) and (Node.ChildCount > 0) then
begin
case Node.Desc of
ctnInterface:
AddSymbol(Node, SymbolKindNamespace, kSymbolName_Interface);
//ctnImplementation:
// AddSymbol(Node, SymbolKindNamespace, kSymbolName_Implementation);
end;
CodeSection := Node.Desc;
Inc(IndentLevel);
ExtractCodeSection(Node.FirstChild);
Dec(IndentLevel);
Node := Node.NextBrother;
continue;
end;
case Node.Desc of
// todo: make constants an option?
//ctnConstSection:
// begin
// Inc(IndentLevel);
// Child := Node.FirstChild;
// while Child <> nil do
// begin
// AddSymbol(Child, SymbolKindConstant);
// PrintNodeDebug(Child);
// Child := Child.NextBrother;
// end;
// Dec(IndentLevel);
// end;
ctnTypeSection:
begin
Inc(IndentLevel);
Child := Node.FirstChild;
while Child <> nil do
begin
if Child.Desc = ctnTypeDefinition then
begin
PrintNodeDebug(Child);
Inc(IndentLevel);
ExtractTypeDefinition(Child, Child.FirstChild);
Dec(IndentLevel);
end;
Child := Child.NextBrother;
end;
Dec(IndentLevel);
end;
ctnProcedure:
begin
Symbol:= ExtractProcedure(nil, Node);
if (symbol<>nil) and (symbol.containerName<>'') then
begin
if (lastClassSymbol=nil) or (symbol.containerName<>lastClassSymbol.name) then
begin
lastClassSymbol:=AddSymbol(node,SymbolKindClass,symbol.containerName);
end
else
begin
lastClassSymbol.location.range.&end:=Symbol.location.range.&end;
end;
end;
end;
end;
Node := Node.NextBrother;
end;
end;
constructor TSymbolExtractor.Create(_Entry: TSymbolTableEntry; _Code: TCodeBuffer; _Tool: TCodeTool);
begin
Entry := _Entry;
Code := _Code;
Tool := _Tool;
OverloadMap := TFPHashList.Create;
RelatedFiles := TFPHashList.Create;
end;
destructor TSymbolExtractor.Destroy;
begin
OverloadMap.Free;
RelatedFiles.Free;
inherited;
end;
{$IFDEF SQLDB}
{ TSQLiteDatabase }
procedure TSQLiteDatabase.LogError(errmsg: pansichar);
begin
end;
function TSQLiteDatabase.SingleQuery(Stat: String): boolean;
var
statement: psqlite3_stmt;
errmsg: pansichar;
begin
Result := false;
if sqlite3_prepare_v2(database, @Stat[1], -1, @statement, @errmsg) = SQLITE_OK then
begin
Result := sqlite3_step(statement) = SQLITE_ROW;
sqlite3_finalize(statement);
end
else
LogError(errmsg);
end;
function TSQLiteDatabase.Exec(Stat: String): boolean;
var
errmsg: pansichar;
begin
result := sqlite3_exec(database, @Stat[1], nil, nil, @errmsg) = SQLITE_OK;
if not result then
LogError(errmsg);
end;
{ TSymbolDatabase }
procedure AddField(var Source: String; Value: String; Terminate: Boolean = true);
begin
Source += ''''+Value+'''';
if Terminate then