forked from jrsoftware/issrc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIsppPreprocessor.pas
1865 lines (1719 loc) · 53.1 KB
/
IsppPreprocessor.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{
Inno Setup Preprocessor
Copyright (C) 2001-2002 Alex Yackimoff
Inno Setup
Copyright (C) 1997-2020 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
}
unit IsppPreprocessor;
interface
uses Windows, SysUtils, Classes, CompPreprocInt, IniFiles, Registry, IsppIntf,
IsppBase, IsppStack, IsppIdentMan, IsppParser;
{$I ..\Version.inc}
type
TPreprocessor = class;
EPreprocError = class(Exception)
FileName: string;
LineNumber: Integer;
ColumnNumber: Integer;
constructor Create(Preproc: TPreprocessor; const Msg: string);
end;
TConditionalBlockInfo = packed record
BlockState, Fired, HadElse, Reserved: Boolean;
end;
TConditionalVerboseMsg = (cvmIf, cvmElif, cvmElse, cvmEndif);
TConditionalTranslationStack = class(TStack)
private
FPreproc: TPreprocessor;
FCache: Boolean;
FCacheValid: Boolean;
procedure VerboseMsg(Msg: TConditionalVerboseMsg; Eval: Boolean);
protected
function Last: TConditionalBlockInfo;
procedure UpdateLast(const Value: TConditionalBlockInfo);
public
constructor Create(Preproc: TPreprocessor);
procedure IfInstruction(Eval: Boolean);
procedure ElseIfInstruction(Eval: Boolean);
procedure ElseInstruction;
procedure EndIfInstruction;
function Include: Boolean;
procedure Resolved;
end;
TPreprocessorCommand = (pcError, pcIf, pcIfDef, pcIfNDef, pcIfExist,
pcIfNExist, pcElseIf, pcElse, pcEndIf, pcDefine, pcUndef, pcInclude,
pcErrorDir, pcPragma, pcLine, pcImport, pcPrint, pcPrintEnv, pcFile,
pcExecute, pcGlue, pcEndGlue, pcDim, pcProcedure, pcEndProc, pcEndLoop,
pcFor, pcReDim);
TDropGarbageProc = procedure(Item: Pointer);
TIsppMessageType = (imtStatus, imtWarning);
TPreprocessor = class(TObject, IIdentManager)
private
FCompilerParams: TPreprocessScriptParams;
FCompilerPath: string;
FCounter: Integer;
FCurrentFile: Word;
FCurrentLine: Word;
FDefaultScope: TDefineScope;
FFileStack: TStringList; { strs: files being included }
FIncludes: TStringList; { strs: files been included, for error msgs }
FIncludePath: string;
FInsertionPoint: Integer;
FLinePointer: Integer;
FMainCounter: Word;
FOutput: TStringList; { strs: translation }
FQueuedLine: string;
FQueuedLineCount: Integer;
FSourcePath: string;
FStack: TConditionalTranslationStack;
FIdentManager: TIdentManager;
FInProcBody: Boolean;
FInForBody: Boolean;
FProcs: TStringList;
FGarbageCollection: TList;
procedure DropGarbage;
function ProcessInlineDirectives(P: PChar): string;
function ProcessPreprocCommand(Command: TPreprocessorCommand;
var Params: string; ParamsOffset: Integer): Boolean;
procedure PushFile(const FileName: string);
procedure PopFile;
function CheckFile(const FileName: string): Boolean;
function EmitDestination: TStringList;
procedure SendMsg(Msg: string; Typ: TIsppMessageType);
function GetFileName(Code: Integer): string;
function GetLineNumber(Code: Integer): Word;
procedure RaiseErrorEx(const Message: string; Column: Integer);
procedure ExecProc(Body: TStrings);
protected
function GetDefaultScope: TDefineScope;
procedure SetDefaultScope(Scope: TDefineScope);
procedure InternalAddLine(const LineRead: string; FileIndex, LineNo: Word;
NonISS: Boolean);
function InternalQueueLine(const LineRead: string; FileIndex, LineNo: Word;
NonISS: Boolean): Integer;
function ParseFormalParams(Parser: TParser; var ParamList: PParamList): Integer;
{ IUnknown }
function QueryInterface(const IID: TGUID; out Obj): HRESULT; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
{ IIdentManager }
function LookupPredefined(Name: string; Value: PIsppVariant): Boolean;
function Defined(const Name: String): Boolean;
function GetIdent(const Name: String;
out CallContext: ICallContext): TIdentType;
function TypeOf(const Name: String): Byte;
function DimOf(const Name: String): Integer;
public
FOptions: TISPPOptions;
constructor Create(const CompilerParams: TPreprocessScriptParams;
VarManager: TIdentManager; const Options: TIsppOptions;
const SourcePath: string; const CompilerPath: string; const FileName: string = '');
destructor Destroy; override;
procedure VerboseMsg(Level: Byte; const Msg: string; const Args: array of const);
procedure StatusMsg(const Msg: string; const Args: array of const);
procedure WarningMsg(const Msg: string; const Args: array of const);
function GetNextOutputLine(var LineFilename: string; var LineNumber: Integer;
var LineText: string): Boolean;
procedure GetNextOutputLineReset;
procedure IncludeFile(FileName: string; Builtins, UseIncludePathOnly, ResetCurrentFile: Boolean);
procedure QueueLine(const LineRead: string);
function PrependDirName(const FileName, Dir: string): string;
procedure RegisterFunction(const Name: string; Handler: TIsppFunction; Ext: Longint);
procedure RaiseError(const Message: string);
procedure SaveToFile(const FileName: string);
procedure CollectGarbage(Item: Pointer; Proc: TDropGarbageProc);
procedure UncollectGarbage(Item: Pointer);
property IncludedFiles: TStringList read FIncludes;
property IncludePath: string read FIncludePath write FIncludePath;
property SourcePath: string read FSourcePath;
property StringList: TStringList read FOutput;
property Stack: TConditionalTranslationStack read FStack;
property VarMan: TIdentManager read FIdentManager;
end;
implementation
uses IsppConsts, IsppFuncs, IsppVarUtils, IsppSessions, CTokenizer, PathFunc,
CmnFunc2, FileClass, Struct;
const
PreprocCommands: array[TPreprocessorCommand] of String =
('', 'if', 'ifdef', 'ifndef', 'ifexist', 'ifnexist', 'elif', 'else',
'endif', 'define', 'undef', 'include', 'error', 'pragma', 'line', 'import',
'emit', 'env', 'file', 'expr', 'insert', 'append', 'dim', 'sub', 'endsub',
'endloop', 'for', 'redim');
PpCmdSynonyms: array[TPreprocessorCommand] of Char =
(#0, '?', #0, #0, #0, #0, #0, '^', '.', ':', #0, '+', #0, #0, #0, #0,
'=', '%', #0, '!', #0, #0, #0, #0, #0, #0, #0, #0);
function GetEnv(const EnvVar: String): String;
function AdjustLength(var S: String; const Res: Cardinal): Boolean;
begin
Result := Integer(Res) < Length(S);
SetLength (S, Res);
end;
var
Res: DWORD;
begin
SetLength(Result, 255);
repeat
Res := GetEnvironmentVariable(PChar(EnvVar), PChar(Result), Length(Result));
if Res = 0 then begin
Result := '';
Break;
end;
until AdjustLength(Result, Res);
end;
function ParsePreprocCommand(var P: PChar; ExtraTerminator: Char): TPreprocessorCommand;
begin
for Result := TPreprocessorCommand(1) to High(TPreprocessorCommand) do
begin
if (P^ = PpCmdSynonyms[Result]) then
Inc(P)
else if (StrLIComp(P, @PreprocCommands[Result][1], Length(PreprocCommands[Result])) = 0) and
CharInSet(P[Length(PreprocCommands[Result])], [#0..#32, ExtraTerminator]) then
Inc(P, Length(PreprocCommands[Result]))
else
Continue;
Exit;
end;
if StrLIComp('echo', P, 4) = 0 then
begin
Result := pcPrint;
Inc(P, 4)
end
else if StrLIComp('call', P, 4) = 0 then
begin
Result := pcExecute;
Inc(P, 4);
end
else
Result := pcError;
end;
{ EPreprocError }
constructor EPreprocError.Create(Preproc: TPreprocessor; const Msg: string);
begin
inherited Create(Msg + '.');
FileName := Preproc.GetFileName(-1);
LineNumber := Preproc.GetLineNumber(-1);
end;
{ TPreprocessor }
function CheckReservedIdent(const Ident: string): string;
begin
Result := UpperCase(Ident);
if (Result = SLocal) or
(Result = SGlobal) or
(Result = SInt) or
(Result = SStr) or
(Result = SAny) then
raise EParsingError.CreateFmt(SExpectedButFound, [SIdent, '''' + Result + '''']);
Result := Ident;
end;
constructor TPreprocessor.Create(const CompilerParams: TPreprocessScriptParams;
VarManager: TIdentManager; const Options: TIsppOptions;
const SourcePath, CompilerPath, FileName: string);
begin
PushPreproc(Self);
if VarManager = nil then
FIdentManager := TIdentManager.Create(Self, Longint(Self))
else
FIdentManager := VarManager;
FOptions := Options;
FIdentManager._AddRef;
FIdentManager.BeginLocal;
FCompilerParams := CompilerParams;
FCompilerPath := CompilerPath;
FSourcePath := SourcePath;
FFileStack := TStringList.Create;
FIncludes := TStringList.Create;
FIncludes.Add(FileName); //main file - no name
FInsertionPoint := -1;
FOutput := TStringList.Create;
FProcs := TStringList.Create;
FStack := TConditionalTranslationStack.Create(Self);
if VarManager = nil then IsppFuncs.RegisterFunctions(Self);
end;
destructor TPreprocessor.Destroy;
begin
DropGarbage;
if PopPreproc <> Self then
RaiseError('Internal error: FSP');
FStack.Free;
FProcs.Free;
FOutput.Free;
FIncludes.Free;
if FFileStack.Count <> 0 then
RaiseError('Internal error: FNE');
FFileStack.Free;
FIdentManager.EndLocal;
FIdentManager._Release;
end;
function TPreprocessor.GetFileName(Code: Integer): string;
begin
if Code = -1 then
Result := FIncludes[FCurrentFile]
else
Result := FIncludes[Longint(FOutput.Objects[Code]) shr 16];
end;
function TPreprocessor.GetLineNumber(Code: Integer): Word;
begin
if Code = -1 then
Result := FCurrentLine
else
Result := Word(FOutput.Objects[Code]) and $FFFF
end;
function TPreprocessor.GetNextOutputLine(var LineFilename: string; var LineNumber: Integer;
var LineText: string): Boolean;
begin
Result := False;
if FLinePointer < FOutput.Count then
begin
LineFilename := GetFileName(FLinePointer);
LineNumber := GetLineNumber(FLinePointer);
LineText := FOutput[FLinePointer];
Inc(FLinePointer);
Result := True;
end;
end;
procedure TPreprocessor.GetNextOutputLineReset;
begin
FLinePointer := 0;
end;
procedure TPreprocessor.InternalAddLine(const LineRead: string; FileIndex, LineNo: Word;
NonISS: Boolean);
var
IncludeLine: Boolean;
P, P1: PChar;
Command: TPreprocessorCommand;
DirectiveOffset: Integer;
State: Boolean;
S, S1: string;
begin
try
Inc(LineNo);
FCurrentFile := FileIndex;
FCurrentLine := LineNo;
P := PChar(LineRead);
IncludeLine := True;
if P^ <> #0 then
begin
P1 := P;
while CharInSet(P^, [#1..#32]) do Inc(P);
if P^ = '#' then
begin
Inc(P);
while CharInSet(P^, [#1..#32]) do Inc(P);
IncludeLine := FInProcBody;
Command := ParsePreprocCommand(P, #0);
if FInProcBody then
begin
case Command of
pcError: RaiseError(SUnknownPreprocessorDirective);
pcProcedure: RaiseError('Nested procedure declaration not allowed');
pcEndProc:
begin
S := P;
ProcessPreprocCommand(Command, S, P - P1);
IncludeLine := False;
end
else
S := LineRead;
end;
end
else
begin
State := FStack.Include;
DirectiveOffset := P - P1;
//S := Copy(LineRead, DirectiveOffset + 1, MaxInt);
S := P;
case Command of
pcIf..pcIfNExist:
FStack.IfInstruction(FStack.Include and
ProcessPreprocCommand(Command, S, DirectiveOffset));
pcElseIf:
FStack.ElseIfInstruction(FStack.Last.Fired or
(FStack.Include or not FStack.Last.BlockState) and
ProcessPreprocCommand(Command, S, DirectiveOffset));
pcElse: FStack.ElseInstruction;
pcEndIf: FStack.EndIfInstruction
else
if State then
case Command of
pcPrint, pcPrintEnv:
begin
ProcessPreprocCommand(Command, S, DirectiveOffset);
VerboseMsg(8, SLineEmitted, [S]);
IncludeLine := True
end;
pcFile: RaiseError(SFileDirectiveCanBeOnlyInline);
else
ProcessPreprocCommand(Command, S, DirectiveOffset);
end;
end
end;
end
else
if not FInProcBody and not FStack.Include then
IncludeLine := False
else
if ((P^ = '/') and (P[1] = '/')) or
((P^ = #0) and not (optEmitEmptyLines in FOptions.Options)) then //P^ is #0 if the line was all whitespace
IncludeLine := False
else
if (P^ <> #0) and (P^ <> ';') and not FInProcBody then
S := PChar(ProcessInlineDirectives(P1))
else
S := P1;
end
else
begin
S := '';
IncludeLine := optEmitEmptyLines in FOptions.Options
end;
if IncludeLine then
begin
P := PChar(S);
repeat
P1 := P;
while not CharInSet(P^, [#0, #10, #13]) do Inc(P);
SetString(S1, P1, P - P1);
if FInsertionPoint >= 0 then
begin
EmitDestination.InsertObject(FInsertionPoint, S1,
TObject(FileIndex shl 16 or LineNo));
Inc(FInsertionPoint);
end
else
EmitDestination.AddObject(S1, TObject(FileIndex shl 16 or LineNo));
while CharInSet(P^, [#10, #13]) do Inc(P);
until P^ = #0;
end;
except
on E: EParsingError do
RaiseErrorEx(E.Message, E.Position);
on E: EPreprocError do
raise;
on E: Exception do
RaiseError(E.Message);
end;
end;
function TPreprocessor.ProcessInlineDirectives(P: PChar): string;
var
S: string;
Command: TPreprocessorCommand;
LineStack: TConditionalTranslationStack;
LineStart, P1, DStart, DEnd: PChar;
function ScanForInlineStart(var P, D: PChar): Boolean;
var
I: Integer;
begin
Result := False;
while P^ <> #0 do
begin
if AnsiChar(P^) = FOptions.InlineStart[1] then
begin
D := P;
Result := True;
for I := 2 to Byte(FOptions.InlineStart[0]) do
begin
Inc(D);
if AnsiChar(D^) <> FOptions.InlineStart[I] then
begin
Result := False;
Break;
end;
end;
Inc(D);
end;
if Result then Break;
Inc(P);
end;
end;
function ScanForInlineEnd(var P: PChar): PChar;
var
I: Integer;
begin
Result := nil;
while P^ <> #0 do
begin
if AnsiChar(P^) = FOptions.InlineEnd[1] then
begin
Result := P;
for I := 2 to Byte(FOptions.InlineEnd[0]) do
begin
Inc(P);
if AnsiChar(P^) <> FOptions.InlineEnd[I] then
begin
Result := nil;
Break;
end;
end;
Inc(P);
end;
if Result <> nil then Exit;
Inc(P);
end;
RaiseError(SUnterminatedPreprocessorDirectiv);
end;
begin
LineStack := TConditionalTranslationStack.Create(Self);
try
Result := '';
LineStart := P;
P1 := P;
while ScanForInlineStart(P, DStart) do
begin
SetString(S, P1, P - P1);
if LineStack.Include then Result := Result + S;
Command := ParsePreprocCommand(DStart, Char(FOptions.InlineEnd[1]));
if Command = pcError then
Command := pcPrint;
DEnd := DStart;
SetString(S, DStart, ScanForInlineEnd(DEnd) - DStart);
case Command of
pcError: RaiseError(SUnknownPreprocessorDirective);
pcIf..pcIfNExist:
LineStack.IfInstruction(LineStack.Include and
ProcessPreprocCommand(Command, S, DStart - LineStart));
pcElseIf:
LineStack.ElseIfInstruction(LineStack.Last.Fired or
(LineStack.Include or not LineStack.Last.BlockState) and
ProcessPreprocCommand(Command, S, DStart - LineStart));
pcElse: LineStack.ElseInstruction;
pcEndIf: LineStack.EndIfInstruction;
else
if LineStack.Include then
case Command of
pcInclude, pcGlue..pcEndLoop:
RaiseError(Format(SDirectiveCannotBeInline,
[PreprocCommands[Command]]));
pcPrint, pcPrintEnv, pcFile:
begin
ProcessPreprocCommand(Command, S, DStart - LineStart);
Result := Result + S;
end;
else
ProcessPreprocCommand(Command, S, DStart - LineStart)
end;
end;
P1 := DEnd;
P := DEnd;
//Inc(P);
end;
Result := Result + P1;
LineStack.Resolved;
finally
LineStack.Free
end;
end;
function TPreprocessor.GetDefaultScope: TDefineScope;
begin
if FFileStack.Count > 0 then
Result := TDefineScope(FFileStack.Objects[FFileStack.Count - 1])
else
Result := FDefaultScope;
end;
procedure TPreprocessor.SetDefaultScope(Scope: TDefineScope);
begin
if Scope = dsAny then Scope := dsPublic;
if FFileStack.Count > 0 then
FFileStack.Objects[FFileStack.Count - 1] := TObject(Scope)
else
FDefaultScope := Scope;
end;
type
TParserAccess = class(TParser);
function TPreprocessor.ProcessPreprocCommand(Command: TPreprocessorCommand;
var Params: string; ParamsOffset: Integer): Boolean;
function ParseScope(Parser: TParser; ExpectedTokens: TTokenKinds = [tkIdent]): TDefineScope;
const
ScopeClauses: array[dsPublic..dsPrivate] of string =
('public', 'protected', 'private');
begin
Parser.NextTokenExpect([tkIdent]);
for Result := Low(ScopeClauses) to High(ScopeClauses) do
if CompareText(Parser.TokenString, ScopeClauses[Result]) = 0 then
begin
Parser.NextTokenExpect(ExpectedTokens);
Exit;
end;
Result := dsAny;
end;
function GetScope(Parser: TParser): TDefineScope;
begin
Result := ParseScope(Parser);
if Result = dsAny then Result := GetDefaultScope;
end;
procedure ParseDim(Parser: TParserAccess; ReDim: Boolean);
var
Name: string;
N, NValues, I: Integer;
Scope: TDefineScope;
Values: array of TIsppVariant;
begin
with Parser do
try
Scope := GetScope(Parser);
Name := CheckReservedIdent(TokenString);
NextTokenExpect([tkOpenBracket]);
N := IntExpr(True);
NValues := 0;
NextTokenExpect([tkCloseBracket]);
if PeekAtNextToken = tkOpenBrace then
begin
NextToken;
SetLength(Values, N);
NValues := 0;
while True do begin
if NValues >= N then
raise EIdentError.CreateFmt(SIndexIsOutOfArraySize, [NValues, Name]);
Values[NValues] := Expr(True);
MakeRValue(Values[NValues]);
Inc(NValues);
if PeekAtNextToken <> tkComma then
Break;
NextToken;
end;
NextTokenExpect([tkCloseBrace]);
end;
FIdentManager.DimVariable(Name, N, Scope, ReDim);
if ReDim and (NValues <> 0) then
Error('Initializers not allowed on #redim of existing array');
for I := 0 to NValues-1 do
FIdentManager.DefineVariable(Name, I, Values[I], Scope);
finally
//Free
end;
end;
procedure ParseDefine(Parser: TParserAccess);
var
Name: string;
Start, P: PChar;
IsMacroDefine: Boolean;
//Ident: string;
//Param: TIsppMacroParam;
ParamList: PParamList;
AParamCount: Byte;
AExpr: string;
VarIndex: Integer;
Scope: TDefineScope;
MacroExprPos: TExprPosition;
begin
with Parser do
begin
Start := FExpr;
Scope := ParseScope(Parser, [tkEOF, tkIdent, tkSemicolon]);
if Scope = dsAny then
Scope := GetDefaultScope
else
if Token <> tkIdent then
begin
SetDefaultScope(Scope);
Exit;
end;
Name := CheckReservedIdent(TokenString);
IsMacroDefine := FExpr^ = '(';
if IsMacroDefine then
begin
NextToken;
AParamCount := ParseFormalParams(Parser, ParamList);
try
Inc(FExpr);
P := FExpr;
MacroExprPos.FileIndex := FCurrentFile;
MacroExprPos.Line := FCurrentLine;
MacroExprPos.Column := (FExpr - Start) + ParamsOffset;
while P^ <> #0 do Inc(P);
SetString(AExpr, FExpr, P - FExpr);
AExpr := Trim(AExpr);
if AExpr = '' then RaiseError(SMacroExpressionExpected);
FIdentManager.DefineMacro(Name, AExpr, MacroExprPos, FOptions.ParserOptions,
Slice(ParamList^, AParamCount), Scope);
finally
Finalize(ParamList^[0], AParamCount);
FreeMem(ParamList)
end;
end
else
begin
VarIndex := -1;
if PeekAtNextToken = tkOpenBracket then
begin
NextToken;
VarIndex := IntExpr(True);
NextTokenExpect([tkCloseBracket]);
end;
case PeekAtNextToken of
opAssign: NextToken;
tkEOF:
begin
FIdentManager.DefineVariable(Name, VarIndex, NULL, Scope);
Exit;
end
end;
FIdentManager.DefineVariable(Name, VarIndex, Evaluate, Scope);
end;
end;
end;
procedure ParseUndef(Parser: TParserAccess);
var
Scope: TDefineScope;
begin
with Parser do
begin
Scope := GetScope(Parser);
FIdentManager.Delete(CheckReservedIdent(TokenString), Scope);
EndOfExpr;
end
end;
procedure IncludeFile(const Params: string);
var
FileName: string;
function TryPascal: Boolean;
begin
Result := not (optPascalStrings in FOptions.ParserOptions.Options);
if Result then
begin
Include(FOptions.ParserOptions.Options, optPascalStrings);
try
try
FileName := ParseStr(Self, Params, ParamsOffset,
@FOptions.ParserOptions);
except
Result := False
end;
finally
Exclude(FOptions.ParserOptions.Options, optPascalStrings);
end;
end
end;
var
IncludePathOnly: Boolean;
begin
FileName := Params;
if Pos(';', FileName) > 0 then
Delete(FileName, Pos(';', FileName), MaxInt);
FileName := Trim(FileName);
if (FileName <> '') and (FileName[1] = '<') and
(FileName[Length(FileName)] = '>') then
begin
FileName := Copy(FileName, 2, Length(FileName) - 2);
IncludePathOnly := True;
end
else
begin
try
FileName := ParseStr(Self, Params, ParamsOffset, @FOptions.ParserOptions);
except
if not TryPascal then
raise
end;
IncludePathOnly := False;
end;
Self.IncludeFile(FileName, False, IncludePathOnly, False);
end;
procedure Pragma(Parser: TParserAccess);
var
P: string;
function StrPragma(AllowEmpty: Boolean): string;
begin
Result := Parser.StrExpr(True);
if (Result = '') and not AllowEmpty then
RaiseError(SNonEmptyStringExpected);
Parser.EndOfExpr;
end;
procedure OptionPragma(var Options: TOptions);
var
C: Char;
V: Boolean;
begin
with Parser do
begin
NextTokenExpect([opSubtract]);
repeat
NextTokenExpect([tkIdent]);
if Length(TokenString) > 1 then
RaiseError(SInvalidOptionName);
C := TokenString[1];
V := NextTokenExpect([opAdd, opSubtract]) = opAdd;
SetOption(Options, C, V);
until NextTokenExpect([tkEOF, opSubtract, tkSemicolon]) <> opSubtract;
end;
end;
var
CatchException: Boolean;
ErrorMsg: string;
begin
CatchException := True;
try
with Parser do
begin
NextTokenExpect([tkIdent]);
P := LowerCase(TokenString);
if P = 'include' then
FIncludePath := StrPragma(True)
else if P = 'inlinestart' then
FOptions.InlineStart := AnsiString(StrPragma(False))
else if P = 'inlineend' then
FOptions.InlineEnd := AnsiString(StrPragma(False))
else if P = 'spansymbol' then
FOptions.SpanSymbol := AnsiChar(StrPragma(False)[1])
else if P = 'parseroption' then
OptionPragma(FOptions.ParserOptions.Options)
else if P = 'option' then
OptionPragma(FOptions.Options)
else if P = 'verboselevel' then
begin
Include(FOptions.Options, optVerbose);
FOptions.VerboseLevel := IntExpr(True);
VerboseMsg(0, SChangedVerboseLevel, [FOptions.VerboseLevel]);
EndOfExpr;
end
else if P = 'warning' then begin
{ Also see WarningFunc in IsppFuncs }
WarningMsg(StrPragma(True), [])
end else if P = 'message' then begin
{ Also see MessageFunc in IsppFuncs }
StatusMsg(StrPragma(True), [])
end else if P = 'error' then begin
{ Also see ErrorFunc in IsppFuncs }
ErrorMsg := StrPragma(True);
if ErrorMsg = '' then ErrorMsg := 'Error';
CatchException := False;
RaiseError(ErrorMsg)
end
else
WarningMsg(SFailedToParsePragmaDirective, []);
end;
except
if CatchException then
WarningMsg(SFailedToParsePragmaDirective, [])
else
raise
end;
end;
function DoFile(FileName: string): string;
function GetTempFileName(const Original: string): string;
var
Path: string;
begin
SetLength(Path, MAX_PATH);
SetLength(Path, GetTempPath(MAX_PATH, PChar(Path)));
SetLength(Result, MAX_PATH);
if Windows.GetTempFileName(PChar(Path), PChar(UpperCase(Original)), 0, PChar(Result)) <> 0 then
SetLength(Result, StrLen(PChar(Result)))
else
{$IFDEF IS_D7}
RaiseLastOSError
{$ELSE}
RaiseLastWin32Error;
{$ENDIF}
end;
var
F: TTextFileReader;
ALine: string;
Preprocessor: TPreprocessor;
NewOptions: TIsppOptions;
begin
FileName := PrependDirName(FileName, FSourcePath);
if FileExists(FileName) then
begin
Result := GetTempFileName(ExtractFileName(FileName));
StatusMsg(SProcessingExternalFile, [FileName]);
NewOptions := FOptions;
Preprocessor := TPreprocessor.Create(FCompilerParams, FIdentManager,
NewOptions, FSourcePath, FCompilerPath, FileName);
try
F := TTextFileReader.Create(Filename, fdOpenExisting, faRead, fsRead);
try
while not F.Eof do begin
ALine := F.ReadLine;
Preprocessor.QueueLine(ALine);
end;
finally
F.Free;
end;
Preprocessor.SaveToFile(Result);
QueueFileForDeletion(Result);
VerboseMsg(1, STemporaryFileCreated, [Result]);
finally
Preprocessor.Free;
end;
end
else
RaiseError(Format(SFileNotFound, [FileName]));
end;
procedure ParseFor(Parser: TParserAccess);
var
Condition, Action, Body: PChar;
begin
Parser.NextTokenExpect([tkOpenBrace]);
Parser.Expr(False);
Parser.NextTokenExpect([tkSemicolon]);
{ Skip condition and remember it }
Condition := Parser.FExpr;
Parser.Sequentional(False);
Parser.NextTokenExpect([tkSemicolon]);
Action := Parser.FExpr;
Parser.Sequentional(False);
Parser.NextTokenExpect([tkCloseBrace]);
Body := Parser.FExpr;
Parser.Sequentional(False);
Parser.EndOfExpr;
Parser.SetPos(Condition);
while Parser.IntExpr(False) <> 0 do
begin
Parser.SetPos(Body);
Parser.Sequentional(True);
Parser.SetPos(Action);
Parser.Sequentional(True);
Parser.SetPos(Condition);
end;
end;
procedure Glue(LineNo: Integer);
begin
if LineNo > FOutput.Count then
RaiseError(Format(SInsertLineNoTooBig, [LineNo]));
FInsertionPoint := LineNo;
VerboseMsg(2, SChangingInsertionPointToLine, [FInsertionPoint]);
end;
procedure EndGlue;
begin
VerboseMsg(2, SResettingInsertionPoint, []);
FInsertionPoint := -1;
end;
procedure BeginProcDecl(Parser: TParserAccess);
var
ProcName: string;
begin
if FInForBody or FInProcBody then
RaiseError('Nested procedure declaration and compound loops not allowed');
FInProcBody := True;
Parser.NextTokenExpect([tkIdent]);
ProcName := Parser.TokenString;
Parser.EndOfExpr;
FProcs.AddObject(ProcName, TStringList.Create);
EmitDestination.Add('#define private');
end;
procedure EndProcDecl;
begin
if not FInProcBody then
RaiseError('''endproc'' without ''procedure''');
FInProcBody := False;
end;
var
IfCondition: TIsppVariant;
DummyContext: ICallContext;
Parser: TParserAccess;
begin
Result := False;
Parser := TParserAccess.Create(Self, Params, ParamsOffset, @FOptions.ParserOptions);
with Parser do
try
case Command of
pcError: RaiseError(SUnknownPreprocessorDirective);
pcIf, pcElseIf:
begin
IfCondition := Evaluate;
case IfCondition.Typ of
evInt: Result := IfCondition.AsInt <> 0;
evStr: Result := IfCondition.AsStr <> ''
else
WarningMsg(SSpecifiedConditionEvalatedToVoid, []);
Result := False
end;
end;
pcIfdef, pcIfndef:
begin
NextTokenExpect([tkIdent]);
case GetIdent(TokenString, DummyContext) of
itUnknown: Result := Command = pcIfNDef;
itVariable, itMacro: Result := Command = pcIfDef;
itFunc:
begin
Result := Command = pcIfDef;
WarningMsg(SFuncIdentForIfdef, []);
end;
else