Menu

[327ada]: / Source / VCL / ClassBrowsing / CppPreprocessor.pas  Maximize  Restore  History

Download this file

1011 lines (892 with data), 33.9 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
{
This file is part of Dev-C++
Copyright (c) 2004 Bloodshed Software
Dev-C++ 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.
Dev-C++ 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 Dev-C++; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
}
unit CppPreprocessor;
interface
uses
{$IFDEF WIN32}
Windows, Classes, SysUtils, StrUtils, ComCtrls, Math, IntList, cbutils, CharUtils;
{$ENDIF}
{$IFDEF LINUX}
Classes, SysUtils, StrUtils, QComCtrls;
{$ENDIF}
type
PFile = ^TFile;
TFile = record
Index: integer; // 0-based for programming convenience
FileName: String;
Buffer: TStringList; // do not concat them all
end;
PDefine = ^TDefine;
TDefine = record
Name: String;
Args: String;
Value: String;
HardCoded: boolean; // if true, don't free memory (points to hard defines)
end;
TCppPreprocessor = class(TComponent)
private
fIndex: integer; // points to current file buffer. do not free
fFileName: String; // idem
fBuffer: TStringList; // idem
fResult: TStringList;
fCurrentIncludes: PFileIncludes;
fPreProcIndex: integer;
fIncludesList: TList;
fHardDefines: TStringList; // set by "cpp -dM -E -xc NUL"
fDefines: TStringList; // working set, editable
fIncludes: TList; // list of files we've stepped into. last one is current file, first one is source file
fBranchResults: TIntList;
// list of branch results (boolean). last one is current branch, first one is outermost branch
fIncludePaths: TStringList; // *pointer* to buffer of CppParser
fProjectIncludePaths: TStringList;
fScannedFiles: TStringList; // idem
fParseSystem: boolean;
fParseLocal: boolean;
procedure PreprocessBuffer;
procedure SkipToEndOfPreprocessor;
procedure SkipToPreprocessor;
function GetNextPreprocessor: String;
procedure Simplify(var Output: String);
procedure HandlePreprocessor(const Value: String);
procedure HandleDefine(const Line: String);
procedure HandleUndefine(const Line: String);
procedure HandleBranch(const Line: String);
procedure HandleInclude(const Line: String);
function ExpandMacros(const Line: String): String;
function RemoveSuffixes(const Input: String): String;
// current file stuff
function GetInclude(index: integer): PFile;
procedure OpenInclude(const FileName: String; Stream: TMemoryStream = nil);
property Includes[index: integer]: PFile read GetInclude; default;
procedure CloseInclude;
// branch stuff
function GetCurrentBranch: boolean;
procedure SetCurrentBranch(value: boolean);
procedure RemoveCurrentBranch;
function GetResult: String;
// include stuff
function GetFileIncludesEntry(const FileName: String): PFileIncludes;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AddDefineByParts(const Name, Args, Value: String; HardCoded: boolean);
procedure GetDefineParts(const Input: String; var Name, Args, Value: String);
procedure AddDefineByLine(const Line: String; HardCoded: boolean);
function GetDefine(const Name: String; var Index: integer): PDefine;
procedure Reset;
procedure ResetDefines;
procedure SetScanOptions(ParseSystem, ParseLocal: boolean);
procedure SetIncludePaths(var List: TStringList);
procedure SetProjectIncludePaths(var List: TStringList);
procedure SetScannedFileList(var List: TStringList);
procedure SetIncludesList(var List: TList);
procedure PreprocessStream(const FileName: String; Stream: TMemoryStream);
procedure PreprocessFile(const FileName: String);
property Result: String read GetResult;
end;
procedure Register;
implementation
uses IniFiles;
procedure Register;
begin
RegisterComponents('Dev-C++', [TCppPreprocessor]);
end;
constructor TCppPreprocessor.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fIncludes := TList.Create;
fHardDefines := TStringList.Create;
fDefines := TStringList.Create;
fDefines.Sorted := True;
fDefines.Duplicates := dupAccept; // duplicate defines should generate warning
fBranchResults := TIntList.Create;
fResult := TStringList.Create;
end;
destructor TCppPreprocessor.Destroy;
var
I: integer;
begin
for I := 0 to fIncludes.Count - 1 do begin
PFile(fIncludes[i])^.Buffer.Free;
Dispose(PFile(fIncludes[i]));
end;
fIncludes.Free;
for I := 0 to fHardDefines.Count - 1 do
Dispose(PDefine(fHardDefines.Objects[i]));
fHardDefines.Free;
for I := 0 to fDefines.Count - 1 do
if not PDefine(fDefines.Objects[i])^.HardCoded then // has already been released
Dispose(PDefine(fDefines.Objects[i]));
fDefines.Free;
fBranchResults.Free;
fResult.Free;
inherited Destroy;
end;
procedure TCppPreprocessor.Reset;
var
I: integer;
begin
fResult.Clear;
// Clear extracted data
for I := 0 to fIncludes.Count - 1 do begin
PFile(fIncludes[i])^.Buffer.Free;
Dispose(PFile(fIncludes[i]));
end;
fIncludes.Clear;
fBranchResults.Clear;
fCurrentIncludes := nil;
ResetDefines; // do not throw away hardcoded
end;
function TCppPreprocessor.GetInclude(index: integer): PFile;
begin
result := PFile(fIncludes[index]);
end;
procedure TCppPreprocessor.OpenInclude(const FileName: String; Stream: TMemoryStream = nil);
var
FileItem: PFile;
IsSystemFile: boolean;
IncludeLine: String;
I: integer;
begin
// Backup old position if we're entering a new file
if fIncludes.Count > 0 then
PFile(fIncludes[fIncludes.Count - 1])^.Index := fIndex;
// Add the new file to the includes of the current file
// Only add items to the include list of the given file if the file hasn't been scanned yet
// The above is fixed by checking for duplicates.
// The proper way would be to do backtracking of files we have FINISHED scanned.
// These are not the same files as the ones in fScannedFiles. We have STARTED scanning these.
if Assigned(fCurrentIncludes) then
with fCurrentIncludes^ do
if not ContainsText(IncludeFiles, FileName) then
IncludeFiles := IncludeFiles + AnsiQuotedStr(FileName, '"') + ',';
// Create and add new buffer/position
FileItem := new(PFile);
FileItem^.Index := 0; // 0-based line counter
FileItem^.FileName := FileName;
FileItem^.Buffer := TStringList.Create;
// Don't parse stuff we have already parsed
if Assigned(Stream) or (FastIndexOf(fScannedFiles, FileName) = -1) then begin
// Keep track of files we include here
// Only create new items for files we have NOT scanned yet
fCurrentIncludes := GetFileIncludesEntry(FileName);
if not Assigned(fCurrentIncludes) then begin // do NOT create a new item for a file that's already in the list
fCurrentIncludes := New(PFileIncludes);
fCurrentIncludes^.BaseFile := FileName;
fCurrentIncludes^.IncludeFiles := '';
fIncludesList.Add(fCurrentIncludes);
end;
// Parse ONCE
if not Assigned(Stream) then
fScannedFiles.Add(FileName);
// Only load up the file if we are allowed to parse it
IsSystemFile := cbutils.IsSystemHeaderFile(FileName, fIncludePaths);
if (fParseSystem and IsSystemFile) or (fParseLocal and not IsSystemFile) then begin
if Assigned(Stream) then begin
Stream.Position := 0; // start scanning from here
FileItem^.Buffer.LoadFromStream(Stream)
end else if FileExists(FileName) then
FileItem^.Buffer.LoadFromFile(FileName); // load it now
end;
end;
fIncludes.Add(FileItem);
// Process it
fIndex := FileItem^.Index;
fFileName := FileItem^.FileName;
fBuffer := FileItem^.Buffer;
// Trim all lines
for I := 0 to fBuffer.Count - 1 do
fBuffer[i] := Trim(fBuffer[i]);
// Update result file
IncludeLine := '#include ' + FileName + ':1';
if fIncludes.Count > 1 then // include from within a file
fResult[fPreProcIndex] := IncludeLine
else // new file
fResult.Add(IncludeLine);
end;
procedure TCppPreprocessor.CloseInclude;
begin
if fIncludes.Count > 0 then begin
// Close current buffer
PFile(fIncludes[fIncludes.Count - 1])^.Buffer.Free;
Dispose(PFile(fIncludes[fIncludes.Count - 1]));
fIncludes.Delete(fIncludes.Count - 1);
if fIncludes.Count > 0 then begin
// Continue where we left off
fIndex := Includes[fIncludes.Count - 1]^.Index;
fFileName := Includes[fIncludes.Count - 1]^.FileName;
fBuffer := Includes[fIncludes.Count - 1]^.Buffer;
// Point to previous buffer and start past the include we walked into
// Start augmenting previous include list again
fCurrentIncludes := GetFileIncludesEntry(fFileName);
// Update result file (we've left the previous file)
fResult.Add('#include ' + Includes[fIncludes.Count - 1]^.FileName + ':' + IntToStr(Includes[fIncludes.Count -
1]^.Index + 1));
end;
end;
end;
function TCppPreprocessor.GetCurrentBranch: boolean;
begin
if fBranchResults.Count > 0 then
Result := boolean(fBranchResults[fBranchResults.Count - 1])
else
Result := True;
end;
procedure TCppPreprocessor.SetCurrentBranch(value: boolean);
begin
fBranchResults.Add(integer(value));
end;
procedure TCppPreprocessor.RemoveCurrentBranch;
begin
if fBranchResults.Count > 0 then
fBranchResults.Delete(fBranchResults.Count - 1);
end;
procedure TCppPreprocessor.SetScanOptions(ParseSystem, ParseLocal: boolean);
begin
fParseSystem := ParseSystem;
fParseLocal := ParseLocal;
end;
procedure TCppPreprocessor.SetIncludesList(var List: TList);
begin
fIncludesList := List;
end;
procedure TCppPreprocessor.SetIncludePaths(var List: TStringList);
begin
fIncludePaths := List;
end;
procedure TCppPreprocessor.SetProjectIncludePaths(var List: TStringList);
begin
fProjectIncludePaths := List;
end;
procedure TCppPreprocessor.SetScannedFileList(var List: TStringList);
begin
fScannedFiles := List;
end;
procedure TCppPreprocessor.SkipToPreprocessor;
function FirstLineChar(const Line: String): Char;
begin
if Length(Line) > 0 then
Result := TrimLeft(Line)[1] // assume trimmed lines
else
Result := #0;
end;
begin
// Increment until a line begins with a #
while (fIndex < fBuffer.Count) and (FirstLineChar(fBuffer[fIndex]) <> '#') do begin
if GetCurrentBranch then // if not skipping, expand current macros
fResult.Add(ExpandMacros(fBuffer[fIndex]))
else // If skipping due to a failed branch, clear line
fResult.Add('');
Inc(fIndex);
end;
end;
procedure TCppPreprocessor.SkipToEndOfPreprocessor;
function LastLineChar(const Line: String): Char;
begin
if Length(Line) > 0 then
Result := Line[Length(Line)] // assume trimmed lines
else
Result := #0;
end;
begin
// Skip until last char of line is NOT \ anymore
while (fIndex < fBuffer.Count) and (LastLineChar(fBuffer[fIndex]) = '\') do begin
Inc(fIndex);
end;
end;
function TCppPreprocessor.GetNextPreprocessor: String;
var
I: integer;
PreProcFrom, PreProcTo: integer;
begin
Result := '';
SkipToPreprocessor; // skip until # at start of line
PreProcFrom := fIndex;
if PreProcFrom >= fBuffer.Count then // we've gone past the final #preprocessor line. Yay
Exit;
SkipToEndOfPreprocessor;
PreProcTo := fIndex;
// Calculate index to insert defines in in result file
fPreProcIndex := (fResult.Count - 1) + 1; // offset by one for #include rootfile
// Assemble whole line, including newlines
for I := PreProcFrom to PreProcTo do begin
Result := Result + fBuffer[i] + #13#10;
fResult.Add(''); // defines resolve into empty files, except #define and #include
end;
// Step over
Inc(fIndex);
end;
procedure TCppPreprocessor.Simplify(var Output: String);
var
DelimPosFrom, DelimPosTo: integer;
begin
// Remove #
Output := Copy(Output, 2, MaxInt);
// Remove newlines in concatenated expressions
Output := FastStringReplace(Output, '\'#13, '', [rfReplaceAll]);
Output := FastStringReplace(Output, '\'#10, '', [rfReplaceAll]);
Output := FastStringReplace(Output, #13, '', [rfReplaceAll]);
Output := FastStringReplace(Output, #10, '', [rfReplaceAll]);
// Remove C-style comments
while true do begin
DelimPosFrom := Pos('/*', Output);
if DelimPosFrom > 0 then begin
DelimPosTo := PosEx('*/', Output, DelimPosFrom);
if DelimPosTo > 0 then
Delete(Output, DelimPosFrom, DelimPosTo - DelimPosFrom + Length('*/'))
else
break; // invalid syntax. ignore
end else
break;
end;
// Don't remove multiple spaces. This can ruin defines which explicity use multiple spaces in their values
Output := Trim(Output); // removes spaces between # and the first word
end;
function TCppPreprocessor.GetDefine(const Name: String; var Index: integer): PDefine;
begin
Index := fDefines.IndexOf(Name); // use sorted searching. is really fast
if Index <> -1 then
Result := PDefine(fDefines.Objects[Index])
else
Result := nil;
end;
procedure TCppPreprocessor.AddDefineByParts(const Name, Args, Value: String; HardCoded: boolean);
var
Item: PDefine;
begin
// Do not check for duplicates. It's too slow
Item := new(PDefine);
Item^.Name := Name;
Item^.Args := Args;
Item^.Value := Value;
Item^.HardCoded := HardCoded;
if HardCoded then
fHardDefines.AddObject(Name, Pointer(Item)) // uses TStringList too to be able to assign to fDefines easily
else
fDefines.AddObject(Name, Pointer(Item)); // sort by name
end;
// input should omit the define word
procedure TCppPreprocessor.GetDefineParts(const Input: String; var Name, Args, Value: String);
var
I, Level, ArgStart: integer;
S: String;
IsFunction: boolean;
begin
S := TrimLeft(Input);
Name := '';
Args := '';
Value := '';
// Rules:
// When the character before the first opening brace is nonblank, a function is defined.
// After that point, switch from name to args
// The value starts after the first blank character outside of the outermost () pair
I := 1;
Level := 0;
IsFunction := False;
ArgStart := 0;
while I <= Length(S) do begin
// When we find the first opening brace, check if this is a function define
if S[i] = '(' then begin
Inc(Level);
if (Level = 1) and not IsFunction then begin // found a function define!
Name := Copy(S, 1, I - 1);
ArgStart := I;
IsFunction := True;
end;
end else if S[i] = ')' then begin
Dec(Level);
end else if (S[i] in SpaceChars) and (Level = 0) then
break; // found the end of our idenfifier
Inc(I);
end;
if IsFunction then begin
// Name has already been found
Args := Copy(S, ArgStart, I - ArgStart);
end else begin
Name := Trim(Copy(S, 1, I));
Args := '';
end;
Value := TrimLeft(Copy(S, I + 1, MaxInt));
end;
procedure TCppPreprocessor.AddDefineByLine(const Line: String; HardCoded: boolean);
var
Name, Args, Value, S: String;
begin
// Remove define
S := TrimLeft(Copy(Line, Length('define') + 1, MaxInt));
// Get parts from generalized function
GetDefineParts(S, Name, Args, Value);
// Add to the list
AddDefineByParts(Name, Args, Value, HardCoded);
end;
procedure TCppPreprocessor.ResetDefines;
var
I: integer;
begin
// Assign hard list to soft list
for I := 0 to fDefines.Count - 1 do begin // remove memory first
if not PDefine(fDefines.Objects[i])^.HardCoded then // memory belongs to hardcoded list
Dispose(PDefine(fDefines.Objects[i]));
end;
// Assign does clear too
fDefines.Duplicates := dupAccept;
fDefines.Sorted := False;
try
fDefines.Assign(fHardDefines); // then assign
finally
fDefines.Duplicates := dupAccept;
fDefines.Sorted := True; // sort once
end;
end;
procedure TCppPreprocessor.HandlePreprocessor(const Value: String);
begin
if StartsStr('define', Value) then
HandleDefine(Value)
else if StartsStr('undef', Value) then
HandleUndefine(Value)
else if StartsStr('if', Value) or StartsStr('else', Value) or StartsStr('elif', Value) or StartsStr('endif', Value)
then
HandleBranch(Value)
else if StartsStr('include', Value) then
HandleInclude(Value);
end;
procedure TCppPreprocessor.HandleDefine(const Line: String);
begin
if GetCurrentBranch then begin
AddDefineByLine(Line, false);
fResult[fPreProcIndex] := '#' + Line; // add define to result file so the parser can handle it
end;
end;
procedure TCppPreprocessor.HandleUndefine(const Line: String);
var
Define: PDefine;
Name: String;
Index: integer;
begin
// Remove undef
Name := TrimLeft(Copy(Line, Length('undef') + 1, MaxInt));
// Remove from soft list only
Define := GetDefine(Name, Index);
if Assigned(Define) then begin
if not Define^.HardCoded then // memory belongs to hardcoded list
Dispose(Define);
fDefines.Delete(Index);
end;
end;
procedure TCppPreprocessor.HandleBranch(const Line: String);
var
Name, IfLine: String;
OldResult: boolean;
I, Dummy: integer;
// Should start on top of the opening char
function SkipBraces(const Line: String; var Index: integer; Step: integer = 1): boolean;
var
Level: integer;
begin
Level := 0;
while (Index > 0) and (Index <= Length(Line)) do begin // Find the corresponding opening brace
if Line[Index] = '(' then begin
Inc(Level);
if Level = 0 then begin
Result := true;
Exit;
end;
end else if Line[Index] = ')' then begin
Dec(Level);
if Level = 0 then begin
Result := true;
Exit;
end;
end;
Inc(Index, Step);
end;
Result := false;
end;
// Expand any token that isn't a number
function ExpandDefines(Line: String): String;
var
SearchPos, Head, Tail, NameStart, NameEnd: integer;
Name, Args, InsertValue: String;
Define: PDefine;
function ExpandFunction(FunctionDefine: PDefine; const ArgValueString: String): String;
var
ArgNames, ArgValues: TStringList;
I: integer;
begin
// Replace function by this string
Result := FunctionDefine^.Value;
// Replace names by values...
ArgNames := TStringList.Create;
ArgValues := TStringList.Create;
try
ExtractStrings([',', '(', ')'], [], PChar(FunctionDefine^.Args), ArgNames);
ExtractStrings([',', '(', ')'], [], PChar(ArgValueString), ArgValues); // extract from Line string
// If the argument count matches up, replace names by values
if ArgNames.Count = ArgValues.Count then begin
for I := 0 to ArgNames.Count - 1 do
Result := StringReplace(Result, Trim(ArgNames[i]), Trim(ArgValues[i]), [rfReplaceAll]);
end;
finally
ArgNames.Free;
ArgValues.Free;
end;
end;
begin
SearchPos := 1;
while (SearchPos <= Length(Line)) do begin
// We have found an identifier. It is not a number suffix. Try to expand it
if (Line[SearchPos] in MacroIdentChars) and ((SearchPos = 1) or not (Line[SearchPos - 1] in DigitChars)) then begin
Tail := SearchPos;
Head := SearchPos;
// Get identifier name (numbers are allowed, but not at the start
while (Head <= Length(Line)) and ((Line[Head] in MacroIdentChars) or (Line[Head] in DigitChars)) do
Inc(Head);
Name := Copy(Line, Tail, Head - Tail);
NameStart := Tail;
NameEnd := Head;
// Skip over contents of these built-in functions
if Name = 'defined' then begin
Head := SearchPos + Length(Name);
while (Head <= Length(Line)) and (Line[Head] in SpaceChars) do
Inc(Head); // skip spaces
// Skip over its arguments
if SkipBraces(Line, Head) then begin
SearchPos := Head;
end else begin
Line := ''; // broken line
break;
end;
// We have found a logical operator. Skip over it
end else if (Name = 'and') or (Name = 'or') then begin
SearchPos := Head; // Skip logical operators
// We have found a regular define. Replace it by its value
end else begin
// Does it exist in the database?
Define := GetDefine(Name,Dummy);
if not Assigned(Define) then begin
InsertValue := '0';
end else begin
while (Head <= Length(Line)) and (Line[Head] in SpaceChars) do
Inc(Head); // skip spaces
// It is a function. Expand arguments
if (Head <= Length(Line)) and (Line[Head] = '(') then begin
Tail := Head;
if SkipBraces(Line, Head) then begin
Args := Copy(Line, Tail, Head - Tail + 1);
InsertValue := ExpandFunction(Define, Args);
NameEnd := Head + 1;
end else begin
Line := ''; // broken line
break;
end;
// Replace regular define
end else begin
if Define^.Value <> '' then
InsertValue := Define^.Value
else
InsertValue := '0';
end;
end;
// Insert found value at place
Delete(Line, NameStart, NameEnd - NameStart);
Insert(InsertValue, Line, SearchPos);
end;
end else
Inc(SearchPos);
end;
Result := Line;
end;
function EvaluateDefines(Line: String): String;
var
S: String;
I, Head, Tail: integer;
DefineResult, InvertResult: boolean;
begin
while true do begin
I := Pos('defined', Line);
if I > 0 then begin
// Check for boolean inverter
InvertResult := (I > 1) and (Line[I - 1] = '!');
// Find expression enclosed in () or after space
Tail := I + Length('defined'); // find (
// Skip spaces after defined keyword
while (Tail <= Length(Line)) and (Line[Tail] in SpaceChars) do
Inc(Tail);
// If we find an opening brace, find its closing brace
Head := Tail;
if (Head <= Length(Line)) and (Line[Head] = '(') then begin
if not SkipBraces(Line, Head) then begin
Result := '';
Exit;
end;
S := Copy(Line, Tail + 1, Head - Tail - 1);
// If we find an identifier, walk until it ends
end else begin
while (Head <= Length(Line)) and (Line[Head] in IdentChars) do // find end of identifier
Inc(Head);
S := Copy(Line, Tail, Head - Tail);
end;
// Delete expression from string
Tail := I;
if InvertResult then
Dec(Tail);
Delete(Line, Tail, Head - Tail + 1);
// Evaludate and replace expression by 1 or 0 (true or false)
DefineResult := Assigned(GetDefine(S,Dummy));
if (DefineResult and not InvertResult) or (not DefineResult and InvertResult) then
Insert('1', Line, Tail)
else
Insert('0', Line, Tail);
end else
break;
end;
Result := Line;
end;
function EvaluateExpression(Line: String): String;
var
Head, Tail, EquatStart, EquatEnd, OperatorPos: integer;
LeftOpValue, RightOpValue, ResultValue: Int64;
LeftOp, RightOp, OperatorToken, ResultLine: String;
function GetNextOperator(var Offset: integer): String;
var
I, PastOperatorEnd: integer;
begin
for I := Low(Operators) to High(Operators) do begin
Offset := Pos(Operators[i], Line);
// Is this operator present in the line?
if Offset > 0 then begin
// Aren't we misinterpreting && for & (for example)?
PastOperatorEnd := Offset + Length(Operators[i]);
if (PastOperatorEnd <= Length(Line)) and not (Line[PastOperatorEnd] in OperatorChars) then begin
Result := Operators[i];
Exit;
end;
end;
end;
Offset := 0;
Result := '';
end;
begin
// Find the first closing brace (this should leave us at the innermost brace pair)
while true do begin
Head := Pos(')', Line);
if Head > 0 then begin
Tail := Head;
if SkipBraces(Line, Tail, -1) then begin // find the corresponding opening brace
ResultLine := EvaluateExpression(Copy(Line, Tail + 1, Head - Tail - 1)); // evaluate this (without braces)
Delete(Line, Tail, Head - Tail + 1); // Remove the old part AND braces
Insert(ResultLine, Line, Tail); // and replace by result
end else begin
Result := '';
Exit;
end;
end else
break;
end;
// Then evaluate braceless part
while true do begin
OperatorToken := GetNextOperator(OperatorPos);
if OperatorPos > 0 then begin
// Get left operand
Tail := OperatorPos - 1;
while (Tail >= 0) and (Line[Tail] in SpaceChars) do
Dec(Tail); // skip spaces
Head := Tail;
while (Head >= 0) and (Line[Head] in IdentChars) do
Dec(Head); // step over identifier
LeftOp := Copy(Line, Head + 1, Tail - Head);
EquatStart := Head + 1; // marks begin of equation
// Get right operand
Tail := OperatorPos + Length(OperatorToken) + 1;
while (Tail <= Length(Line)) and (Line[Tail] in SpaceChars) do
Inc(Tail); // skip spaces
Head := Tail;
while (Head <= Length(Line)) and (Line[Head] in IdentChars) do
Inc(Head); // step over identifier
RightOp := Copy(Line, Tail, Head - Tail);
EquatEnd := Head; // marks begin of equation
// Evaluate after removing length suffixes...
LeftOpValue := StrToIntDef(RemoveSuffixes(LeftOp), 0);
RightOpValue := StrToIntDef(RemoveSuffixes(RightOp), 0);
if OperatorToken = '*' then
ResultValue := LeftOpValue * RightOpValue
else if OperatorToken = '/' then
ResultValue := LeftOpValue div RightOpValue // int division
else if OperatorToken = '+' then
ResultValue := LeftOpValue + RightOpValue
else if OperatorToken = '-' then
ResultValue := LeftOpValue - RightOpValue
else if OperatorToken = '<' then
ResultValue := integer(LeftOpValue < RightOpValue)
else if OperatorToken = '<=' then
ResultValue := integer(LeftOpValue <= RightOpValue)
else if OperatorToken = '>' then
ResultValue := integer(LeftOpValue > RightOpValue)
else if OperatorToken = '>=' then
ResultValue := integer(LeftOpValue >= RightOpValue)
else if OperatorToken = '==' then
ResultValue := integer(LeftOpValue = RightOpValue)
else if OperatorToken = '!=' then
ResultValue := integer(LeftOpValue <> RightOpValue)
else if OperatorToken = '&' then // bitwise and
ResultValue := integer(LeftOpValue and RightOpValue)
else if OperatorToken = '|' then // bitwise or
ResultValue := integer(LeftOpValue or RightOpValue)
else if OperatorToken = '^' then // bitwise xor
ResultValue := integer(LeftOpValue xor RightOpValue)
else if (OperatorToken = '&&') or (OperatorToken = 'and') then
ResultValue := integer(LeftOpValue and RightOpValue)
else if (OperatorToken = '||') or (OperatorToken = 'or') then
ResultValue := integer(LeftOpValue or RightOpValue)
else
ResultValue := 0;
// And replace by result in string form
Delete(Line, EquatStart, EquatEnd - EquatStart);
Insert(IntToStr(ResultValue), Line, EquatStart);
end else
break;
end;
Result := Line;
end;
function EvaluateIf(Line: String): boolean;
begin
Line := ExpandDefines(Line); // replace FOO by numerical value of FOO
Line := EvaluateDefines(Line); // replace all defined() by 1 or 0
Result := StrToIntDef(EvaluateExpression(Line), -1) > 0; // perform the remaining int arithmetic
end;
begin
if StartsStr('ifdef', Line) then begin
if not GetCurrentBranch then // we are already inside an if that is NOT being taken
SetCurrentBranch(false) // so don't take this one either
else begin
Name := TrimLeft(Copy(Line, Length('ifdef') + 1, MaxInt));
SetCurrentBranch(Assigned(GetDefine(Name,Dummy)));
end;
end else if StartsStr('ifndef', Line) then begin
if not GetCurrentBranch then // we are already inside an if that is NOT being taken
SetCurrentBranch(false) // so don't take this one either
else begin
Name := TrimLeft(Copy(Line, Length('ifndef') + 1, MaxInt));
SetCurrentBranch(not Assigned(GetDefine(Name,Dummy)));
end;
end else if StartsStr('if', Line) then begin
if not GetCurrentBranch then // we are already inside an if that is NOT being taken
SetCurrentBranch(false) // so don't take this one either
else begin
IfLine := TrimLeft(Copy(Line, Length('if') + 1, MaxInt)); // remove if
SetCurrentBranch(EvaluateIf(IfLine));
end;
end else if StartsStr('else', Line) then begin
// if a branch that is not at our level is false, ignore (that means we're skipping)
for I := 0 to fBranchResults.Count - 2 do
if fBranchResults[i] = 0 then // ignore it too
Exit;
// otherwise, process it
OldResult := GetCurrentBranch; // take either if or else
RemoveCurrentBranch;
SetCurrentBranch(not OldResult);
end else if StartsStr('elif', Line) then begin
// if a branch that is not at our level is false, ignore
for I := 0 to fBranchResults.Count - 2 do
if fBranchResults[i] = 0 then // ignore it too
Exit;
OldResult := GetCurrentBranch; // take either if or else
RemoveCurrentBranch;
if OldResult then begin // don't take this one, previous if has been taken
SetCurrentBranch(false);
end else begin // previous ifs failed. try this one
IfLine := TrimLeft(Copy(Line, Length('elif') + 1, MaxInt)); // remove elif
SetCurrentBranch(EvaluateIf(IfLine));
end;
end else if StartsStr('endif', Line) then
RemoveCurrentBranch;
end;
procedure TCppPreprocessor.HandleInclude(const Line: String);
var
FileName: String;
begin
if not GetCurrentBranch then // we're skipping due to a branch failure
Exit;
// Get full header file name
FileName := cbutils.GetHeaderFileName(Includes[fIncludes.Count - 1]^.FileName, Line, fIncludePaths,
fProjectIncludePaths);
// And open a new entry
OpenInclude(FileName);
end;
function TCppPreprocessor.ExpandMacros(const Line: String): String; // Too slow at the moment, so disabling.
begin
Result := Line;
end;
function TCppPreprocessor.RemoveSuffixes(const Input: String): String;
var
I: integer;
begin
Result := Input; // remove suffixes like L from integer values
if Length(Input) > 0 then begin
if not (Result[1] in DigitChars) then
Exit; // don't process names
I := Length(Result);
while (I >= 0) and CharInSet(Result[i], ['A'..'Z', 'a'..'z']) do // find first alphabetical character at end
Dec(I);
Delete(Result, I + 1, MaxInt); // remove from there
end;
end;
function TCppPreprocessor.GetFileIncludesEntry(const FileName: String): PFileIncludes;
var
I: integer;
begin
Result := nil;
for I := 0 to fIncludesList.Count - 1 do begin
if SameText(PFileIncludes(fIncludesList[I])^.BaseFile, Filename) then begin
Result := PFileIncludes(fIncludesList[I]);
Exit;
end;
end;
end;
procedure TCppPreprocessor.PreprocessBuffer;
var
S: String;
begin
while fIncludes.Count > 0 do begin
repeat
S := GetNextPreprocessor;
if StartsStr('#', S) then begin
Simplify(S);
if S <> '' then
HandlePreprocessor(S);
end;
until S = '';
CloseInclude;
end;
end;
procedure TCppPreprocessor.PreprocessStream(const FileName: String; Stream: TMemoryStream);
begin
Reset;
OpenInclude(FileName, Stream);
PreprocessBuffer;
end;
procedure TCppPreprocessor.PreprocessFile(const FileName: String);
begin
Reset;
OpenInclude(FileName, nil);
PreprocessBuffer;
//fResult.SaveToFile('C:\TCppPreprocessorResult' + ExtractFileName(FileName) + '.txt');
end;
function TCppPreprocessor.GetResult: String;
begin
Result := fResult.Text; // sloooow
end;
end.
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.