forked from lmbelo/pyscripter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcPythonSourceScanner.pas
More file actions
1793 lines (1643 loc) · 57.2 KB
/
cPythonSourceScanner.pas
File metadata and controls
1793 lines (1643 loc) · 57.2 KB
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
{-----------------------------------------------------------------------------
Unit Name: cPythonSourceScanner
Author: Kiriakos Vlahos
Date: 14-Jun-2005
Purpose: Class for Scanning and analysing Python code
Does not check correctness
Code draws from Bicycle Repair Man and Boa Constructor
History:
-----------------------------------------------------------------------------}
unit cPythonSourceScanner;
interface
uses SysUtils,
Classes,
Contnrs,
SynRegExpr,
AsyncCalls;
Type
TParsedModule = class;
TCodePos = record
LineNo : integer;
CharOffset : integer;
end;
TBaseCodeElement = class
// abstract base class
private
fParent : TBaseCodeElement;
protected
fIsProxy : boolean;
fCodePos : TCodePos;
function GetCodeHint : string; virtual; abstract;
public
Name : string;
function GetRoot : TBaseCodeElement;
function GetModule : TParsedModule;
function GetDottedName : string;
function GetModuleSource : string;
property CodePos : TCodePos read fCodePos;
property Parent : TBaseCodeElement read fParent write fParent;
property IsProxy : boolean read fIsProxy; // true if derived from live Python object
property CodeHint : string read GetCodeHint;
end;
TCodeBlock = record
StartLine : integer;
EndLine : integer;
end;
TModuleImport = class(TBaseCodeElement)
private
fRealName : string; // used if name is an alias
fPrefixDotCount : integer; // for relative package imports
fCodeBlock : TCodeBlock;
function GetRealName: string;
protected
function GetCodeHint : string; override;
public
ImportAll : Boolean;
ImportedNames : TObjectList;
property RealName : string read GetRealName;
property PrefixDotCount : integer read fPrefixDotCount;
property CodeBlock : TCodeBlock read fCodeBlock;
constructor Create(AName : string; CB : TCodeBlock);
destructor Destroy; override;
end;
TVariableAttribute = (vaBuiltIn, vaClassAttribute, vaCall, vaArgument,
vaStarArgument, vaStarStarArgument, vaArgumentWithDefault,
vaImported);
TVariableAttributes = set of TVariableAttribute;
TVariable = class(TBaseCodeElement)
// The parent can be TParsedModule, TParsedClass, TParsedFunction or TModuleImport
private
// only used if Parent is TModuleImport and Name is an alias
fRealName : string;
function GetRealName: string;
protected
function GetCodeHint : string; override;
public
ObjType : string;
DefaultValue : string;
Attributes : TVariableAttributes;
property RealName : string read GetRealName;
end;
TCodeElement = class(TBaseCodeElement)
private
fCodeBlock : TCodeBlock;
fDocString : string;
fIndent : integer;
fDocStringExtracted : boolean;
function GetChildCount: integer;
function GetChildren(i : integer): TCodeElement;
procedure ExtractDocString;
protected
fChildren : TObjectList;
function GetDocString: string; virtual;
public
constructor Create;
destructor Destroy; override;
procedure AddChild(CE : TCodeElement);
procedure GetSortedClasses(SortedClasses : TObjectList);
procedure GetSortedFunctions(SortedFunctions : TObjectList);
procedure GetNameSpace(SList : TStringList); virtual;
function GetScopeForLine(LineNo : integer) : TCodeElement;
function GetChildByName(ChildName : string): TCodeElement;
property CodeBlock : TCodeBlock read fCodeBlock;
property Indent : integer read fIndent;
property ChildCount : integer read GetChildCount;
property Children[i : integer] : TCodeElement read GetChildren;
property DocString : string read GetDocString;
end;
TParsedModule = class(TCodeElement)
private
fImportedModules : TObjectList;
fSource : string;
fFileName : string;
fMaskedSource : string;
fAllExportsVar : string;
fFileAge : TDateTime;
function GetIsPackage: boolean;
procedure SetFileName(const Value: string);
protected
fGlobals : TObjectList;
function GetAllExportsVar: string; virtual;
function GetCodeHint : string; override;
procedure GetNameSpaceInternal(SList, ImportedModuleCache : TStringList);
public
constructor Create; overload;
constructor Create(const Source : string); overload;
constructor Create(const FName : string; const Source : string); overload;
destructor Destroy; override;
procedure Clear;
procedure GetNameSpace(SList : TStringList); override;
procedure GetSortedImports(ImportsList : TObjectList);
procedure GetUniqueSortedGlobals(GlobalsList : TObjectList);
property ImportedModules : TObjectList read fImportedModules;
property Globals : TObjectList read fGlobals;
property Source : string read fSource write fSource;
property FileName : string read fFileName write SetFileName;
property MaskedSource : string read fMaskedSource;
property IsPackage : boolean read GetIsPackage;
property AllExportsVar : string read GetAllExportsVar;
property FileAge : TDateTime read fFileAge write fFileAge;
end;
TParsedFunction = class(TCodeElement)
private
fArguments : TObjectList;
fLocals : TObjectList;
protected
function GetCodeHint : string; override;
public
ReturnType : string;
ReturnAttributes : TVariableAttributes;
constructor Create;
destructor Destroy; override;
function ArgumentsString : string; virtual;
procedure GetNameSpace(SList : TStringList); override;
property Arguments : TObjectList read fArguments;
property Locals : TObjectList read fLocals;
end;
TParsedClass = class(TCodeElement)
private
fSuperClasses : TStringList;
fAttributes : TObjectList;
procedure GetNameSpaceImpl(SList: TStringList; BaseClassResolver : TStringList);
function GetConstructorImpl(BaseClassResolver : TStringList) : TParsedFunction;
protected
function GetCodeHint : string; override;
public
constructor Create;
destructor Destroy; override;
procedure GetNameSpace(SList : TStringList); override;
procedure GetUniqueSortedAttibutes(AttributesList: TObjectList);
function GetConstructor : TParsedFunction; virtual;
property SuperClasses : TStringList read fSuperClasses;
property Attributes : TObjectList read fAttributes;
end;
TScannerProgressEvent = procedure(CharNo, NoOfChars : integer; var Stop : Boolean) of object;
TPythonScanner = class
private
fOnScannerProgress : TScannerProgressEvent;
fCodeRE : TRegExpr;
fBlankLineRE : TRegExpr;
//fEscapedQuotesRE : TRegExpr;
fStringsAndCommentsRE : TRegExpr;
fLineContinueRE : TRegExpr;
fImportRE : TRegExpr;
fFromImportRE : TRegExpr;
fAssignmentRE : TRegExpr;
fForRE : TRegExpr;
fReturnRE : TRegExpr;
fWithRE : TRegExpr;
fGlobalRE : TRegExpr;
fAliasRE : TRegExpr;
fListRE : TRegExpr;
protected
procedure DoScannerProgress(CharNo, NoOfChars : integer; var Stop : Boolean);
public
property OnScannerProgress : TScannerProgressEvent
read fOnScannerProgress write fOnScannerProgress;
constructor Create;
destructor Destroy; override;
function ScanModule(Module : TParsedModule) : boolean;
end;
IAsyncSourceScanner = interface
function GetParsedModule : TParsedModule;
function Finished : Boolean;
procedure StopScanning;
property ParsedModule : TParsedModule read GetParsedModule;
end;
TAsynchSourceScanner = class(TInterfacedObject, IAsyncSourceScanner)
private
fStopped : Boolean;
fPythonScanner : TPythonScanner;
fParsedModule : TParsedModule;
fAsyncCall : IAsyncCall;
procedure ThreadProc(Arg : Integer);
procedure ScanProgress(CharNo, NoOfChars : integer; var Stop : Boolean);
// IAsyncSourceScanner implementation
function Finished : Boolean;
function GetParsedModule : TParsedModule;
procedure StopScanning;
public
constructor Create(const FileName : string; const Source : String);
destructor Destroy; override;
end;
TAsynchSourceScannerFactory = class
private
fIList : TInterfaceList;
procedure ClearFinished;
public
constructor Create;
destructor Destroy; override;
procedure ReleaseScanner(Scanner : IAsyncSourceScanner);
function CreateAsynchSourceScanner(const FileName : string; const Source : String): IAsyncSourceScanner;
end;
Var
AsynchSourceScannerFactory : TAsynchSourceScannerFactory;
function CodeBlock(StartLine, EndLine : integer) : TCodeBlock;
function GetExpressionBuiltInType(Expr : string; Var IsBuiltIn : boolean) : string;
implementation
uses Windows, uCommonFunctions, VarPyth,
StringResources, JclSysUtils, Math,
cRefactoring, cPyBaseDebugger, cPyDebugger,
gnugettext, JclStrings;
Const
MaskChar = WideChar(#96);
NoOfImplicitContinuationBraces = 3;
ImplicitContinuationBraces : array[0..NoOfImplicitContinuationBraces-1] of
array [0..1] of WideChar = (('(', ')'), ('[', ']'), ('{', '}'));
Type
ImplicitContinuationBracesCount = array [0..NoOfImplicitContinuationBraces-1] of integer;
Var
DocStringRE : TRegExpr;
procedure HangingBraces(S : string; OpenBrace, CloseBrace : WideChar; var Count : integer);
var
I: Integer;
begin
for I := 1 to Length(S) do
if S[I] = OpenBrace then
Inc(Count)
else if S[I] = CloseBrace then
Dec(Count);
end;
function HaveImplicitContinuation(S : string;
var CountArray : ImplicitContinuationBracesCount; InitCount : boolean = false) : boolean;
Var
i : integer;
begin
if InitCount then
for i := 0 to NoOfImplicitContinuationBraces - 1 do
CountArray[i] := 0;
for i := 0 to NoOfImplicitContinuationBraces - 1 do
HangingBraces(S, ImplicitContinuationBraces[i][0],
ImplicitContinuationBraces[i][1], CountArray[i]);
Result := False;
for i := 0 to NoOfImplicitContinuationBraces - 1 do
// Code would be incorrect if Count < 0 but we ignore it
if CountArray[i] > 0 then begin
Result := True;
break;
end;
end;
{ Code Ellement }
constructor TCodeElement.Create;
begin
inherited;
fParent := nil;
fChildren := nil;
end;
destructor TCodeElement.Destroy;
begin
FreeAndNil(fChildren);
inherited;
end;
procedure TCodeElement.AddChild(CE : TCodeElement);
begin
if fChildren = nil then
fChildren := TObjectList.Create(True);
CE.fParent := Self;
fChildren.Add(CE);
end;
function TCodeElement.GetChildCount: integer;
begin
if Assigned(fChildren) then
Result := fChildren.Count
else
Result := 0;
end;
function TCodeElement.GetChildren(i : integer): TCodeElement;
begin
if Assigned(fChildren) then begin
Result := TCodeElement(fChildren[i]);
Assert(Result is TCodeElement);
Assert(Assigned(Result));
end else
Result := nil;
end;
function TCodeElement.GetChildByName(ChildName: string): TCodeElement;
var
i : integer;
CE : TCodeElement;
begin
Result := nil;
if not Assigned(fChildren) then Exit;
for i := 0 to fChildren.Count - 1 do begin
CE := GetChildren(i);
if CE.Name = ChildName then begin
Result := CE;
Exit;
end;
end;
end;
function CompareCodeElements(Item1, Item2: Pointer): Integer;
begin
Result := CompareStr(TCodeElement(Item1).Name, TCodeElement(Item2).Name);
end;
procedure TCodeElement.GetSortedClasses(SortedClasses: TObjectList);
Var
i : integer;
begin
if not Assigned(fChildren) then Exit;
for i := 0 to Self.fChildren.Count - 1 do
if fChildren[i] is TParsedClass then
SortedClasses.Add(fChildren[i]);
SortedClasses.Sort(CompareCodeElements);
end;
procedure TCodeElement.GetSortedFunctions(SortedFunctions: TObjectList);
Var
i : integer;
begin
if not Assigned(fChildren) then Exit;
for i := 0 to Self.fChildren.Count - 1 do
if fChildren[i] is TParsedFunction then
SortedFunctions.Add(fChildren[i]);
SortedFunctions.Sort(CompareCodeElements);
end;
procedure TCodeElement.GetNameSpace(SList: TStringList);
Var
i : integer;
begin
// Add from Children
if Assigned(fChildren) then
for i := 0 to fChildren.Count - 1 do
SList.AddObject(TCodeElement(fChildren[i]).Name, fChildren[i]);
end;
function TCodeElement.GetScopeForLine(LineNo: integer): TCodeElement;
Var
i : integer;
CE : TCodeElement;
begin
if (LineNo >= fCodeBlock.StartLine) and (LineNo <= fCodeBlock.EndLine) then begin
Result := Self;
// try to see whether the line belongs to a child
if not Assigned(fChildren) then Exit;
for i := 0 to fChildren.Count - 1 do begin
CE := Children[i];
if LineNo < CE.CodeBlock.StartLine then
break
else if LineNo > CE.CodeBlock.EndLine then
continue
else begin
// recursive call
Result := CE.GetScopeForLine(LineNo);
break;
end;
end;
end else
Result := nil;
end;
procedure TCodeElement.ExtractDocString;
var
ModuleSource, DocStringSource : string;
CB : TCodeBlock;
begin
if fDocStringExtracted then Exit;
fDocStringExtracted := True;
fDocString := '';
CB := fCodeBlock;
if Assigned(fChildren) and (fChildren.Count > 0) then
CB.EndLine := Pred(Children[0].CodeBlock.StartLine);
if CB.StartLine > CB.EndLine then Exit;
ModuleSource := GetModuleSource;
if ModuleSource = '' then Exit;
DocStringSource := GetLineRange(ModuleSource, CB.StartLine, CB.EndLine);
if DocStringSource = '' then Exit;
if DocStringRE.Exec(DocStringSource) then begin
if DocStringRE.MatchPos[2] >= 0 then
fDocString := DocStringRE.Match[2]
else
fDocString := DocStringRE.Match[3];
fDocString := FormatDocString(fDocString);
end;
end;
function TCodeElement.GetDocString: string;
begin
if not fDocStringExtracted then
ExtractDocString;
Result := fDocString;
end;
{ TPythonScanner }
constructor TPythonScanner.Create;
begin
inherited;
fCodeRE := CompiledRegExpr('^([ \t]*)(class|def)[ \t]+([^ \t\(\)\[\]\{\}:;\.,@]+)[ \t]*(\(.*\))?');
fBlankLineRE := CompiledRegExpr('^[ \t]*($|\$|\#|\"\"\"|''''''|' + MaskChar +')');
//fEscapedQuotesRE := CompiledRegExpr('(\\\\|\\\"|\\\'')');
fStringsAndCommentsRE :=
CompiledRegExpr('(?sm)(\"\"\".*?\"\"\"|''''''.*?''''''|\"[^\"]*\"|\''[^\'']*\''|#.*?\n)');
fLineContinueRE := CompiledRegExpr('\\[ \t]*(#.*)?$');
fImportRE := CompiledRegExpr('^[ \t]*import[ \t]+([^#;]+)');
fFromImportRE :=
CompiledRegExpr(Format('^[ \t]*from[ \t]+(\.*)(%s)?[ \t]+import[ \t]+([^#;]+)', [DottedIdentRE]));
fAssignmentRE :=
CompiledRegExpr(Format('^([ \t]*(self.)?%s[ \t]*(,[ \t]*(self.)?%s[ \t]*)*(=))+[ \t]*((%s)(\(?))?',
[IdentRE, IdentRE, DottedIdentRE]));
fForRE := CompiledRegExpr(Format('^\s*for +(%s)( *, *%s)* *(in)', [IdentRe, IdentRe]));
fReturnRE :=
CompiledRegExpr(Format('^([ \t]*return[ \t]*)((%s)(\(?))?',
[DottedIdentRE]));
fWithRE :=
CompiledRegExpr(Format('^[ \t]*with +(%s) *(\(?).*as +(%s)',
[DottedIdentRE, IdentRE]));
fGlobalRE :=
CompiledRegExpr(Format('^[ \t]*global +((%s)( *, *%s)*)',
[IdentRE, IdentRE]));
fAliasRE :=
CompiledRegExpr(Format('^[ \t]*(%s)([ \t]+as[ \t]+(%s))?',
[DottedIdentRE, IdentRE]));
fListRE :=
CompiledRegExpr('\[(.*)\]');
end;
destructor TPythonScanner.Destroy;
begin
fCodeRE.Free;
fBlankLineRE.Free;
//fEscapedQuotesRE.Free;
fStringsAndCommentsRE.Free;
fLineContinueRE.Free;
fImportRE.Free;
fFromImportRE.Free;
fAssignmentRE.Free;
fForRE.Free;
fReturnRE.Free;
fWithRE.Free;
fGlobalRE.Free;
fAliasRE.Free;
fListRE.Free;
inherited;
end;
procedure TPythonScanner.DoScannerProgress(CharNo, NoOfChars : integer;
var Stop: Boolean);
begin
if Assigned(fOnScannerProgress) then
fOnScannerProgress(CharNo, NoOfChars, Stop);
end;
function TPythonScanner.ScanModule(Module : TParsedModule): boolean;
// Expectes Module Source code in Module.Source
// Parses the Python Source code and adds code elements as children of Module
{ TODO 2 : Optimize out calls to Trim }
Var
UseModifiedSource : boolean;
SourceLines : TStringList;
SourceLinesSafeGuard: ISafeGuard;
function GetNthSourceLine(LineNo : integer) : string;
begin
if not Assigned(SourceLines) then begin
SourceLines := TStringList(Guard(TStringList.Create, SourceLinesSafeGuard));
SourceLines.Text := Module.Source;
end;
if LineNo <= SourceLines.Count then
Result := SourceLines[LineNo-1]
else
Result := '';
end;
procedure GetLine(var P : PWideChar; var Line : string; var LineNo : integer);
Var
Start : PWideChar;
begin
Inc(LineNo);
Start := P;
while not CharInSet(P^, [#0, #10, #13]) do Inc(P);
if UseModifiedSource then
SetString(Line, Start, P - Start)
else
Line := GetNthSourceLine(LineNo);
if P^ = WideChar(#13) then Inc(P);
if P^ = WideChar(#10) then Inc(P);
end;
procedure CharOffsetToCodePos(CharOffset, FirstLine : integer; LineStarts : TList;
var CodePos: TCodePos);
var
i : integer;
begin
CodePos.LineNo := FirstLine;
CodePos.CharOffset := CharOffset;
for i := LineStarts.Count - 1 downto 0 do begin
if Integer(LineStarts[i]) <= CharOffset then begin
CodePos.CharOffset := CharOffset - Integer(LineStarts[i]) + 1;
CodePos.LineNo := FirstLine + i + 1;
break;
end;
end;
end;
procedure RemoveComment(var S : string);
var
Index : Integer;
begin
// Remove comment
Index := CharPos(S, WideChar('#'));
if Index > 0 then
S := Copy(S, 1, Index -1);
end;
function ProcessLineContinuation(var P : PWideChar; var Line : string;
var LineNo: integer; LineStarts : TList): boolean;
// Process continuation lines
var
ExplicitContinuation, ImplicitContinuation : boolean;
CountArray : ImplicitContinuationBracesCount;
NewLine : string;
TrimmedLine : string;
begin
LineStarts.Clear;
RemoveComment(Line);
ExplicitContinuation := fLineContinueRE.Exec(Line);
ImplicitContinuation := HaveImplicitContinuation(Line, CountArray, True);
Result := ExplicitContinuation or ImplicitContinuation;
while (ExplicitContinuation or ImplicitContinuation) and (P^ <> WideChar(#0)) do begin
if ExplicitContinuation then
// Drop the continuation char
Line := Copy(Line, 1, fLineContinueRE.MatchPos[0] - 1);
LineStarts.Add(Pointer(Length(Line)+2));
GetLine(P, NewLine, LineNo);
RemoveComment(NewLine);
TrimmedLine := Trim(NewLine);
if ExplicitContinuation and (TrimmedLine='') then break;
// issue 212
if StrIsLeft(PWideChar(TrimmedLine), 'class ') or StrIsLeft(PWideChar(TrimmedLine), 'def ') then break;
Line := Line + WideChar(' ') + NewLine;
ExplicitContinuation := fLineContinueRE.Exec(Line);
ImplicitContinuation := not ExplicitContinuation and
HaveImplicitContinuation(Line, CountArray, True);
end;
end;
function GetActiveClass(CodeElement : TBaseCodeElement) : TParsedClass;
begin
while Assigned(CodeElement) and (CodeElement.ClassType <> TParsedClass) do
CodeElement := CodeElement.Parent;
Result := TParsedClass(CodeElement);
end;
procedure ReplaceQuotedChars(var Source : string);
// replace quoted \ ' " with **
Var
pRes, pSource : PWideChar;
begin
if Length(Source) = 0 then Exit;
pRes := PWideChar(Source);
pSource := PWideChar(Source);
while pSource^ <> WideChar(#0) do begin
if (pSource^ = WideChar('\')) then begin
Inc(pSource);
if CharInSet(pSource^, ['\', '''', '"']) then begin
pRes^ := WideChar('*');
Inc(pRes);
pRes^ := WideChar('*');
end else
Inc(pRes);
end;
inc(pSource);
inc(pRes);
end;
end;
procedure MaskStringsAndComments(var Source : string);
// Replace all chars in strings and comments with *
Type
TParseState = (psNormal, psInTripleSingleQuote, psInTripleDoubleQuote,
psInSingleString, psInDoubleString, psInComment);
Var
pRes, pSource : PWideChar;
ParseState : TParseState;
begin
SourceLines := nil;
if Length(Source) = 0 then Exit;
pRes := PWideChar(Source);
pSource := PWideChar(Source);
ParseState := psNormal;
while pSource^ <> #0 do begin
case pSource^ of
WideChar('"') :
case ParseState of
psNormal :
if StrIsLeft(psource + 1, '""') then begin
ParseState := psInTripleDoubleQuote;
Inc(pRes,2);
Inc(pSource, 2);
end else
ParseState := psInDoubleString;
psInTripleSingleQuote,
psInSingleString,
psInComment :
pRes^ := MaskChar;
psInTripleDoubleQuote :
if StrIsLeft(psource + 1, '""') then begin
ParseState := psNormal;
Inc(pRes,2);
Inc(pSource, 2);
end else
pRes^ := MaskChar;
psInDoubleString :
ParseState := psNormal;
end;
WideChar(''''):
case ParseState of
psNormal :
if StrIsLeft(psource + 1, '''''') then begin
ParseState := psInTripleSingleQuote;
Inc(pRes, 2);
Inc(pSource, 2);
end else
ParseState := psInSingleString;
psInTripleDoubleQuote,
psInDoubleString,
psInComment :
pRes^ := MaskChar;
psInTripleSingleQuote :
if StrIsLeft(psource + 1, '''''') then begin
ParseState := psNormal;
Inc(pRes, 2);
Inc(pSource, 2);
end else
pRes^ := MaskChar;
psInSingleString :
ParseState := psNormal;
end;
WideChar('#') :
if ParseState = psNormal then
ParseState := psInComment
else
pRes^ := MaskChar;
WideChar(#10), WideChar(#13):
begin
if ParseState in [psInSingleString, psInDoubleString, psInComment] then
ParseState := psNormal;
end;
WideChar(' '),
WideChar(#9) : {do nothing};
else
if ParseState <> psNormal then
pRes^ := MaskChar;
end;
inc(pSource);
inc(pRes);
end;
end;
var
P : PWideChar;
LineNo, Indent, Index, CharOffset, CharOffset2, LastLength : integer;
CodeStart : integer;
Line, Token, AsgnTargetList, S, SourceLine : string;
Stop : Boolean;
CodeElement, LastCodeElement, Parent : TCodeElement;
ModuleImport : TModuleImport;
Variable : TVariable;
Klass : TParsedClass;
IsBuiltInType : Boolean;
LineStarts: TList;
LineStartsGuard: ISafeGuard;
GlobalList : TStringList;
GlobalListGuard : ISafeGuard;
AsgnTargetCount : integer;
begin
LineStarts := TList(Guard(TList.Create, LineStartsGuard));
GlobalList := TStringList(Guard(TStringList.Create, GlobalListGuard));
GlobalList.CaseSensitive := True;
UseModifiedSource := True;
Module.Clear;
Module.fCodeBlock.StartLine := 1;
Module.fIndent := -1; // so that everything is a child of the module
// Change \" \' and \\ into ** so that text searches
// for " and ' won't hit escaped ones
//Module.fMaskedSource := fEscapedQuotesRE.Replace(Source, '**', False);
Module.fMaskedSource := Copy(Module.fSource, 1, MaxInt);
ReplaceQuotedChars(Module.fMaskedSource);
// Replace all chars in strings and comments with *
// This ensures that text searches don't mistake comments for keywords, and that all
// matches are in the same line/comment as the original
MaskStringsAndComments(Module.fMaskedSource);
P := PWideChar(Module.fMaskedSource);
LineNo := 0;
Stop := False;
LastCodeElement := Module;
while not Stop and (P^ <> #0) do begin
GetLine(P, Line, LineNo);
if (Length(Line) = 0) or fBlankLineRE.Exec(Line) then begin
// skip blank lines and comment lines
end else if fCodeRE.Exec(Line) then begin
// found class or function definition
GlobalList.Clear;
CodeStart := LineNo;
// Process continuation lines
if ProcessLineContinuation(P, Line, LineNo, LineStarts) then
fCodeRE.Exec(Line); // reparse
S := StrReplaceChars(fCodeRE.Match[4], ['(', ')'], ' ');
if fCodeRE.Match[2] = 'class' then begin
// class definition
CodeElement := TParsedClass.Create;
TParsedClass(CodeElement).fSuperClasses.CommaText := S;
end else begin
// function or method definition
CodeElement := TParsedFunction.Create;
CharOffset := fCodeRE.MatchPos[4];
LastLength := Length(S);
Token := StrToken(S, WideChar(','));
CharOffset2 := CalcIndent(Token);
Token := Trim(Token);
Index := 0;
While Token <> '' do begin
Variable := TVariable.Create;
Variable.Parent := CodeElement;
if StrIsLeft(PWideChar(Token), '**') then begin
Variable.Name := Copy(Token, 3, Length(Token) -2);
Include(Variable.Attributes, vaStarStarArgument);
end else if Token[1] = '*' then begin
Variable.Name := Copy(Token, 2, Length(Token) - 1);
Include(Variable.Attributes, vaStarArgument);
end else begin
Index := CharPos(Token, WideChar('='));
if Index > 0 then begin
Variable.Name := Trim(Copy(Token, 1, Index - 1));
Variable.DefaultValue := Copy(Token, Index + 1, Length(Token) - Index);
Include(Variable.Attributes, vaArgumentWithDefault);
end else begin
Variable.Name := Token;
Include(Variable.Attributes, vaArgument);
end;
end;
CharOffsetToCodePos(CharOffset + CharOffset2, CodeStart, LineStarts, Variable.fCodePos);
// Deal with string annotations (Issue 511)
if CharPos(Variable.Name, MaskChar) > 0 then begin
SourceLine := GetNthSourceLine(Variable.fCodePos.LineNo);
Variable.Name :=
Copy(SourceLine, Variable.CodePos.CharOffset, Length(Variable.Name));
end;
// Deal with string arguments (Issue 32)
if (Variable.DefaultValue <> '') then begin
if CharPos(Variable.DefaultValue, MaskChar) > 0 then begin
SourceLine := GetNthSourceLine(Variable.fCodePos.LineNo);
Variable.DefaultValue :=
Copy(SourceLine, Variable.CodePos.CharOffset + Index, Length(Variable.DefaultValue));
end;
Variable.DefaultValue := Trim(Variable.DefaultValue);
end;
TParsedFunction(CodeElement).fArguments.Add(Variable);
Inc(CharOffset, LastLength - Length(S));
LastLength := Length(S);
Token := StrToken(S, ',');
CharOffset2 := CalcIndent(Token);
Token := Trim(Token);
end;
end;
CodeElement.Name := fCodeRE.Match[3];
CodeElement.fCodePos.LineNo := CodeStart;
CodeElement.fCodePos.CharOffset := fCodeRe.MatchPos[3];
CodeElement.fIndent := CalcIndent(fCodeRE.Match[1]);
CodeElement.fCodeBlock.StartLine := CodeStart;
// Decide where to insert CodeElement
if CodeElement.Indent > LastCodeElement.Indent then
LastCodeElement.AddChild(CodeElement)
else begin
LastCodeElement.fCodeBlock.EndLine := Pred(CodeStart);
Parent := LastCodeElement.Parent as TCodeElement;
while Assigned(Parent) do begin
// Note that Module.Indent = -1
if Parent.Indent < CodeElement.Indent then begin
Parent.AddChild(CodeElement);
break;
end else
Parent.fCodeBlock.EndLine := Pred(CodeStart);
Parent := Parent.Parent as TCodeElement;
end;
end;
LastCodeElement := CodeElement;
end else begin
// Close Functions and Classes based on indentation
Indent := CalcIndent(Line);
while Assigned(LastCodeElement) and (LastCodeElement.Indent >= Indent) do begin
// Note that Module.Indent = -1
LastCodeElement.fCodeBlock.EndLine := Pred(LineNo);
LastCodeElement := LastCodeElement.Parent as TCodeElement;
end;
// search for imports
if fImportRE.Exec(Line) then begin
// Import statement
CodeStart := LineNo;
if ProcessLineContinuation(P, Line, LineNo, LineStarts) then
fImportRE.Exec(Line); // reparse
S := fImportRE.Match[1];
CharOffset := fImportRE.MatchPos[1];
LastLength := Length(S);
Token := StrToken(S, ',');
While Token <> '' do begin
if fAliasRE.Exec(Token) then begin
if fAliasRE.MatchLen[3] > 0 then begin
Token := fAliasRE.Match[3];
CharOffset2 := fAliasRE.MatchPos[3] - 1;
end else begin
Token := fAliasRE.Match[1];
CharOffset2 := fAliasRE.MatchPos[1] - 1;
end;
ModuleImport := TModuleImport.Create(Token, CodeBlock(CodeStart, LineNo));
CharOffsetToCodePos(CharOffset + CharOffset2, CodeStart, LineStarts, ModuleImport.fCodePos);
ModuleImport.Parent := Module;
if fAliasRE.MatchLen[3] > 0 then
ModuleImport.fRealName := fAliasRE.Match[1];
Module.fImportedModules.Add(ModuleImport);
end;
Inc(CharOffset, LastLength - Length(S));
LastLength := Length(S);
Token := StrToken(S, ',');
end;
end else if fFromImportRE.Exec(Line) then begin
// From Import statement
CodeStart := LineNo;
if ProcessLineContinuation(P, Line, LineNo, LineStarts) then
fFromImportRE.Exec(Line); // reparse
ModuleImport := TModuleImport.Create(fFromImportRE.Match[2],
CodeBlock(CodeStart, LineNo));
ModuleImport.fPrefixDotCount := fFromImportRE.MatchLen[1];
ModuleImport.fCodePos.LineNo := CodeStart;
ModuleImport.fCodePos.CharOffset := fFromImportRE.MatchPos[2];
S := fFromImportRE.Match[3];
if Trim(S) = '*' then
ModuleImport.ImportAll := True
else begin
ModuleImport.ImportedNames := TObjectList.Create(True);
CharOffset := fFromImportRE.MatchPos[3];
if Pos('(', S) > 0 then begin
Inc(CharOffset);
S := StrRemoveChars(S, ['(',')']); //from module import (a,b,c) form
end;
LastLength := Length(S);
Token := StrToken(S, ',');
While Token <> '' do begin
if fAliasRE.Exec(Token) then begin
if fAliasRE.MatchLen[3] > 0 then begin
Token := fAliasRE.Match[3];
CharOffset2 := fAliasRE.MatchPos[3] - 1;
end else begin
Token := fAliasRE.Match[1];
CharOffset2 := fAliasRE.MatchPos[1] - 1;
end;
Variable := TVariable.Create;
Variable.Name := Token;
CharOffsetToCodePos(CharOffset + CharOffset2, CodeStart, LineStarts, Variable.fCodePos);
Variable.Parent := ModuleImport;
Include(Variable.Attributes, vaImported);
if fAliasRE.MatchLen[3] > 0 then
Variable.fRealName := fAliasRE.Match[1];
ModuleImport.ImportedNames.Add(Variable);
end;
Inc(CharOffset, LastLength - Length(S));
LastLength := Length(S);
Token := StrToken(S, ',');
end;
end;
ModuleImport.Parent := Module;
Module.fImportedModules.Add(ModuleImport);
end else if fAssignmentRE.Exec(Line) then begin
S := Copy(Line, 1, fAssignmentRE.MatchPos[5]-1);
AsgnTargetList := StrToken(S, '=');
CharOffset2 := 1; // Keeps track of the end of the identifier
while AsgnTargetList <> '' do begin
AsgnTargetCount := 0;
Variable := nil;
while AsgnTargetList <> '' do begin
Token := StrToken(AsgnTargetList, ',');
CharOffset := CharOffset2; // Keeps track of the start of the identifier
Inc(CharOffset, CalcIndent(Token, 1)); // do not expand tabs
Inc(CharOffset2, Succ(Length(Token))); // account for ,
Token := Trim(Token);
if StrIsLeft(PWideChar(Token), 'self.') then begin
// class variable
Token := Copy(Token, 6, Length(Token) - 5);
Inc(CharOffset, 5); // Length of "self."
// search for class attributes
Klass := GetActiveClass(LastCodeElement);
if Assigned(Klass) then begin
Variable := TVariable.Create;
Variable.Name := Token;
Variable.Parent := Klass;
Variable.fCodePos.LineNo := LineNo;
Variable.fCodePos.CharOffset := CharOffset;
Klass.fAttributes.Add(Variable);
Inc(AsgnTargetCount);
end;
end else if (GlobalList.IndexOf(Token) < 0) then begin
// search for local/global variables
Variable := TVariable.Create;
Variable.Name := Token;
Variable.Parent := LastCodeElement;
Variable.fCodePos.LineNo := LineNo;
Variable.fCodePos.CharOffset := CharOffset;
if LastCodeElement.ClassType = TParsedFunction then
TParsedFunction(LastCodeElement).Locals.Add(Variable)
else if LastCodeElement.ClassType = TParsedClass then begin
Include(Variable.Attributes, vaClassAttribute);
TParsedClass(LastCodeElement).Attributes.Add(Variable)
end else begin