-
Notifications
You must be signed in to change notification settings - Fork 1
/
pscanner.pp
3737 lines (3458 loc) · 99.8 KB
/
pscanner.pp
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 file is part of the Free Component Library
Pascal source lexical scanner
Copyright (c) 2003 by
Areca Systems GmbH / Sebastian Guenther, sg@freepascal.org
See the file COPYING.FPC, included in this distribution,
for details about the copyright.
This program 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.
**********************************************************************}
{$mode objfpc}
{$h+}
unit PScanner;
interface
uses SysUtils, Classes;
// message numbers
const
nErrInvalidCharacter = 1001;
nErrOpenString = 1002;
nErrIncludeFileNotFound = 1003;
nErrIfXXXNestingLimitReached = 1004;
nErrInvalidPPElse = 1005;
nErrInvalidPPEndif = 1006;
nLogOpeningFile = 1007;
nLogLineNumber = 1008;
nLogIFDefAccepted = 1009;
nLogIFDefRejected = 1010;
nLogIFNDefAccepted = 1011;
nLogIFNDefRejected = 1012;
nLogIFAccepted = 1013;
nLogIFRejected = 1014;
nLogIFOptAccepted = 1015;
nLogIFOptRejected = 1016;
nLogELSEIFAccepted = 1017;
nLogELSEIFRejected = 1018;
nErrInvalidMode = 1019;
nErrInvalidModeSwitch = 1020;
nErrXExpectedButYFound = 1021;
nErrRangeCheck = 1022;
nErrDivByZero = 1023;
nErrOperandAndOperatorMismatch = 1024;
nUserDefined = 1025;
nLogMacroDefined = 1026; // FPC=3101
nLogMacroUnDefined = 1027; // FPC=3102
nWarnIllegalCompilerDirectiveX = 1028;
// resourcestring patterns of messages
resourcestring
SErrInvalidCharacter = 'Invalid character ''%s''';
SErrOpenString = 'string exceeds end of line';
SErrIncludeFileNotFound = 'Could not find include file ''%s''';
SErrIfXXXNestingLimitReached = 'Nesting of $IFxxx too deep';
SErrInvalidPPElse = '$ELSE without matching $IFxxx';
SErrInvalidPPEndif = '$ENDIF without matching $IFxxx';
SLogOpeningFile = 'Opening source file "%s".';
SLogLineNumber = 'Reading line %d.';
SLogIFDefAccepted = 'IFDEF %s found, accepting.';
SLogIFDefRejected = 'IFDEF %s found, rejecting.';
SLogIFNDefAccepted = 'IFNDEF %s found, accepting.';
SLogIFNDefRejected = 'IFNDEF %s found, rejecting.';
SLogIFAccepted = 'IF %s found, accepting.';
SLogIFRejected = 'IF %s found, rejecting.';
SLogIFOptAccepted = 'IFOpt %s found, accepting.';
SLogIFOptRejected = 'IFOpt %s found, rejecting.';
SLogELSEIFAccepted = 'ELSEIF %s found, accepting.';
SLogELSEIFRejected = 'ELSEIF %s found, rejecting.';
SErrInvalidMode = 'Invalid mode: "%s"';
SErrInvalidModeSwitch = 'Invalid mode switch: "%s"';
SErrXExpectedButYFound = '"%s" expected, but "%s" found';
sErrRangeCheck = 'range check failed';
sErrDivByZero = 'division by zero';
sErrOperandAndOperatorMismatch = 'operand and operator mismatch';
SUserDefined = 'User defined: "%s"';
sLogMacroDefined = 'Macro defined: %s';
sLogMacroUnDefined = 'Macro undefined: %s';
sWarnIllegalCompilerDirectiveX = 'Illegal compiler directive "%s"';
type
TMessageType = (
mtFatal,
mtError,
mtWarning,
mtNote,
mtHint,
mtInfo,
mtDebug
);
TMessageTypes = set of TMessageType;
TMessageArgs = array of string;
TToken = (
tkEOF,
tkWhitespace,
tkComment,
tkIdentifier,
tkString,
tkNumber,
tkChar,
// Simple (one-character) tokens
tkBraceOpen, // '('
tkBraceClose, // ')'
tkMul, // '*'
tkPlus, // '+'
tkComma, // ','
tkMinus, // '-'
tkDot, // '.'
tkDivision, // '/'
tkColon, // ':'
tkSemicolon, // ';'
tkLessThan, // '<'
tkEqual, // '='
tkGreaterThan, // '>'
tkAt, // '@'
tkSquaredBraceOpen, // '['
tkSquaredBraceClose, // ']'
tkCaret, // '^'
tkBackslash, // '\'
// Two-character tokens
tkDotDot, // '..'
tkAssign, // ':='
tkNotEqual, // '<>'
tkLessEqualThan, // '<='
tkGreaterEqualThan, // '>='
tkPower, // '**'
tkSymmetricalDifference, // '><'
tkAssignPlus, // +=
tkAssignMinus, // -=
tkAssignMul, // *=
tkAssignDivision, // /=
tkAtAt, // @@
// Reserved words
tkabsolute,
tkand,
tkarray,
tkas,
tkasm,
tkbegin,
tkbitpacked,
tkcase,
tkclass,
tkconst,
tkconstref,
tkconstructor,
tkdestructor,
tkdispinterface,
tkdiv,
tkdo,
tkdownto,
tkelse,
tkend,
tkexcept,
tkexports,
tkfalse,
tkfile,
tkfinalization,
tkfinally,
tkfor,
tkfunction,
tkgeneric,
tkgoto,
tkif,
tkimplementation,
tkin,
tkinherited,
tkinitialization,
tkinline,
tkinterface,
tkis,
tklabel,
tklibrary,
tkmod,
tknil,
tknot,
tkobject,
tkof,
tkoperator,
tkor,
tkpacked,
tkprocedure,
tkprogram,
tkproperty,
tkraise,
tkrecord,
tkrepeat,
tkResourceString,
tkself,
tkset,
tkshl,
tkshr,
tkspecialize,
// tkstring,
tkthen,
tkthreadvar,
tkto,
tktrue,
tktry,
tktype,
tkunit,
tkuntil,
tkuses,
tkvar,
tkwhile,
tkwith,
tkxor,
tkLineEnding,
tkTab
);
TTokens = set of TToken;
TModeSwitch = (
msNone,
{ generic }
msFpc, msObjfpc, msDelphi, msDelphiUnicode, msTP7, msMac, msIso, msExtpas, msGPC,
{ more specific }
msClass, { delphi class model }
msObjpas, { load objpas unit }
msResult, { result in functions }
msStringPchar, { pchar 2 string conversion }
msCVarSupport, { cvar variable directive }
msNestedComment, { nested comments }
msTPProcVar, { tp style procvars (no @ needed) }
msMacProcVar, { macpas style procvars }
msRepeatForward, { repeating forward declarations is needed }
msPointer2Procedure, { allows the assignement of pointers to
procedure variables }
msAutoDeref, { does auto dereferencing of struct. vars }
msInitFinal, { initialization/finalization for units }
msDefaultAnsistring, { ansistring turned on by default }
msOut, { support the calling convention OUT }
msDefaultPara, { support default parameters }
msHintDirective, { support hint directives }
msDuplicateNames, { allow locals/paras to have duplicate names of globals }
msProperty, { allow properties }
msDefaultInline, { allow inline proc directive }
msExcept, { allow exception-related keywords }
msObjectiveC1, { support interfacing with Objective-C (1.0) }
msObjectiveC2, { support interfacing with Objective-C (2.0) }
msNestedProcVars, { support nested procedural variables }
msNonLocalGoto, { support non local gotos (like iso pascal) }
msAdvancedRecords, { advanced record syntax with visibility sections, methods and properties }
msISOLikeUnaryMinus, { unary minus like in iso pascal: same precedence level as binary minus/plus }
msSystemCodePage, { use system codepage as compiler codepage by default, emit ansistrings with system codepage }
msFinalFields, { allows declaring fields as "final", which means they must be initialised
in the (class) constructor and are constant from then on (same as final
fields in Java) }
msDefaultUnicodestring, { makes the default string type in $h+ mode unicodestring rather than
ansistring; similarly, char becomes unicodechar rather than ansichar }
msTypeHelpers, { allows the declaration of "type helper" (non-Delphi) or "record helper"
(Delphi) for primitive types }
msCBlocks, { 'cblocks', support for http://en.wikipedia.org/wiki/Blocks_(C_language_extension) }
msISOLikeIO, { I/O as it required by an ISO compatible compiler }
msISOLikeProgramsPara, { program parameters as it required by an ISO compatible compiler }
msISOLikeMod, { mod operation as it is required by an iso compatible compiler }
msExternalClass { Allow external class definitions }
);
TModeSwitches = Set of TModeSwitch;
TTokenOption = (toForceCaret,toOperatorToken);
TTokenOptions = Set of TTokenOption;
{ TMacroDef }
TMacroDef = Class(TObject)
Private
FName: String;
FValue: String;
Public
Constructor Create(Const AName,AValue : String);
Property Name : String Read FName;
Property Value : String Read FValue Write FValue;
end;
{ TLineReader }
TLineReader = class
Private
FFilename: string;
public
constructor Create(const AFilename: string); virtual;
function IsEOF: Boolean; virtual; abstract;
function ReadLine: string; virtual; abstract;
property Filename: string read FFilename;
end;
{ TFileLineReader }
TFileLineReader = class(TLineReader)
private
FTextFile: Text;
FileOpened: Boolean;
FBuffer : Array[0..4096-1] of byte;
public
constructor Create(const AFilename: string); override;
destructor Destroy; override;
function IsEOF: Boolean; override;
function ReadLine: string; override;
end;
{ TStreamLineReader }
TStreamLineReader = class(TLineReader)
private
FContent: AnsiString;
FPos : Integer;
public
Procedure InitFromStream(AStream : TStream);
function IsEOF: Boolean; override;
function ReadLine: string; override;
end;
{ TFileStreamLineReader }
TFileStreamLineReader = class(TStreamLineReader)
Public
constructor Create(const AFilename: string); override;
end;
{ TStringStreamLineReader }
TStringStreamLineReader = class(TStreamLineReader)
Public
constructor Create( const AFilename: string; Const ASource: String); reintroduce;
end;
{ TMacroReader }
TMacroReader = Class(TStringStreamLineReader)
private
FCurCol: Integer;
FCurRow: Integer;
Public
Property CurCol : Integer Read FCurCol Write FCurCol;
Property CurRow : Integer Read FCurRow Write FCurRow;
end;
{ TBaseFileResolver }
TBaseFileResolver = class
private
FBaseDirectory: string;
FIncludePaths: TStringList;
FStrictFileCase : Boolean;
Protected
procedure SetBaseDirectory(AValue: string); virtual;
procedure SetStrictFileCase(AValue: Boolean); virtual;
Function FindIncludeFileName(const AName: string): String;
Property IncludePaths: TStringList Read FIncludePaths;
public
constructor Create; virtual;
destructor Destroy; override;
procedure AddIncludePath(const APath: string); virtual;
function FindSourceFile(const AName: string): TLineReader; virtual; abstract;
function FindIncludeFile(const AName: string): TLineReader; virtual; abstract;
Property StrictFileCase : Boolean Read FStrictFileCase Write SetStrictFileCase;
property BaseDirectory: string read FBaseDirectory write SetBaseDirectory;
end;
{ TFileResolver }
TFileResolver = class(TBaseFileResolver)
private
FUseStreams: Boolean;
Protected
Function CreateFileReader(Const AFileName : String) : TLineReader; virtual;
Public
function FindSourceFile(const AName: string): TLineReader; override;
function FindIncludeFile(const AName: string): TLineReader; override;
Property UseStreams : Boolean Read FUseStreams Write FUseStreams;
end;
{ TStreamResolver }
TStreamResolver = class(TBaseFileResolver)
Private
FOwnsStreams: Boolean;
FStreams : TStringList;
function FindStream(const AName: string; ScanIncludes: Boolean): TStream;
function FindStreamReader(const AName: string; ScanIncludes: Boolean): TLineReader;
procedure SetOwnsStreams(AValue: Boolean);
Public
constructor Create; override;
destructor Destroy; override;
Procedure Clear;
Procedure AddStream(Const AName : String; AStream : TStream);
function FindSourceFile(const AName: string): TLineReader; override;
function FindIncludeFile(const AName: string): TLineReader; override;
Property OwnsStreams : Boolean Read FOwnsStreams write SetOwnsStreams;
Property Streams: TStringList read FStreams;
end;
const
CondDirectiveBool: array[boolean] of string = (
'0', // false
'1' // true Note: True is <>'0'
);
type
TCondDirectiveEvaluator = class;
TCEEvalVarEvent = function(Sender: TCondDirectiveEvaluator; Name: String; out Value: string): boolean of object;
TCEEvalFunctionEvent = function(Sender: TCondDirectiveEvaluator; Name, Param: String; out Value: string): boolean of object;
TCELogEvent = procedure(Sender: TCondDirectiveEvaluator; Args : Array of const) of object;
{ TCondDirectiveEvaluator - evaluate $IF expression }
TCondDirectiveEvaluator = class
private
FOnEvalFunction: TCEEvalFunctionEvent;
FOnEvalVariable: TCEEvalVarEvent;
FOnLog: TCELogEvent;
protected
type
TPrecedenceLevel = (
ceplFirst, // tkNot
ceplSecond, // *, /, div, mod, and, shl, shr
ceplThird, // +, -, or, xor
ceplFourth // =, <>, <, >, <=, >=
);
TStackItem = record
Level: TPrecedenceLevel;
Operathor: TToken;
Operand: String;
OperandPos: integer;
end;
protected
FTokenStart: PChar;
FTokenEnd: PChar;
FToken: TToken;
FStack: array of TStackItem;
FStackTop: integer;
function IsFalse(const Value: String): boolean; inline;
function IsTrue(const Value: String): boolean; inline;
function IsInteger(const Value: String; out i: int64): boolean;
function IsExtended(const Value: String; out e: extended): boolean;
procedure NextToken;
procedure Log(aMsgType: TMessageType; aMsgNumber: integer;
const aMsgFmt: String; const Args: array of const; MsgPos: integer = 0);
procedure LogXExpectedButTokenFound(const X: String; ErrorPos: integer = 0);
procedure ReadOperand(Skip: boolean = false); // unary operators plus one operand
procedure ReadExpression; // binary operators
procedure ResolveStack(MinStackLvl: integer; Level: TPrecedenceLevel;
NewOperator: TToken);
function GetTokenString: String;
function GetStringLiteralValue: String; // read value of tkString
procedure Push(const AnOperand: String; OperandPosition: integer);
public
Expression: String;
MsgPos: integer;
MsgNumber: integer;
MsgType: TMessageType;
MsgPattern: String; // Format parameter
constructor Create;
destructor Destroy; override;
function Eval(const Expr: string): boolean;
property OnEvalVariable: TCEEvalVarEvent read FOnEvalVariable write FOnEvalVariable;
property OnEvalFunction: TCEEvalFunctionEvent read FOnEvalFunction write FOnEvalFunction;
property OnLog: TCELogEvent read FOnLog write FOnLog;
end;
EScannerError = class(Exception);
EFileNotFoundError = class(Exception);
TPascalScannerPPSkipMode = (ppSkipNone, ppSkipIfBranch, ppSkipElseBranch, ppSkipAll);
TPOption = (
po_delphi, // DEPRECATED Delphi mode: forbid nested comments
po_KeepScannerError, // default: catch EScannerError and raise an EParserError instead
po_CAssignments, // allow C-operators += -= *= /=
po_ResolveStandardTypes, // search for 'longint', 'string', etc., do not use dummies, TPasResolver sets this to use its declarations
po_AsmWhole, // store whole text between asm..end in TPasImplAsmStatement.Tokens
po_NoOverloadedProcs, // do not create TPasOverloadedProc for procs with same name
po_KeepClassForward, // disabled: delete class fowards when there is a class declaration
po_ArrayRangeExpr, // enable: create TPasArrayType.IndexRange, disable: create TPasArrayType.Ranges
po_SelfToken, // Self is a token. For backward compatibility.
po_CheckModeSwitches, // stop on unknown modeswitch with an error
po_CheckCondFunction // stop on unknown function in conditional expression, default: return '0'
);
TPOptions = set of TPOption;
type
TPasSourcePos = Record
FileName: String;
Row, Column: Cardinal;
end;
const
DefPasSourcePos: TPasSourcePos = (Filename:''; Row:0; Column:0);
type
{ TPascalScanner }
TPScannerLogHandler = Procedure (Sender : TObject; Const Msg : String) of object;
TPScannerLogEvent = (sleFile,sleLineNumber,sleConditionals,sleDirective);
TPScannerLogEvents = Set of TPScannerLogEvent;
TPScannerDirectiveEvent = procedure(Sender: TObject; Directive, Param: String;
var Handled: boolean) of object;
TPascalScanner = class
private
FAllowedModes: TModeSwitches;
FAllowedModeSwitches: TModeSwitches;
FConditionEval: TCondDirectiveEvaluator;
FCurrentModeSwitches: TModeSwitches;
FCurTokenPos: TPasSourcePos;
FLastMsg: string;
FLastMsgArgs: TMessageArgs;
FLastMsgNumber: integer;
FLastMsgPattern: string;
FLastMsgType: TMessageType;
FFileResolver: TBaseFileResolver;
FCurSourceFile: TLineReader;
FCurFilename: string;
FCurRow: Integer;
FCurToken: TToken;
FCurTokenString: string;
FCurLine: string;
FMacros,
FDefines: TStrings;
FMacrosOn: boolean;
FNonTokens: TTokens;
FOnDirective: TPScannerDirectiveEvent;
FOnEvalFunction: TCEEvalFunctionEvent;
FOnEvalVariable: TCEEvalVarEvent;
FOptions: TPOptions;
FLogEvents: TPScannerLogEvents;
FOnLog: TPScannerLogHandler;
FPreviousToken: TToken;
FReadOnlyModeSwitches: TModeSwitches;
FSkipComments: Boolean;
FSkipWhiteSpace: Boolean;
FTokenOptions: TTokenOptions;
TokenStr: PChar;
FIncludeStack: TFPList;
// Preprocessor $IFxxx skipping data
PPSkipMode: TPascalScannerPPSkipMode;
PPIsSkipping: Boolean;
PPSkipStackIndex: Integer;
PPSkipModeStack: array[0..255] of TPascalScannerPPSkipMode;
PPIsSkippingStack: array[0..255] of Boolean;
function GetCurColumn: Integer;
function GetForceCaret: Boolean;
function OnCondEvalFunction(Sender: TCondDirectiveEvaluator; Name,
Param: String; out Value: string): boolean;
procedure OnCondEvalLog(Sender: TCondDirectiveEvaluator;
Args: array of const);
function OnCondEvalVar(Sender: TCondDirectiveEvaluator; Name: String; out
Value: string): boolean;
procedure SetAllowedModeSwitches(const AValue: TModeSwitches);
procedure SetCurrentModeSwitches(AValue: TModeSwitches);
procedure SetOptions(AValue: TPOptions);
procedure SetReadOnlyModeSwitches(const AValue: TModeSwitches);
protected
function FetchLine: boolean;
function GetMacroName(const Param: String): String;
procedure SetCurMsg(MsgType: TMessageType; MsgNumber: integer; Const Fmt : String; Args : Array of const);
Procedure DoLog(MsgType: TMessageType; MsgNumber: integer; Const Msg : String; SkipSourceInfo : Boolean = False);overload;
Procedure DoLog(MsgType: TMessageType; MsgNumber: integer; Const Fmt : String; Args : Array of const;SkipSourceInfo : Boolean = False);overload;
procedure Error(MsgNumber: integer; const Msg: string);overload;
procedure Error(MsgNumber: integer; const Fmt: string; Args: array of Const);overload;
procedure PushSkipMode;
function HandleDirective(const ADirectiveText: String): TToken; virtual;
function HandleLetterDirective(Letter: char; Enable: boolean): TToken; virtual;
procedure HandleIFDEF(const AParam: String);
procedure HandleIFNDEF(const AParam: String);
procedure HandleIFOPT(const AParam: String);
procedure HandleIF(const AParam: String);
procedure HandleELSEIF(const AParam: String);
procedure HandleELSE(const AParam: String);
procedure HandleENDIF(const AParam: String);
procedure HandleDefine(Param: String); virtual;
procedure HandleError(Param: String); virtual;
procedure HandleIncludeFile(Param: String); virtual;
procedure HandleUnDefine(Param: String);virtual;
function HandleInclude(const Param: String): TToken;virtual;
procedure HandleMacroDirective(const Param: String);virtual;
procedure HandleMode(const Param: String);virtual;
procedure HandleModeSwitch(const Param: String);virtual;
function HandleMacro(AIndex: integer): TToken;virtual;
procedure PushStackItem; virtual;
function DoFetchTextToken: TToken;
function DoFetchToken: TToken;
procedure ClearFiles;
Procedure ClearMacros;
Procedure SetCurTokenString(AValue : string);
function LogEvent(E : TPScannerLogEvent) : Boolean; inline;
public
constructor Create(AFileResolver: TBaseFileResolver);
destructor Destroy; override;
procedure OpenFile(const AFilename: string);
Procedure SetNonToken(aToken : TToken);
Procedure UnsetNonToken(aToken : TToken);
Procedure SetTokenOption(aOption : TTokenoption);
Procedure UnSetTokenOption(aOption : TTokenoption);
Function CheckToken(aToken : TToken; const ATokenString : String) : TToken;
function FetchToken: TToken;
function ReadNonPascalTillEndToken(StopAtLineEnd: boolean): TToken;
function AddDefine(const aName: String; Quiet: boolean = false): boolean;
function RemoveDefine(const aName: String; Quiet: boolean = false): boolean;
function UnDefine(const aName: String; Quiet: boolean = false): boolean; // check defines and macros
function IsDefined(const aName: String): boolean; // check defines and macros
function IfOpt(Letter: Char): boolean;
function AddMacro(const aName, aValue: String; Quiet: boolean = false): boolean;
function RemoveMacro(const aName: String; Quiet: boolean = false): boolean;
Procedure SetCompilerMode(S : String);
function CurSourcePos: TPasSourcePos;
Function SetForceCaret(AValue : Boolean) : Boolean; // returns old state
property FileResolver: TBaseFileResolver read FFileResolver;
property CurSourceFile: TLineReader read FCurSourceFile;
property CurFilename: string read FCurFilename;
Property SkipWhiteSpace : Boolean Read FSkipWhiteSpace Write FSkipWhiteSpace;
Property SkipComments : Boolean Read FSkipComments Write FSkipComments;
property CurLine: string read FCurLine;
property CurRow: Integer read FCurRow;
property CurColumn: Integer read GetCurColumn;
property CurToken: TToken read FCurToken;
property CurTokenString: string read FCurTokenString;
property CurTokenPos: TPasSourcePos read FCurTokenPos;
Property PreviousToken : TToken Read FPreviousToken;
Property NonTokens : TTokens Read FNonTokens;
Property TokenOptions : TTokenOptions Read FTokenOptions Write FTokenOptions;
property Defines: TStrings read FDefines;
property Macros: TStrings read FMacros;
property MacrosOn: boolean read FMacrosOn write FMacrosOn;
property OnDirective: TPScannerDirectiveEvent read FOnDirective write FOnDirective;
property AllowedModeSwitches: TModeSwitches Read FAllowedModeSwitches Write SetAllowedModeSwitches;
property ReadOnlyModeSwitches: TModeSwitches Read FReadOnlyModeSwitches Write SetReadOnlyModeSwitches;// always set, cannot be disabled
property CurrentModeSwitches: TModeSwitches Read FCurrentModeSwitches Write SetCurrentModeSwitches;
property Options : TPOptions Read FOptions Write SetOptions;
property ForceCaret : Boolean Read GetForceCaret;
property LogEvents : TPScannerLogEvents Read FLogEvents Write FLogEvents;
property OnLog : TPScannerLogHandler Read FOnLog Write FOnLog;
property ConditionEval: TCondDirectiveEvaluator read FConditionEval;
property OnEvalVariable: TCEEvalVarEvent read FOnEvalVariable write FOnEvalVariable;
property OnEvalFunction: TCEEvalFunctionEvent read FOnEvalFunction write FOnEvalFunction;
property LastMsg: string read FLastMsg write FLastMsg;
property LastMsgNumber: integer read FLastMsgNumber write FLastMsgNumber;
property LastMsgType: TMessageType read FLastMsgType write FLastMsgType;
property LastMsgPattern: string read FLastMsgPattern write FLastMsgPattern;
property LastMsgArgs: TMessageArgs read FLastMsgArgs write FLastMsgArgs;
end;
const
TokenInfos: array[TToken] of string = (
'EOF',
'Whitespace',
'Comment',
'Identifier',
'string',
'Number',
'Character',
'(',
')',
'*',
'+',
',',
'-',
'.',
'/',
':',
';',
'<',
'=',
'>',
'@',
'[',
']',
'^',
'\',
'..',
':=',
'<>',
'<=',
'>=',
'**',
'><',
'+=',
'-=',
'*=',
'/=',
'@@',
// Reserved words
'absolute',
'and',
'array',
'as',
'asm',
'begin',
'bitpacked',
'case',
'class',
'const',
'constref',
'constructor',
'destructor',
'dispinterface',
'div',
'do',
'downto',
'else',
'end',
'except',
'exports',
'false',
'file',
'finalization',
'finally',
'for',
'function',
'generic',
'goto',
'if',
'implementation',
'in',
'inherited',
'initialization',
'inline',
'interface',
'is',
'label',
'library',
'mod',
'nil',
'not',
'object',
'of',
'operator',
'or',
'packed',
'procedure',
'program',
'property',
'raise',
'record',
'repeat',
'resourcestring',
'self',
'set',
'shl',
'shr',
'specialize',
// 'string',
'then',
'threadvar',
'to',
'true',
'try',
'type',
'unit',
'until',
'uses',
'var',
'while',
'with',
'xor',
'LineEnding',
'Tab'
);
SModeSwitchNames : array[TModeSwitch] of string[18] =
( '', // msNone
'', // Fpc,
'', // Objfpc,
'', // Delphi,
'', // DelphiUnicode,
'', // TP7,
'', // Mac,
'', // Iso,
'', // Extpas,
'', // GPC,
{ more specific }
'CLASS',
'OBJPAS',
'RESULT',
'PCHARTOSTRING',
'CVAR',
'NESTEDCOMMENTS',
'CLASSICPROCVARS',
'MACPROCVARS',
'REPEATFORWARD',
'POINTERTOPROCVAR',
'AUTODEREF',
'INITFINAL',
'ANSISTRINGS',
'OUT',
'DEFAULTPARAMETERS',
'HINTDIRECTIVE',
'DUPLICATELOCALS',
'PROPERTIES',
'ALLOWINLINE',
'EXCEPTIONS',
'OBJECTIVEC1',
'OBJECTIVEC2',
'NESTEDPROCVARS',
'NONLOCALGOTO',
'ADVANCEDRECORDS',
'ISOUNARYMINUS',
'SYSTEMCODEPAGE',
'FINALFIELDS',
'UNICODESTRINGS',
'TYPEHELPERS',
'CBLOCKS',
'ISOIO',
'ISOPROGRAMPARAS',
'ISOMOD',
'EXTERNALCLASS'
);
LetterSwitchNames: array['A'..'Z'] of string=(
'ALIGN' // A
,'BOOLEVAL' // B
,'ASSERTIONS' // C
,'DEBUGINFO' // D
,'EXTENSION' // E
,'' // F
,'IMPORTEDDATA' // G
,'LONGSTRINGS' // H
,'IOCHECKS' // I
,'WRITEABLECONST' // J
,'' // K
,'LOCALSYMBOLS' // L
,'TYPEINFO' // M
,'' // N
,'OPTIMIZATION' // O
,'OPENSTRINGS' // P
,'OVERFLOWCHECKS' // Q
,'RANGECHECKS' // R
,'' // S
,'TYPEADDRESS' // T
,'SAFEDIVIDE' // U
,'VARSTRINGCHECKS'// V
,'STACKFRAMES' // W
,'EXTENDEDSYNTAX' // X
,'REFERENCEINFO' // Y
,'' // Z
);
const
AllLanguageModes = [msFPC,msObjFPC,msDelphi,msTP7,msMac,msISO,msExtPas];
Const
MessageTypeNames : Array[TMessageType] of string = (
'Fatal','Error','Warning','Note','Hint','Info','Debug'
);
const
// all mode switches supported by FPC
msAllFPCModeSwitches = [low(TModeSwitch)..High(TModeSwitch)];
DelphiModeSwitches = [msDelphi,msClass,msObjpas,msresult,msstringpchar,
mspointer2procedure,msautoderef,msTPprocvar,msinitfinal,msdefaultansistring,
msout,msdefaultpara,msduplicatenames,mshintdirective,
msproperty,msdefaultinline,msexcept,msadvancedrecords,mstypehelpers];
DelphiUnicodeModeSwitches = delphimodeswitches + [mssystemcodepage,msdefaultunicodestring];
// mode switches of $mode FPC, don't confuse with msAllFPCModeSwitches
FPCModeSwitches = [msfpc,msstringpchar,msnestedcomment,msrepeatforward,
mscvarsupport,msinitfinal,mshintdirective, msproperty,msdefaultinline];
OBJFPCModeSwitches = [msobjfpc,msclass,msobjpas,msresult,msstringpchar,msnestedcomment,
msrepeatforward,mscvarsupport,msinitfinal,msout,msdefaultpara,mshintdirective,
msproperty,msdefaultinline,msexcept];
TPModeSwitches = [mstp7,mstpprocvar,msduplicatenames];
GPCModeSwitches = [msgpc,mstpprocvar];
MacModeSwitches = [msmac,mscvarsupport,msmacprocvar,msnestedprocvars,msnonlocalgoto,
msisolikeunaryminus,msdefaultinline];
ISOModeSwitches = [msiso,mstpprocvar,msduplicatenames,msnestedprocvars,msnonlocalgoto,msisolikeunaryminus,msisolikeio,
msisolikeprogramspara, msisolikemod];
ExtPasModeSwitches = [msextpas,mstpprocvar,msduplicatenames,msnestedprocvars,msnonlocalgoto,msisolikeunaryminus,msisolikeio,
msisolikeprogramspara, msisolikemod];
function StrToModeSwitch(aName: String): TModeSwitch;
function FilenameIsAbsolute(const TheFilename: string):boolean;
function FilenameIsWinAbsolute(const TheFilename: string): boolean;
function FilenameIsUnixAbsolute(const TheFilename: string): boolean;
function IsNamedToken(Const AToken : String; Out T : TToken) : Boolean;
procedure CreateMsgArgs(var MsgArgs: TMessageArgs; Args: array of const);
function SafeFormat(const Fmt: string; Args: array of const): string;
implementation
Var
SortedTokens : array of TToken;
LowerCaseTokens : Array[ttoken] of String;
Procedure SortTokenInfo;
Var
tk: tToken;
I,J,K, l: integer;
begin
for tk:=Low(TToken) to High(ttoken) do
LowerCaseTokens[tk]:=LowerCase(TokenInfos[tk]);
SetLength(SortedTokens,Ord(tkXor)-Ord(tkAbsolute)+1);
I:=0;
for tk := tkAbsolute to tkXOR do
begin
SortedTokens[i]:=tk;
Inc(i);
end;
l:=Length(SortedTokens)-1;
k:=l shr 1;
while (k>0) do
begin
for i:=0 to l-k do
begin
j:=i;
while (J>=0) and (LowerCaseTokens[SortedTokens[J]]>LowerCaseTokens[SortedTokens[J+K]]) do
begin
tk:=SortedTokens[J];
SortedTokens[J]:=SortedTokens[J+K];
SortedTokens[J+K]:=tk;
if (J>K) then
Dec(J,K)
else
J := 0
end;
end;
K:=K shr 1;
end;
end;
function IndexOfToken(Const AToken : string) : Integer;
var
B,T,M : Integer;
N : String;
begin
B:=0;
T:=Length(SortedTokens)-1;
while (B<=T) do
begin
M:=(B+T) div 2;
N:=LowerCaseTokens[SortedTokens[M]];
if (AToken<N) then
T:=M-1
else if (AToken=N) then
Exit(M)
else
B:=M+1;
end;
Result:=-1;
end;
function IsNamedToken(Const AToken : String; Out T : TToken) : Boolean;
Var
I : Integer;
begin
if (Length(SortedTokens)=0) then
SortTokenInfo;
I:=IndexOfToken(LowerCase(AToken));
Result:=I<>-1;
If Result then
T:=SortedTokens[I];
end;
procedure CreateMsgArgs(var MsgArgs: TMessageArgs; Args: array of const);
var
i: Integer;
begin
SetLength(MsgArgs, High(Args)-Low(Args)+1);
for i:=Low(Args) to High(Args) do
case Args[i].VType of
vtInteger: MsgArgs[i] := IntToStr(Args[i].VInteger);
vtBoolean: MsgArgs[i] := BoolToStr(Args[i].VBoolean);
vtChar: MsgArgs[i] := Args[i].VChar;
{$ifndef FPUNONE}
vtExtended: ; // Args[i].VExtended^;
{$ENDIF}
vtString: MsgArgs[i] := Args[i].VString^;
vtPointer: ; // Args[i].VPointer;
vtPChar: MsgArgs[i] := Args[i].VPChar;
vtObject: ; // Args[i].VObject;
vtClass: ; // Args[i].VClass;
vtWideChar: MsgArgs[i] := AnsiString(Args[i].VWideChar);
vtPWideChar: MsgArgs[i] := Args[i].VPWideChar;
vtAnsiString: MsgArgs[i] := AnsiString(Args[i].VAnsiString);
vtCurrency: ; // Args[i].VCurrency^);
vtVariant: ; // Args[i].VVariant^);