forked from fpc/Lazarus
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbasiccodetools.pas
More file actions
7122 lines (6758 loc) · 201 KB
/
Copy pathbasiccodetools.pas
File metadata and controls
7122 lines (6758 loc) · 201 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
{
***************************************************************************
* *
* This source 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 2 of the License, or *
* (at your option) any later version. *
* *
* This code 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. *
* *
* A copy of the GNU General Public License is available on the World *
* Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also *
* obtain it by writing to the Free Software Foundation, *
* Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA. *
* *
***************************************************************************
Author: Mattias Gaertner
Abstract:
Basic pascal code functions. Many of the functions have counterparts in the
code tools, which are faster, more flexible and aware of compiler settings
and directives.
}
unit BasicCodeTools;
{$ifdef FPC}
{$mode objfpc}
{$else}
{$ifdef MSWindows}
{$define Windows}
{$endif}
{$endif}{$H+}
{$inline on}
interface
uses
Classes, SysUtils, StrUtils, AVL_Tree,
// LazUtils
LazFileUtils, LazStringUtils, LazUTF8,
// Codetools
SourceLog, KeywordFuncLists, FileProcs;
//----------------------------------------------------------------------------
{ These functions are used by the codetools }
// comments
function FindNextNonSpace(const ASource: string; StartPos: integer): integer;
function FindPrevNonSpace(const ASource: string; StartPos: integer): integer;
function FindCommentEnd(const ASource: string; StartPos: integer;
NestedComments: boolean): integer; overload;
function FindCommentEnd(Src: PChar; NestedComments: boolean): PChar; overload;
function IsCommentEnd(const ASource: string; EndPos: integer): boolean;
function FindNextComment(const ASource: string;
StartPos: integer; MaxPos: integer = 0): integer;
procedure FindCommentsInRange(const Src: string; StartPos, EndPos: integer;
out FirstCommentStart, FirstAtomStart, LastCommentEnd, LastAtomEnd: integer;
NestedComments: boolean = false);
function FindNextCompilerDirective(const ASource: string; StartPos: integer;
NestedComments: boolean; MaxPos: integer = -1): integer;
function FindNextCompilerDirectiveWithName(const ASource: string;
StartPos: integer; const DirectiveName: string;
NestedComments: boolean; out ParamPos: integer): integer;
function FindNextIncludeDirective(const ASource: string;
StartPos: integer; NestedComments: boolean;
out FilenameStartPos, FileNameEndPos,
CommentStartPos, CommentEndPos: integer): integer;
function FindNextIDEDirective(const ASource: string; StartPos: integer;
NestedComments: boolean; EndPos: integer = 0): integer;
function CleanCodeFromComments(const Src: string;
NestedComments: boolean; KeepDirectives: boolean = false;
KeepVerbosityDirectives: boolean = false): string;
function ExtractCommentContent(const ASource: string; CommentStart: integer;
NestedComments: boolean;
TrimStart: boolean = false; TrimEnd: boolean = false;
TrimPasDoc: boolean = false): string;
function FindMainUnitHint(const ASource: string; out Filename: string): boolean;
function InEmptyLine(const ASource: string; StartPos: integer): boolean;
function SkipResourceDirective(const ASource: string; StartPos, EndPos: integer;
NestedComments: boolean): integer;
// indent
function GetLineIndent(const Source: string; Position: integer): integer;
function GetLineIndentWithTabs(const Source: string; Position: integer;
TabWidth: integer): integer;
function GetPosInLine(const Source: string; Position: integer): integer; // 0 based
function GetBlockMinIndent(const Source: string;
StartPos, EndPos: integer): integer;
function GetIndentStr(Indent: integer; TabWidth: integer = 0): string;
procedure IndentText(const Source: string; Indent, TabWidth: integer;
out NewSource: string);
function FindFirstNonSpaceCharInLine(const Source: string;
Position: integer): integer;
function IsFirstNonSpaceCharInLine(const Source: string;
Position: integer): boolean;
procedure GuessIndentSize(const Source: string;
var IndentSize: integer; TabWidth: integer = 2; MaxLineCount: integer = 10000);
function ReIndent(const Source: string; OldIndent, OldTabWidth,
NewIndent, NewTabWidth: integer): string;
// identifiers
procedure GetIdentStartEndAtPosition(const Source:string; Position:integer;
out IdentStart,IdentEnd:integer);
function GetIdentStartPosition(const Source:string; Position:integer): integer;
function GetIdentLen(Identifier: PChar): integer;
function GetIdentifier(Identifier: PChar; aSkipAmp: Boolean = True;
IsDottedIdent: Boolean = False): string;
function FindNextIdentifier(const Source: string; StartPos, MaxPos: integer): integer;
function FindNextIdentifierSkipStrings(const Source: string;
StartPos, MaxPos: integer): integer;
function IsValidDottedIdent(const Ident: string; AllowDots: Boolean = True): Boolean; // as sysutils.IsValidIdent, but faster and supports &
function IsValidIdentPair(const NamePair: string): boolean; // true if exactly two identifiers separated by a dot
function IsValidIdentPair(const NamePair: string; out First, Second: string): boolean;
function ExtractPasIdentifier(const Ident: string; AllowDots: Boolean): string; // removes non identifier chars
// line/code ends
function SrcPosToLineCol(const s: string; Position: integer;
out Line, Col: integer): boolean;
procedure GetLineStartEndAtPosition(const Source: string; Position:integer;
out LineStart,LineEnd:integer); // LineEnd at first line break character
function GetLineStartPosition(const Source: string; Position:integer): integer;
function GetLineInSrc(const Source: string; Position:integer): string;
function LineEndCount(const Txt: string): integer; inline;
function LineEndCount(const Txt: string; out LengthOfLastLine:integer): integer; inline;
function LineEndCount(const Txt: string; StartPos, EndPos: integer;
out LengthOfLastLine:integer): integer;
function EmptyCodeLineCount(const Source: string; StartPos, EndPos: integer;
NestedComments: boolean): integer;
function PositionsInSameLine(const Source: string;
Pos1, Pos2: integer): boolean;
function FindLineEndOrCodeInFrontOfPosition(const Source: string;
Position, MinPosition: integer; NestedComments: boolean;
StopAtDirectives: boolean = true; SkipSemicolonComma: boolean = true;
SkipEmptyLines: boolean = false): integer;
function FindLineEndOrCodeAfterPosition(const Source: string;
Position, MaxPosition: integer; NestedComments: boolean;
StopAtDirectives: boolean = true; SkipEmptyLines: boolean = false;
IncludeLineEnd: boolean = false): integer;
function FindFirstLineEndInFrontOfInCode(const Source: string;
Position, MinPosition: integer; NestedComments: boolean): integer;
function FindFirstLineEndAfterInCode(const Source: string;
Position, MaxPosition: integer; NestedComments: boolean): integer;
function ChompLineEndsAtEnd(const s: string): string;
function ChompOneLineEndAtEnd(const s: string): string;
function TrimLineEnds(const s: string; TrimStart, TrimEnd: boolean): string;
// brackets
function GetBracketLvl(const Src: string; StartPos, EndPos: integer;
NestedComments: boolean): integer;
// string interpolation ($'text {expr} text')
procedure SkipPascalInterpolatedString(var p: PChar; NestedComments: Boolean);
// replacements
function ReplacementNeedsLineEnd(const Source: string;
FromPos, ToPos, NewLength, MaxLineLength: integer): boolean;
function CountNeededLineEndsToAddForward(const Src: string;
StartPos, MinLineEnds: integer): integer;
function CountNeededLineEndsToAddBackward(const Src: string;
StartPos, MinLineEnds: integer): integer;
procedure AdjustPositionAfterInsert(var p: integer; IsStart: boolean;
FromPos, ToPos, DiffPos: integer);
// comparison
function CompareText(Txt1: PChar; Len1: integer; Txt2: PChar; Len2: integer;
CaseSensitive: boolean): integer; overload;
function CompareTextCT(const Txt1, Txt2: string;
CaseSensitive: boolean = false): integer; overload;
function CompareText(Txt1: PChar; Len1: integer; Txt2: PChar; Len2: integer;
CaseSensitive, IgnoreSpace: boolean): integer; overload;
function CompareTextIgnoringSpace(const Txt1, Txt2: string;
CaseSensitive: boolean): integer;
function CompareTextIgnoringSpace(Txt1: PChar; Len1: integer;
Txt2: PChar; Len2: integer; CaseSensitive: boolean): integer;
function CompareAnsiStringIgnoringSpaceIgnoreCase(Txt1, Txt2: pointer): integer;
function CompareSubStrings(const Find, Txt: string;
FindStartPos, TxtStartPos, Len: integer; CaseSensitive: boolean): integer;
function CompareIdentifiers(Identifier1, Identifier2: PChar): integer; {$IFDEF HasInline}inline;{$ENDIF}
function CompareIdentifiersCaseSensitive(Identifier1, Identifier2: PChar): integer;
function CompareIdentifierPtrs(Identifier1, Identifier2: Pointer): integer; {$IFDEF HasInline}inline;{$ENDIF}
function ComparePrefixIdent(PrefixIdent, Identifier: PChar): boolean;
function TextBeginsWith(Txt: PChar; TxtLen: integer; StartTxt: PChar;
StartTxtLen: integer; CaseSensitive: boolean): boolean;
function StrBeginsWith(const s, Prefix: string): boolean;
function IdentifierPos(Search, Identifier: PChar): PtrInt; // search Search in Identifier
function CompareAtom(p1, p2: PChar; NestedComments: boolean): integer;
function CompareStringConstants(p1, p2: PChar): integer; // compare case sensitive
function CompareComments(p1, p2: PChar; NestedComments: boolean): integer; // compare case insensitive
function FindDiff(const s1, s2: string): integer;
function dbgsDiff(Expected, Actual: string): string; overload;
// dotted identifiers. Note: spaces and comments are treated as end
function DottedIdentifierLength(Identifier: PChar): integer;
function GetDottedIdentifier(Identifier: PChar): string;
function IsDottedIdentifier(const Identifier: string; AllowAmp: boolean = True): boolean;
function GetDotCountInIdentifier(Identifier: PChar): integer; // -1 if not an identifier
function CompareDottedIdentifiers(Identifier1, Identifier2: PChar): integer;
function CompareDottedIdentifiersCaseSensitive(Identifier1, Identifier2: PChar): integer;
function ChompDottedIdentifier(const Identifier: string): string;
function SkipDottedIdentifierPart(var Identifier: PChar): boolean;
function DottedIdentifierStartsWith(Identifier, StartsWithIdent: PChar): boolean; // true if equal or longer
function DottedIdentifierEndsWith(Identifier, EndsWithIdent: PChar): boolean; // true if equal or longer
function SplitDottedIdentifier(const Dotted: string; out Arr: TStringArray; SkipAmps: boolean = false): boolean;
// space and special chars
function TrimCodeSpace(const ACode: string): string;
function CodeIsOnlySpace(const ACode: string; FromPos, ToPos: integer): boolean;
function StringToPascalConst(const s: string): string;
function UnicodeSpacesToASCII(const s: string): string;
function RemoveAmpersands(const s: string): string;
// string constants
function SplitStringConstant(const StringConstant: string;
FirstLineLength, OtherLineLengths, Indent: integer;
const aLineBreak: string): string;
procedure ImproveStringConstantStart(const ACode: string; var StartPos: integer);
procedure ImproveStringConstantEnd(const ACode: string; var EndPos: integer);
function HexStrToIntDef(p: PChar; Def: integer): integer;
// search
function SearchNextInText(Search: PChar; SearchLen: PtrInt;
Src: PChar; SrcLen: PtrInt;
StartPos: PtrInt;// 0 based
out MatchStart, MatchEnd: PtrInt;// 0 based
WholeWords: boolean = false; MultiLine: boolean = false): boolean;
procedure HasTxtWord(SearchWord, Txt: PChar; out WholeWord: boolean;
out Count: SizeInt);
// misc
function SubString(p: PChar; Count: SizeInt): string; overload;
// files
type
{ TUnitFileInfo }
TUnitFileInfo = class
private
FFilename: string;
FUnitName: string;
function GetFileUnitNameWithoutNamespace: string;
function GetIdentifierStartInUnitName: Integer;
public
constructor Create(const TheUnitName, TheFilename: string);
property FileUnitName: string read FUnitName;
property FileUnitNameWithoutNamespace: string read GetFileUnitNameWithoutNamespace;
property Filename: string read FFilename;
property IdentifierStartInUnitName: Integer read GetIdentifierStartInUnitName;
end;
{ TNameSpaceInfo }
TNameSpaceInfo = class
private
FUnitName: string;
FNamespace: string;
FIdentifierStartInUnitName: Integer;
public
constructor Create(const TheNamespace, TheUnitName: string; TheIdentifierStartInUnitName: Integer);
property UnitName: string read FUnitName;
property Namespace: string read FNamespace;
property IdentifierStartInUnitName: Integer read FIdentifierStartInUnitName;
end;
function ExtractFileNamespace(const Filename: string): string;
procedure AddToTreeOfUnitFilesOrNamespaces(
var TreeOfUnitFiles, TreeOfNameSpaces: TAVLTree;
const NameSpacePath, Filename: string;
CaseInsensitive, KeepDoubles: boolean);
function GatherUnitFiles(const BaseDir, SearchPath,
Extensions, NameSpacePath: string; KeepDoubles, CaseInsensitive: boolean;
var TreeOfUnitFiles, TreeOfNamespaces: TAVLTree): boolean;
procedure FreeTreeOfUnitFiles(TreeOfUnitFiles: TAVLTree);
procedure AddToTreeOfUnitFiles(var TreeOfUnitFiles: TAVLTree;
const Filename, Unitname: string;
KeepDoubles: boolean);
procedure AddToTreeOfNamespaces(var TreeOfNameSpaces: TAVLTree;
const UnitName, ParentNameSpacePath: string;
KeepDoubles: boolean);
function CompareUnitFileInfos(Data1, Data2: Pointer): integer;
function CompareNameSpaceInfos(Data1, Data2: Pointer): integer;
function CompareUnitNameAndUnitFileInfo(UnitnamePAnsiString,
UnitFileInfo: Pointer): integer;
function CompareNameSpaceAndNameSpaceInfo(NamespacePAnsiString,
NamespaceInfo: Pointer): integer;
//-----------------------------------------------------------------------------
// functions / procedures
{ These functions are not context sensitive. Especially they ignore compiler
settings and compiler directives. They exist only for basic usage.
}
// source type
function FindSourceType(const Source: string;
var SrcNameStart, SrcNameEnd: integer; NestedComments: boolean = false): string;
// read dotted identifier, skipping spaces and comments
function ReadDottedIdentifier(const Source: string; var Position: integer;
NestedComments: boolean = false; aSkipAmp: boolean = true): string;
function ReadDottedIdentifier(var Position: PChar; SrcEnd: PChar;
NestedComments: boolean = false; aSkipAmp: boolean = true): string;
// program name
function RenameProgramInSource(Source:TSourceLog;
const NewProgramName:string):boolean;
function FindProgramNameInSource(const Source:string;
out ProgramNameStart,ProgramNameEnd:integer):string;
// unit name
function RenameUnitInSource(Source:TSourceLog;const NewUnitName:string):boolean;
function FindUnitNameInSource(const Source:string;
out UnitNameStart,UnitNameEnd: integer; NestedComments: boolean = false):string;
function FindModuleNameInSource(const Source:string;
out ModuleType: string; out NameStart,NameEnd: integer;
NestedComments: boolean = false):string;
// uses sections
function UnitIsUsedInSource(const Source,SrcUnitName:string):boolean;
function RenameUnitInProgramUsesSection(Source:TSourceLog;
const OldUnitName, NewUnitName, NewInFile:string): boolean;
function AddToProgramUsesSection(Source:TSourceLog;
const AUnitName,InFileName:string):boolean;
function RemoveFromProgramUsesSection(Source:TSourceLog;
const AUnitName:string):boolean;
function RenameUnitInInterfaceUsesSection(Source:TSourceLog;
const OldUnitName, NewUnitName, NewInFile:string): boolean;
function AddToInterfaceUsesSection(Source:TSourceLog;
const AUnitName,InFileName:string):boolean;
function RemoveFromInterfaceUsesSection(Source:TSourceLog;
const AUnitName:string):boolean;
// single uses section
function IsUnitUsedInUsesSection(const Source,SrcUnitName:string;
UsesStart:integer):boolean;
function RenameUnitInUsesSection(Source:TSourceLog; UsesStart: integer;
const OldUnitName, NewUnitName, NewInFile:string): boolean;
function AddUnitToUsesSection(Source:TSourceLog;
const AnUnitName,InFilename:string; UsesStart:integer):boolean;
function RemoveUnitFromUsesSection(Source:TSourceLog;
const AnUnitName:string; UsesStart:integer):boolean;
// compiler directives
function FindIncludeDirective(const Source,Section:string; Index:integer;
out IncludeStart,IncludeEnd:integer):boolean;
function ExtractLongParamDirective(const Source: string; CommentStartPos: integer;
out DirectiveName, FileParam: string): boolean;
function SplitCompilerDirective(const Directive:string;
out DirectiveName,Parameters:string):boolean;
// createform
{function AddCreateFormToProgram(Source:TSourceLog;
const AClassName,AName:string):boolean;
function RemoveCreateFormFromProgram(Source:TSourceLog;
const AClassName,AName:string):boolean;
function CreateFormExistsInProgram(const Source,AClassName,AName:string):boolean;
function ListAllCreateFormsInProgram(const Source:string):TStrings;
}
// resource code
function FindResourceInCode(const Source, AddCode:string;
out Position,EndPosition:integer):boolean;
function AddResourceCode(Source:TSourceLog; const AddCode:string):boolean;
// form components
function FindFormClassDefinitionInSource(const Source, FormClassName:string;
var FormClassNameStartPos, FormBodyStartPos: integer):boolean;
function FindFormComponentInSource(const Source: string; FormBodyStartPos: integer;
const ComponentName, ComponentClassName: string): integer;
function AddFormComponentToSource(Source:TSourceLog; FormBodyStartPos: integer;
const ComponentName, ComponentClassName: string): boolean;
function RemoveFormComponentFromSource(Source:TSourceLog;
FormBodyStartPos: integer;
const ComponentName, ComponentClassName: string): boolean;
function FindClassAncestorName(const Source, FormClassName: string): string;
// procedure specifiers
function FindFirstProcSpecifier(const ProcText: string;
NestedComments: boolean = false): integer;
function SearchProcSpecifier(const ProcText, Specifier: string;
out SpecifierEndPosition: integer;
NestedComments: boolean = false;
WithSpaceBehindSemicolon: boolean = true): integer;
function RemoveProcSpecifier(const ProcText, Specifier: string;
NestedComments: boolean = false): string;
// code search
function SearchCodeInSource(const Source, Find: string; StartPos: integer;
out EndFoundPosition: integer; CaseSensitive: boolean;
NestedComments: boolean = false): integer;
function ReadNextPascalAtom(const Source: string;
var Position: integer; out AtomStart: integer; NestedComments: boolean = false;
SkipDirectives: boolean = false): string;
procedure ReadRawNextPascalAtom(const Source: string;
var Position: integer; out AtomStart: integer;
NestedComments: boolean = false; SkipDirectives: boolean = false);
procedure ReadRawNextPascalAtom(var Position: PChar; out AtomStart: PChar;
const SrcEnd: PChar = nil; NestedComments: boolean = false;
SkipDirectives: boolean = false);
function ReadRawPascal(StartP: PChar; SrcEnd: PChar = nil; NestedComments: boolean = false;
SkipDirectives: boolean = true): string;
procedure ReadPriorPascalAtom(const Source: string;
var Position: integer; out AtomEnd: integer; NestedComments: boolean = false);
function ReadTilPascalBracketClose(const Source: string;
var Position: integer; NestedComments: boolean = false): boolean;
function GetAtomLength(p: PChar; NestedComments: boolean): integer;
function GetAtomString(p: PChar; NestedComments: boolean): string;
function FindStartOfAtom(const Source: string; Position: integer): integer;
function FindEndOfAtom(const Source: string; Position: integer): integer;
//-----------------------------------------------------------------------------
const
MaxLineLength: integer = 80;
//=============================================================================
implementation
function Min(i1, i2: integer): integer; inline;
begin
if i1<=i2 then Result:=i1 else Result:=i2;
end;
function Max(i1, i2: integer): integer; inline;
begin
if i1>=i2 then Result:=i1 else Result:=i2;
end;
procedure SkipPascalInterpolatedString(var p: PChar; NestedComments: Boolean);
// Precondition: p^ = '$' and p[1] = ''''
// Postcondition: p advanced past the closing apostrophe (or past the offending
// newline/EOF on a malformed literal, matching compiler behaviour).
//
// Syntax (modeswitch INTERPOLATEDSTRINGS, default in `{$mode unleashed}`):
// $'literal text {expr[:mask]} more text'
// - `''` inside the string part = literal apostrophe
// - `{{` / `}}` inside the string = literal brace
// - `{` starts an expression; `}` at the top level of that expression ends it
// - a `:` at the top level of an expression starts a raw format mask that
// runs verbatim to the closing `}` (it is not Pascal, so it is skipped)
// - expressions may span multiple lines and contain nested strings, comments,
// balanced `(...)`/`[...]` and nested `$'...'` interpolations
// - string parts themselves may NOT cross a line
procedure SkipCurlyComment;
var Lvl: Integer;
begin
Lvl:=1;
inc(p);
while p^<>#0 do begin
case p^ of
'{': if NestedComments then inc(Lvl);
'}':
begin
dec(Lvl);
if Lvl=0 then begin
inc(p);
exit;
end;
end;
end;
inc(p);
end;
end;
procedure SkipRoundComment;
var Lvl: Integer;
begin
Lvl:=1;
inc(p,2);
while p^<>#0 do begin
if (p^='(') and (p[1]='*') and NestedComments then begin
inc(Lvl); inc(p,2);
end else if (p^='*') and (p[1]=')') then begin
dec(Lvl); inc(p,2);
if Lvl=0 then exit;
end else
inc(p);
end;
end;
procedure SkipRegularApostropheString;
// p^ = ''''; skip `'...'` with `''` as escaped apostrophe, single line
begin
inc(p);
while p^<>#0 do begin
case p^ of
'''':
if p[1]='''' then
inc(p,2)
else begin
inc(p);
exit;
end;
#10,#13:
exit;
else
inc(p);
end;
end;
end;
procedure SkipBacktickString;
begin
inc(p);
while not (p^ in [#0,'`']) do inc(p);
if p^='`' then inc(p);
end;
procedure SkipCharConstant;
begin
inc(p);
if p^='$' then begin
inc(p);
while IsHexNumberChar[p^] do inc(p);
end else
while IsNumberChar[p^] do inc(p);
end;
procedure SkipInterpExpr;
// p is just past the expression-opening `{`; advance past the matching `}`
var PLvl: Integer;
begin
PLvl:=0;
while p^<>#0 do begin
case p^ of
'}':
begin
inc(p);
exit;
end;
':':
if PLvl=0 then begin
// `{expr:mask}` - mask runs raw to the closing `}`
while not (p^ in [#0,'}']) do inc(p);
end else
inc(p);
'{':
SkipCurlyComment;
'(':
if p[1]='*' then
SkipRoundComment
else begin
inc(PLvl); inc(p);
end;
')':
begin
if PLvl>0 then dec(PLvl);
inc(p);
end;
'[':
begin
inc(PLvl); inc(p);
end;
']':
begin
if PLvl>0 then dec(PLvl);
inc(p);
end;
'/':
if p[1]='/' then begin
while not (p^ in [#0,#10,#13]) do inc(p);
end else
inc(p);
'''':
SkipRegularApostropheString;
'`':
SkipBacktickString;
'#':
SkipCharConstant;
'$':
if p[1]='''' then
SkipPascalInterpolatedString(p,NestedComments)
else begin
inc(p);
while IsHexNumberChar[p^] do inc(p);
end;
else
inc(p);
end;
end;
end;
begin
// skip $'
inc(p,2);
while p^<>#0 do begin
case p^ of
'''':
if p[1]='''' then
inc(p,2) // doubled apostrophe = literal
else begin
inc(p);
exit;
end;
'{':
if p[1]='{' then
inc(p,2) // escaped brace
else begin
inc(p);
SkipInterpExpr;
end;
'}':
if p[1]='}' then
inc(p,2) // escaped brace
else
inc(p);
#10,#13:
exit; // newline in string part ends the literal
else
inc(p);
end;
end;
end;
{ most simple code tools - just methods }
function FindIncludeDirective(const Source,Section:string; Index:integer;
out IncludeStart,IncludeEnd:integer):boolean;
var Atom,DirectiveName:string;
Position,EndPos,AtomStart:integer;
Filename:string;
begin
Result:=false;
// find section
Position:=SearchCodeInSource(Source,Section,1,EndPos,false);
if (Position<1) or (EndPos<1) then exit;
// search for include directives
repeat
Atom:=ReadNextPascalAtom(Source,Position,AtomStart);
if LazStartsStr('{$',Atom) or LazStartsStr('(*$', Atom) then begin
SplitCompilerDirective(Atom,DirectiveName,Filename);
if (DirectiveName='i') or (DirectiveName='I')
or (CompareText(DirectiveName,'include')=0) then begin
// include directive
dec(Index);
if Index=0 then begin
IncludeStart:=AtomStart;
IncludeEnd:=Position;
Result:=true;
exit;
end;
end;
end;
until Atom='';
end;
function ExtractLongParamDirective(const Source: string; CommentStartPos: integer;
out DirectiveName, FileParam: string): boolean;
var
p, StartPos: PChar;
begin
Result:=false;
FileParam:='';
if CommentStartPos>length(Source) then exit;
p:=@Source[CommentStartPos];
if (p^<>'{') or (p[1]<>'$') then exit;
inc(p,2);
StartPos:=p;
if not IsIdentStartChar[p^] then exit;
while IsIdentChar[p^] do inc(p);
DirectiveName:=copy(Source,StartPos-PChar(Source)+1,p-StartPos);
Result:=true;
while p^ in [' ',#9] do inc(p);
if p^='''' then begin
// 'param with spaces'
inc(p);
StartPos:=p;
while not (p^ in [#0,#10,#13,'''']) do inc(p);
end else begin
// param without spaces
StartPos:=p;
while not (p^ in [#0,#9,#10,#13,' ','}']) do inc(p);
end;
FileParam:=copy(Source,StartPos-PChar(Source)+1,p-StartPos);
end;
function SplitCompilerDirective(const Directive:string;
out DirectiveName,Parameters:string):boolean;
var EndPos,DirStart,DirEnd:integer;
begin
if LazStartsStr('{$',Directive) or LazStartsStr('(*$',Directive) then begin
if LazStartsStr('{$',Directive) then begin
DirStart:=3;
DirEnd:=length(Directive);
end else begin
DirStart:=4;
DirEnd:=length(Directive)-1;
end;
EndPos:=DirStart;
while (EndPos<DirEnd) and (IsIdentChar[Directive[EndPos]]) do
inc(EndPos);
DirectiveName:=lowercase(copy(Directive,DirStart,EndPos-DirStart));
Parameters:=copy(Directive,EndPos+1,DirEnd-EndPos-1);
Result:=true;
end else
Result:=false;
end;
function FindSourceType(const Source: string; var SrcNameStart,
SrcNameEnd: integer; NestedComments: boolean): string;
var
u: String;
p, AtomStart: Integer;
begin
// read first atom for type
SrcNameStart:=0;
SrcNameEnd:=0;
p:=1;
Result:=ReadNextPascalAtom(Source,p,AtomStart,NestedComments);
u:=Uppercase(Result);
if (u='UNIT') or (u='PROGRAM') or (u='LIBRARY') or (u='PACKAGE') then begin
// read name
ReadNextPascalAtom(Source,p,AtomStart,NestedComments);
if p<=AtomStart then exit;
if not IsIdentStartChar[Source[AtomStart]] then exit;
SrcNameStart:=AtomStart;
SrcNameEnd:=p;
repeat
ReadRawNextPascalAtom(Source,p,AtomStart,NestedComments);
if (AtomStart=p+1) and (Source[AtomStart]='.') then begin
ReadRawNextPascalAtom(Source,p,AtomStart,NestedComments);
if p<=AtomStart then exit;
if not IsIdentStartChar[Source[AtomStart]] then exit;
SrcNameEnd:=p;
end else
break;
until false;
end else begin
Result:='';
end;
end;
function RenameUnitInSource(Source:TSourceLog;const NewUnitName:string):boolean;
var UnitNameStart,UnitNameEnd:integer;
begin
UnitNameStart:=0;
UnitNameEnd:=0;
Result:=(FindUnitNameInSource(Source.Source,UnitNameStart,UnitNameEnd)<>'');
if Result then
Source.Replace(UnitNameStart,UnitNameEnd-UnitNameStart,NewUnitName);
end;
function FindUnitNameInSource(const Source: string; out UnitNameStart,
UnitNameEnd: integer; NestedComments: boolean): string;
var
ModuleType: string;
begin
Result:=FindModuleNameInSource(Source,ModuleType,UnitNameStart,UnitNameEnd,NestedComments);
if CompareText(ModuleType,'UNIT')<>0 then
Result:='';
end;
function FindModuleNameInSource(const Source: string; out ModuleType: string;
out NameStart, NameEnd: integer; NestedComments: boolean): string;
var
u: String;
p, AtomStart: Integer;
begin
// read first atom for type
Result:='';
NameStart:=0;
NameEnd:=0;
p:=1;
ModuleType:=ReadNextPascalAtom(Source,p,AtomStart,NestedComments);
u:=UpperCase(ModuleType);
if (u='UNIT') or (u='PROGRAM') or (u='LIBRARY') or (u='PACKAGE') then begin
// read name
ReadNextPascalAtom(Source,p,AtomStart,NestedComments);
if p<=AtomStart then exit;
if not IsIdentStartChar[Source[AtomStart]] then exit;
NameStart:=AtomStart;
NameEnd:=AtomStart;
Result:=ReadDottedIdentifier(Source,NameEnd,NestedComments);
end else
ModuleType:='';
end;
function ReadDottedIdentifier(const Source: string; var Position: integer; NestedComments: boolean;
aSkipAmp: boolean): string;
var
p: PChar;
begin
if (Position<1) or (Position>length(Source)) then exit('');
p:=@Source[Position];
Result:=ReadDottedIdentifier(p,PChar(Source)+length(Source),NestedComments,aSkipAmp);
Position:=p-PChar(Source)+1;
end;
function ReadDottedIdentifier(var Position: PChar; SrcEnd: PChar; NestedComments: boolean;
aSkipAmp: boolean): string;
var
AtomStart, p: PChar;
s: String;
begin
Result:='';
p:=Position;
ReadRawNextPascalAtom(p,AtomStart,SrcEnd,NestedComments);
Position:=AtomStart;
if (AtomStart>=p) then exit;
Result:=GetIdentifier(AtomStart,aSkipAmp);
if Result='' then exit;
repeat
Position:=p;
ReadRawNextPascalAtom(p,AtomStart,SrcEnd,NestedComments);
if (AtomStart+1<>p) or (AtomStart^<>'.') then exit;
ReadRawNextPascalAtom(p,AtomStart,SrcEnd,NestedComments);
if (AtomStart>=p) then exit;
s:=GetIdentifier(AtomStart,aSkipAmp);
if s='' then exit;
Result:=Result+'.'+s;
until false;
end;
function RenameProgramInSource(Source: TSourceLog;
const NewProgramName:string):boolean;
var ProgramNameStart,ProgramNameEnd:integer;
begin
Result:=(FindProgramNameInSource(Source.Source,
ProgramNameStart,ProgramNameEnd)<>'');
if Result then
Source.Replace(ProgramNameStart,
ProgramNameEnd-ProgramNameStart,NewProgramName)
end;
function FindProgramNameInSource(const Source:string;
out ProgramNameStart,ProgramNameEnd:integer):string;
begin
ProgramNameStart:=0;
ProgramNameEnd:=0;
if UpperCaseStr(FindSourceType(Source,ProgramNameStart,ProgramNameEnd))='PROGRAM'
then
Result:=copy(Source,ProgramNameStart,ProgramNameEnd-ProgramNameStart)
else
Result:='';
end;
function UnitIsUsedInSource(const Source,SrcUnitName:string):boolean;
// search in all uses sections
var UsesStart,UsesEnd:integer;
begin
Result:=false;
repeat
UsesStart:=SearchCodeInSource(Source,'uses',1,UsesEnd,false);
if UsesEnd=0 then ;
if UsesStart>0 then begin
if IsUnitUsedInUsesSection(Source,SrcUnitName,UsesStart) then begin
Result:=true;
exit;
end;
end;
until UsesStart<1;
end;
function RenameUnitInProgramUsesSection(Source:TSourceLog;
const OldUnitName, NewUnitName, NewInFile:string): boolean;
var
ProgramTermStart,ProgramTermEnd,
UsesStart,UsesEnd:integer;
begin
Result:=false;
// search Program section
ProgramTermStart:=SearchCodeInSource(Source.Source,'program',1,ProgramTermEnd
,false);
if ProgramTermStart<1 then exit;
// search programname
ReadNextPascalAtom(Source.Source,ProgramTermEnd,ProgramTermStart);
// search semicolon after programname
if not (ReadNextPascalAtom(Source.Source,ProgramTermEnd,ProgramTermStart)=';')
then exit;
UsesEnd:=ProgramTermEnd;
ReadNextPascalAtom(Source.Source,UsesEnd,UsesStart);
if UsesEnd>length(Source.Source) then exit;
if CompareText(copy(Source.Source,UsesStart,UsesEnd-UsesStart),'uses')<>0
then begin
// no uses section in interface -> add one
Source.Insert(ProgramTermEnd,LineEnding+LineEnding+'uses'+LineEnding+' ;');
UsesEnd:=ProgramTermEnd;
ReadNextPascalAtom(Source.Source,UsesEnd,UsesStart);
end;
if CompareText(copy(Source.Source,UsesStart,UsesEnd-UsesStart),'uses')<>0
then exit;
Result:=RenameUnitInUsesSection(Source,UsesStart,OldUnitName
,NewUnitName,NewInFile);
end;
function AddToProgramUsesSection(Source:TSourceLog;
const AUnitName,InFileName:string):boolean;
var
ProgramTermStart,ProgramTermEnd,
UsesStart,UsesEnd:integer;
begin
Result:=false;
if (AUnitName='') or (AUnitName=';') then exit;
// search program
ProgramTermStart:=SearchCodeInSource(Source.Source,'program',1,ProgramTermEnd
,false);
if ProgramTermStart<1 then exit;
// search programname
ReadNextPascalAtom(Source.Source,ProgramTermEnd,ProgramTermStart);
// search semicolon after programname
if not (ReadNextPascalAtom(Source.Source,ProgramTermEnd,ProgramTermStart)=';')
then exit;
// search uses section
UsesEnd:=ProgramTermEnd;
ReadNextPascalAtom(Source.Source,UsesEnd,UsesStart);
if UsesEnd>length(Source.Source) then exit;
if CompareText(copy(Source.Source,UsesStart,UsesEnd-UsesStart),'uses')<>0
then begin
// no uses section after program term -> add one
Source.Insert(ProgramTermEnd,LineEnding+LineEnding+'uses'+LineEnding+' ;');
UsesEnd:=ProgramTermEnd;
ReadNextPascalAtom(Source.Source,UsesEnd,UsesStart);
end;
if CompareText(copy(Source.Source,UsesStart,UsesEnd-UsesStart),'uses')<>0
then exit;
Result:=AddUnitToUsesSection(Source,AUnitName,InFileName,UsesStart);
end;
function RenameUnitInInterfaceUsesSection(Source:TSourceLog;
const OldUnitName, NewUnitName, NewInFile:string): boolean;
var
InterfaceStart,InterfaceWordEnd,
UsesStart,UsesEnd:integer;
begin
Result:=false;
// search interface section
InterfaceStart:=SearchCodeInSource(Source.Source,'interface',1
,InterfaceWordEnd,false);
if InterfaceStart<1 then exit;
UsesEnd:=InterfaceWordEnd;
ReadNextPascalAtom(Source.Source,UsesEnd,UsesStart);
if UsesEnd>length(Source.Source) then exit;
if CompareText(copy(Source.Source,UsesStart,UsesEnd-UsesStart),'uses')<>0
then begin
// no uses section in interface -> add one
Source.Insert(InterfaceWordEnd,LineEnding+LineEnding+'uses'+LineEnding+' ;');
UsesEnd:=InterfaceWordEnd;
ReadNextPascalAtom(Source.Source,UsesEnd,UsesStart);
end;
if CompareText(copy(Source.Source,UsesStart,UsesEnd-UsesStart),'uses')<>0
then exit;
Result:=RenameUnitInUsesSection(Source,UsesStart,OldUnitName
,NewUnitName,NewInFile);
end;
function AddToInterfaceUsesSection(Source:TSourceLog;
const AUnitName,InFileName:string):boolean;
var
InterfaceStart,InterfaceWordEnd,
UsesStart,UsesEnd:integer;
begin
Result:=false;
if AUnitName='' then exit;
// search interface section
InterfaceStart:=SearchCodeInSource(Source.Source,'interface',1
,InterfaceWordEnd,false);
if InterfaceStart<1 then exit;
UsesEnd:=InterfaceWordEnd;
ReadNextPascalAtom(Source.Source,UsesEnd,UsesStart);
if UsesEnd>length(Source.Source) then exit;
if CompareText(copy(Source.Source,UsesStart,UsesEnd-UsesStart),'uses')<>0
then begin
// no uses section in interface -> add one
Source.Insert(InterfaceWordEnd,LineEnding+LineEnding+'uses'+LineEnding+' ;');
UsesEnd:=InterfaceWordEnd;
ReadNextPascalAtom(Source.Source,UsesEnd,UsesStart);
end;
if CompareText(copy(Source.Source,UsesStart,UsesEnd-UsesStart),'uses')<>0
then exit;
Result:=AddUnitToUsesSection(Source,AUnitName,InFileName,UsesStart);
end;
function RemoveFromProgramUsesSection(Source:TSourceLog;
const AUnitName:string):boolean;
var
ProgramTermStart,ProgramTermEnd,
UsesStart,UsesEnd:integer;
Atom:string;
begin
Result:=false;
if AUnitName='' then exit;
// search program
ProgramTermStart:=SearchCodeInSource(Source.Source,'program',1
,ProgramTermEnd,false);
if ProgramtermStart<1 then exit;
// search programname
ReadNextPascalAtom(Source.Source,ProgramTermEnd,ProgramTermStart);
// search semicolon after programname
if not (ReadNextPascalAtom(Source.Source,ProgramTermEnd,ProgramTermStart)=';')
then exit;
UsesEnd:=ProgramTermEnd;
Atom:=ReadNextPascalAtom(Source.Source,UsesEnd,UsesStart);
if UsesEnd>length(Source.Source) then exit;
if CompareText(Atom,'uses')<>0 then exit;
Result:=RemoveUnitFromUsesSection(Source,AUnitName,UsesStart);