-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfpexprpars2.pas
3572 lines (2952 loc) · 95.5 KB
/
fpexprpars2.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
{
This file is part of the Free Component Library (FCL)
Copyright (c) 2008 Michael Van Canneyt.
Expression parser, supports variables, functions and
float/integer/string/boolean/datetime operations.
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 fpexprpars2;
interface
uses
Classes, SysUtils, contnrs;
Type
// tokens
TTokenType = (ttPlus, ttMinus, ttLessThan, ttLargerThan, ttEqual, ttDiv,
ttMul, ttLeft, ttRight, ttLessThanEqual, ttLargerThanEqual,
ttunequal, ttNumber, ttString, ttIdentifier,
ttComma, ttand, ttOr,ttXor,ttTrue,ttFalse,ttnot,ttif,
ttCase,ttEOF, ttPower);
TExprFloat = Double;
Const
ttDelimiters = [ttPlus, ttMinus, ttLessThan, ttLargerThan, ttEqual, ttDiv,
ttMul, ttLeft, ttRight, ttLessThanEqual, ttLargerThanEqual,
ttunequal, ttPower];
ttComparisons = [ttLargerThan,ttLessthan,
ttLargerThanEqual,ttLessthanEqual,
ttEqual,ttUnequal];
Type
TFPExpressionParser = Class;
TExprBuiltInManager = Class;
{ TFPExpressionScanner }
TFPExpressionScanner = Class(TObject)
FSource : String;
LSource,
FPos : Integer;
FChar : PChar;
FToken : String;
FTokenType : TTokenType;
private
function GetCurrentChar: Char;
procedure ScanError(Msg: String);
protected
procedure SetSource(const AValue: String); virtual;
function DoIdentifier: TTokenType;
function DoNumber: TTokenType;
function DoDelimiter: TTokenType;
function DoString: TTokenType;
Function NextPos : Char; // inline;
procedure SkipWhiteSpace; // inline;
function IsWordDelim(C : Char) : Boolean; // inline;
function IsDelim(C : Char) : Boolean; // inline;
function IsDigit(C : Char) : Boolean; // inline;
function IsAlpha(C : Char) : Boolean; // inline;
public
Constructor Create;
Function GetToken : TTokenType;
Property Token : String Read FToken;
Property TokenType : TTokenType Read FTokenType;
Property Source : String Read FSource Write SetSource;
Property Pos : Integer Read FPos;
Property CurrentChar : Char Read GetCurrentChar;
end;
EExprScanner = Class(Exception);
TResultType = (rtBoolean,rtInteger,rtFloat,rtDateTime,rtString);
TResultTypes = set of TResultType;
TFPExpressionResult = record
ResString : String;
Case ResultType : TResultType of
rtBoolean : (ResBoolean : Boolean);
rtInteger : (ResInteger : Int64);
rtFloat : (ResFloat : TExprFloat);
rtDateTime : (ResDateTime : TDatetime);
rtString : ();
end;
PFPExpressionResult = ^TFPExpressionResult;
TExprParameterArray = Array of TFPExpressionResult;
{ TFPExprNode }
TFPExprNode = Class(TObject)
Protected
Procedure CheckNodeType(Anode : TFPExprNode; Allowed : TResultTypes);
// A procedure with var saves an implicit try/finally in each node
// A marked difference in execution speed.
Procedure GetNodeValue(var Result : TFPExpressionResult); virtual; abstract;
Public
Procedure Check; virtual; abstract;
Function NodeType : TResultType; virtual; abstract;
Function NodeValue : TFPExpressionResult;
Function AsString : string; virtual; abstract;
end;
TExprArgumentArray = Array of TFPExprNode;
{ TFPBinaryOperation }
TFPBinaryOperation = Class(TFPExprNode)
private
FLeft: TFPExprNode;
FRight: TFPExprNode;
Protected
Procedure CheckSameNodeTypes;
Public
Constructor Create(ALeft,ARight : TFPExprNode);
Destructor Destroy; override;
Procedure Check; override;
Property left : TFPExprNode Read FLeft;
Property Right : TFPExprNode Read FRight;
end;
TFPBinaryOperationClass = Class of TFPBinaryOperation;
{ TFPBooleanOperation }
TFPBooleanOperation = Class(TFPBinaryOperation)
Public
Procedure Check; override;
Function NodeType : TResultType; override;
end;
{ TFPBinaryAndOperation }
TFPBinaryAndOperation = Class(TFPBooleanOperation)
Protected
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
Public
Function AsString : string ; override;
end;
{ TFPBinaryOrOperation }
TFPBinaryOrOperation = Class(TFPBooleanOperation)
Protected
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
Public
Function AsString : string ; override;
end;
{ TFPBinaryXOrOperation }
TFPBinaryXOrOperation = Class(TFPBooleanOperation)
Protected
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
Public
Function AsString : string ; override;
end;
{ TFPBooleanResultOperation }
TFPBooleanResultOperation = Class(TFPBinaryOperation)
Public
Procedure Check; override;
Function NodeType : TResultType; override;
end;
TFPBooleanResultOperationClass = Class of TFPBooleanResultOperation;
{ TFPEqualOperation }
TFPEqualOperation = Class(TFPBooleanResultOperation)
Protected
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
Public
Function AsString : string ; override;
end;
{ TFPUnequalOperation }
TFPUnequalOperation = Class(TFPEqualOperation)
Protected
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
Public
Function AsString : string ; override;
end;
{ TFPOrderingOperation }
TFPOrderingOperation = Class(TFPBooleanResultOperation)
Public
Procedure Check; override;
end;
{ TFPLessThanOperation }
TFPLessThanOperation = Class(TFPOrderingOperation)
Protected
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
Public
Function AsString : string ; override;
end;
{ TFPGreaterThanOperation }
TFPGreaterThanOperation = Class(TFPOrderingOperation)
Protected
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
Public
Function AsString : string ; override;
end;
{ TFPLessThanEqualOperation }
TFPLessThanEqualOperation = Class(TFPGreaterThanOperation)
Protected
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
Public
Function AsString : string ; override;
end;
{ TFPGreaterThanEqualOperation }
TFPGreaterThanEqualOperation = Class(TFPLessThanOperation)
Protected
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
Public
Function AsString : string ; override;
end;
{ TIfOperation }
TIfOperation = Class(TFPBinaryOperation)
private
FCondition: TFPExprNode;
protected
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
Public
Procedure Check; override;
Function NodeType : TResultType; override;
Constructor Create(ACondition,ALeft,ARight : TFPExprNode);
Destructor destroy; override;
Function AsString : string ; override;
Property Condition : TFPExprNode Read FCondition;
end;
{ TCaseOperation }
TCaseOperation = Class(TFPExprNode)
private
FArgs : TExprArgumentArray;
FCondition: TFPExprNode;
protected
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
Public
Procedure Check; override;
Function NodeType : TResultType; override;
Constructor Create(Args : TExprArgumentArray);
Destructor destroy; override;
Function AsString : string ; override;
Property Condition : TFPExprNode Read FCondition;
end;
{ TMathOperation }
TMathOperation = Class(TFPBinaryOperation)
Public
Procedure Check; override;
Function NodeType : TResultType; override;
end;
{ TFPAddOperation }
TFPAddOperation = Class(TMathOperation)
Protected
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
Public
Function AsString : string ; override;
end;
{ TFPSubtractOperation }
TFPSubtractOperation = Class(TMathOperation)
Public
Procedure Check; override;
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
Function AsString : string ; override;
end;
{ TFPMultiplyOperation }
TFPMultiplyOperation = Class(TMathOperation)
Public
Procedure check; override;
Function AsString : string ; override;
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
end;
{ TFPDivideOperation }
TFPDivideOperation = Class(TMathOperation)
Public
Procedure Check; override;
Function AsString : string ; override;
Function NodeType : TResultType; override;
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
end;
{ TFPPowerOperation }
TFPPowerOperation = Class(TMathOperation)
Public
Procedure check; override;
Function AsString : string ; override;
Function NodeType : TResultType; override;
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
end;
{ TFPUnaryOperator }
TFPUnaryOperator = Class(TFPExprNode)
private
FOperand: TFPExprNode;
Public
Constructor Create(AOperand : TFPExprNode);
Destructor Destroy; override;
Procedure Check; override;
Property Operand : TFPExprNode Read FOperand;
end;
{ TFPConvertNode }
TFPConvertNode = Class(TFPUnaryOperator)
Function AsString : String; override;
end;
{ TFPNotNode }
TFPNotNode = Class(TFPUnaryOperator)
Public
Procedure Check; override;
Function NodeType : TResultType; override;
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
Function AsString : String; override;
end;
TIntConvertNode = Class(TFPConvertNode)
Public
Procedure Check; override;
end;
{ TIntToFloatNode }
TIntToFloatNode = Class(TIntConvertNode)
Public
Function NodeType : TResultType; override;
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
end;
{ TIntToDateTimeNode }
TIntToDateTimeNode = Class(TIntConvertNode)
Public
Function NodeType : TResultType; override;
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
end;
{ TFloatToDateTimeNode }
TFloatToDateTimeNode = Class(TFPConvertNode)
Public
Procedure Check; override;
Function NodeType : TResultType; override;
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
end;
{ TFPNegateOperation }
TFPNegateOperation = Class(TFPUnaryOperator)
Public
Procedure Check; override;
Function NodeType : TResultType; override;
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
Function AsString : String; override;
end;
{ TFPConstExpression }
TFPConstExpression = Class(TFPExprnode)
private
FValue : TFPExpressionResult;
public
Constructor CreateString(AValue : String);
Constructor CreateInteger(AValue : Int64);
Constructor CreateDateTime(AValue : TDateTime);
Constructor CreateFloat(AValue : TExprFloat);
Constructor CreateBoolean(AValue : Boolean);
Procedure Check; override;
Function NodeType : TResultType; override;
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
Function AsString : string ; override;
// For inspection
Property ConstValue : TFPExpressionResult read FValue;
end;
TIdentifierType = (itVariable,itFunctionCallBack,itFunctionHandler);
TFPExprFunctionCallBack = Procedure (Var Result : TFPExpressionResult; Const Args : TExprParameterArray);
TFPExprFunctionEvent = Procedure (Var Result : TFPExpressionResult; Const Args : TExprParameterArray) of object;
TFPExprVariableCallBack = Procedure (Var Result : TFPExpressionResult; ConstRef AName : ShortString);
TFPExprVariableEvent = Procedure (Var Result : TFPExpressionResult; ConstRef AName : ShortString) of Object;
{ TFPExprIdentifierDef }
TFPExprIdentifierDef = Class(TCollectionItem)
private
FOnGetVarValue: TFPExprVariableEvent;
FOnGetVarValueCB: TFPExprVariableCallBack;
FStringValue : String;
FValue : TFPExpressionResult;
FArgumentTypes: String;
FIDType: TIdentifierType;
FName: ShortString;
FOnGetValue: TFPExprFunctionEvent;
FOnGetValueCB: TFPExprFunctionCallBack;
function GetAsBoolean: Boolean;
function GetAsDateTime: TDateTime;
function GetAsFloat: TExprFloat;
function GetAsInteger: Int64;
function GetAsString: String;
function GetResultType: TResultType;
function GetValue: String;
procedure SetArgumentTypes(const AValue: String);
procedure SetAsBoolean(const AValue: Boolean);
procedure SetAsDateTime(const AValue: TDateTime);
procedure SetAsFloat(const AValue: TExprFloat);
procedure SetAsInteger(const AValue: Int64);
procedure SetAsString(const AValue: String);
procedure SetName(const AValue: ShortString);
procedure SetResultType(const AValue: TResultType);
procedure SetValue(const AValue: String);
Protected
Procedure CheckResultType(Const AType : TResultType);
Procedure CheckVariable;
Procedure FetchValue;
Public
Function ArgumentCount : Integer;
Procedure Assign(Source : TPersistent); override;
Function EventBasedVariable : Boolean; Inline;
Property AsFloat : TExprFloat Read GetAsFloat Write SetAsFloat;
Property AsInteger : Int64 Read GetAsInteger Write SetAsInteger;
Property AsString : String Read GetAsString Write SetAsString;
Property AsBoolean : Boolean Read GetAsBoolean Write SetAsBoolean;
Property AsDateTime : TDateTime Read GetAsDateTime Write SetAsDateTime;
Property OnGetFunctionValueCallBack : TFPExprFunctionCallBack Read FOnGetValueCB Write FOnGetValueCB;
Property OnGetVariableValueCallBack : TFPExprVariableCallBack Read FOnGetVarValueCB Write FOnGetVarValueCB;
Published
Property IdentifierType : TIdentifierType Read FIDType Write FIDType;
Property Name : ShortString Read FName Write SetName;
Property Value : String Read GetValue Write SetValue;
Property ParameterTypes : String Read FArgumentTypes Write SetArgumentTypes;
Property ResultType : TResultType Read GetResultType Write SetResultType;
Property OnGetFunctionValue : TFPExprFunctionEvent Read FOnGetValue Write FOnGetValue;
Property OnGetVariableValue : TFPExprVariableEvent Read FOnGetVarValue Write FOnGetVarValue;
end;
TBuiltInCategory = (bcStrings,bcDateTime,bcMath,bcBoolean,bcConversion,bcData,bcVaria,bcUser);
TBuiltInCategories = Set of TBuiltInCategory;
{ TFPBuiltInExprIdentifierDef }
TFPBuiltInExprIdentifierDef = Class(TFPExprIdentifierDef)
private
FCategory: TBuiltInCategory;
Public
Procedure Assign(Source : TPersistent); override;
Published
Property Category : TBuiltInCategory Read FCategory Write FCategory;
end;
{ TFPExprIdentifierDefs }
TFPExprIdentifierDefs = Class(TCollection)
private
FParser: TFPExpressionParser;
function GetI(AIndex : Integer): TFPExprIdentifierDef;
procedure SetI(AIndex : Integer; const AValue: TFPExprIdentifierDef);
Protected
procedure Update(Item: TCollectionItem); override;
Property Parser: TFPExpressionParser Read FParser;
Public
Function IndexOfIdentifier(Const AName : ShortString) : Integer;
Function FindIdentifier(Const AName : ShortString) : TFPExprIdentifierDef;
Function IdentifierByName(Const AName : ShortString) : TFPExprIdentifierDef;
Function AddVariable(Const AName : ShortString; AResultType : TResultType; ACallback : TFPExprVariableCallBack) : TFPExprIdentifierDef;
Function AddVariable(Const AName : ShortString; AResultType : TResultType; ACallback : TFPExprVariableEvent) : TFPExprIdentifierDef;
Function AddVariable(Const AName : ShortString; AResultType : TResultType; AValue : String) : TFPExprIdentifierDef;
Function AddBooleanVariable(Const AName : ShortString; AValue : Boolean) : TFPExprIdentifierDef;
Function AddIntegerVariable(Const AName : ShortString; AValue : Integer) : TFPExprIdentifierDef;
Function AddFloatVariable(Const AName : ShortString; AValue : TExprFloat) : TFPExprIdentifierDef;
Function AddStringVariable(Const AName : ShortString; AValue : String) : TFPExprIdentifierDef;
Function AddDateTimeVariable(Const AName : ShortString; AValue : TDateTime) : TFPExprIdentifierDef;
Function AddFunction(Const AName : ShortString; Const AResultType : Char; Const AParamTypes : String; ACallBack : TFPExprFunctionCallBack) : TFPExprIdentifierDef;
Function AddFunction(Const AName : ShortString; Const AResultType : Char; Const AParamTypes : String; ACallBack : TFPExprFunctionEvent) : TFPExprIdentifierDef;
property Identifiers[AIndex : Integer] : TFPExprIdentifierDef Read GetI Write SetI; Default;
end;
{ TFPExprIdentifierNode }
TFPExprIdentifierNode = Class(TFPExprNode)
Private
FID : TFPExprIdentifierDef;
PResult : PFPExpressionResult;
FResultType : TResultType;
public
Constructor CreateIdentifier(AID : TFPExprIdentifierDef);
Function NodeType : TResultType; override;
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
Property Identifier : TFPExprIdentifierDef Read FID;
end;
{ TFPExprVariable }
TFPExprVariable = Class(TFPExprIdentifierNode)
Procedure Check; override;
function AsString: string; override;
end;
{ TFPExprFunction }
TFPExprFunction = Class(TFPExprIdentifierNode)
private
FArgumentNodes : TExprArgumentArray;
FargumentParams : TExprParameterArray;
Protected
Procedure CalcParams;
Public
Procedure Check; override;
Constructor CreateFunction(AID : TFPExprIdentifierDef; Const Args : TExprArgumentArray); virtual;
Destructor Destroy; override;
Property ArgumentNodes : TExprArgumentArray Read FArgumentNodes;
Property ArgumentParams : TExprParameterArray Read FArgumentParams;
Function AsString : String; override;
end;
{ TFPFunctionCallBack }
TFPFunctionCallBack = Class(TFPExprFunction)
Private
FCallBack : TFPExprFunctionCallBack;
Public
Constructor CreateFunction(AID : TFPExprIdentifierDef; Const Args : TExprArgumentArray); override;
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
Property CallBack : TFPExprFunctionCallBack Read FCallBack;
end;
{ TFPFunctionEventHandler }
TFPFunctionEventHandler = Class(TFPExprFunction)
Private
FCallBack : TFPExprFunctionEvent;
Public
Constructor CreateFunction(AID : TFPExprIdentifierDef; Const Args : TExprArgumentArray); override;
Procedure GetNodeValue(var Result : TFPExpressionResult); override;
Property CallBack : TFPExprFunctionEvent Read FCallBack;
end;
{ TFPExpressionParser }
TFPExpressionParser = class(TComponent)
private
FBuiltIns: TBuiltInCategories;
FExpression: String;
FScanner : TFPExpressionScanner;
FExprNode : TFPExprNode;
FIdentifiers : TFPExprIdentifierDefs;
FHashList : TFPHashObjectlist;
FDirty : Boolean;
procedure CheckEOF;
function ConvertNode(Todo: TFPExprNode; ToType: TResultType): TFPExprNode;
function GetAsBoolean: Boolean;
function GetAsDateTime: TDateTime;
function GetAsFloat: TExprFloat;
function GetAsInteger: Int64;
function GetAsString: String;
function MatchNodes(Todo, Match: TFPExprNode): TFPExprNode;
procedure CheckNodes(var Left, Right: TFPExprNode);
procedure SetBuiltIns(const AValue: TBuiltInCategories);
procedure SetIdentifiers(const AValue: TFPExprIdentifierDefs);
Protected
procedure ParserError(Msg: String);
procedure SetExpression(const AValue: String); virtual;
Procedure CheckResultType(Const Res :TFPExpressionResult; AType : TResultType); inline;
class Function BuiltinsManager : TExprBuiltInManager;
Function Level1 : TFPExprNode;
Function Level2 : TFPExprNode;
Function Level3 : TFPExprNode;
Function Level4 : TFPExprNode;
Function Level5 : TFPExprNode;
Function Level6 : TFPExprNode;
Function Level7 : TFPExprNode;
Function Primitive : TFPExprNode;
function GetToken: TTokenType;
Function TokenType : TTokenType;
Function CurrentToken : String;
Procedure CreateHashList;
Property Scanner : TFPExpressionScanner Read FScanner;
Property ExprNode : TFPExprNode Read FExprNode;
Property Dirty : Boolean Read FDirty;
public
Constructor Create(AOwner :TComponent); override;
Destructor Destroy; override;
Function IdentifierByName(const AName : ShortString) : TFPExprIdentifierDef; virtual;
Procedure Clear;
Procedure EvaluateExpression(Var Result : TFPExpressionResult);
Function Evaluate : TFPExpressionResult;
Function ResultType : TResultType;
Property AsFloat : TExprFloat Read GetAsFloat;
Property AsInteger : Int64 Read GetAsInteger;
Property AsString : String Read GetAsString;
Property AsBoolean : Boolean Read GetAsBoolean;
Property AsDateTime : TDateTime Read GetAsDateTime;
Published
// The Expression to parse
property Expression : String read FExpression write SetExpression;
Property Identifiers : TFPExprIdentifierDefs Read FIdentifiers Write SetIdentifiers;
Property BuiltIns : TBuiltInCategories Read FBuiltIns Write SetBuiltIns;
end;
{ TExprBuiltInManager }
TExprBuiltInManager = Class(TComponent)
Private
FDefs : TFPExprIdentifierDefs;
function GetCount: Integer;
function GetI(AIndex : Integer): TFPBuiltInExprIdentifierDef;
protected
Property Defs : TFPExprIdentifierDefs Read FDefs;
Public
Constructor Create(AOwner : TComponent); override;
Destructor Destroy; override;
Function IndexOfIdentifier(Const AName : ShortString) : Integer;
Function FindIdentifier(Const AName : ShortString) : TFPBuiltinExprIdentifierDef;
Function IdentifierByName(Const AName : ShortString) : TFPBuiltinExprIdentifierDef;
Function AddVariable(Const ACategory : TBuiltInCategory; Const AName : ShortString; AResultType : TResultType; AValue : String) : TFPBuiltInExprIdentifierDef;
Function AddBooleanVariable(Const ACategory : TBuiltInCategory; Const AName : ShortString; AValue : Boolean) : TFPBuiltInExprIdentifierDef;
Function AddIntegerVariable(Const ACategory : TBuiltInCategory; Const AName : ShortString; AValue : Integer) : TFPBuiltInExprIdentifierDef;
Function AddFloatVariable(Const ACategory : TBuiltInCategory; Const AName : ShortString; AValue : TExprFloat) : TFPBuiltInExprIdentifierDef;
Function AddStringVariable(Const ACategory : TBuiltInCategory; Const AName : ShortString; AValue : String) : TFPBuiltInExprIdentifierDef;
Function AddDateTimeVariable(Const ACategory : TBuiltInCategory; Const AName : ShortString; AValue : TDateTime) : TFPBuiltInExprIdentifierDef;
Function AddFunction(Const ACategory : TBuiltInCategory; Const AName : ShortString; Const AResultType : Char; Const AParamTypes : String; ACallBack : TFPExprFunctionCallBack) : TFPBuiltInExprIdentifierDef;
Function AddFunction(Const ACategory : TBuiltInCategory; Const AName : ShortString; Const AResultType : Char; Const AParamTypes : String; ACallBack : TFPExprFunctionEvent) : TFPBuiltInExprIdentifierDef;
Property IdentifierCount : Integer Read GetCount;
Property Identifiers[AIndex : Integer] :TFPBuiltInExprIdentifierDef Read GetI;
end;
EExprParser = Class(Exception);
Function TokenName (AToken : TTokenType) : String;
Function ResultTypeName (AResult : TResultType) : String;
Function CharToResultType(C : Char) : TResultType;
Function BuiltinIdentifiers : TExprBuiltInManager;
Procedure RegisterStdBuiltins(AManager : TExprBuiltInManager);
function ArgToFloat(Arg: TFPExpressionResult): TExprFloat;
Const
AllBuiltIns = [bcStrings,bcDateTime,bcMath,bcBoolean,bcConversion,bcData,bcVaria,bcUser];
implementation
uses
typinfo, math;
{ TFPExpressionParser }
const
cNull=#0;
cSingleQuote = '''';
Digits = ['0'..'9','.'];
WhiteSpace = [' ',#13,#10,#9];
Operators = ['+','-','<','>','=','/','*','^'];
Delimiters = Operators+[',','(',')'];
Symbols = ['%']+Delimiters;
WordDelimiters = WhiteSpace + Symbols;
Resourcestring
SBadQuotes = 'Unterminated string';
SUnknownDelimiter = 'Unknown delimiter character: "%s"';
SErrUnknownCharacter = 'Unknown character at pos %d: "%s"';
SErrUnexpectedEndOfExpression = 'Unexpected end of expression';
SErrUnknownComparison = 'Internal error: Unknown comparison';
SErrUnknownBooleanOp = 'Internal error: Unknown boolean operation';
SErrBracketExpected = 'Expected ) bracket at position %d, but got %s';
SerrUnknownTokenAtPos = 'Unknown token at pos %d : %s';
SErrLeftBracketExpected = 'Expected ( bracket at position %d, but got %s';
SErrInvalidFloat = '%s is not a valid floating-point value';
SErrUnknownIdentifier = 'Unknown identifier: %s';
SErrInExpression = 'Cannot evaluate: error in expression';
SErrInExpressionEmpty = 'Cannot evaluate: empty expression';
SErrCommaExpected = 'Expected comma (,) at position %d, but got %s';
SErrInvalidNumberChar = 'Unexpected character in number : %s';
SErrInvalidNumber = 'Invalid numerical value : %s';
SErrNoOperand = 'No operand for unary operation %s';
SErrNoleftOperand = 'No left operand for binary operation %s';
SErrNoRightOperand = 'No right operand for binary operation %s';
SErrNoNegation = 'Cannot negate expression of type %s : %s';
SErrNoNOTOperation = 'Cannot perform "not" on expression of type %s: %s';
SErrTypesDoNotMatch = 'Type mismatch: %s<>%s for expressions "%s" and "%s".';
SErrTypesIncompatible = 'Incompatible types: %s<>%s for expressions "%s" and "%s".';
SErrNoNodeToCheck = 'Internal error: No node to check !';
SInvalidNodeType = 'Node type (%s) not in allowed types (%s) for expression: %s';
SErrUnterminatedExpression = 'Badly terminated expression. Found token at position %d : %s';
SErrDuplicateIdentifier = 'An identifier with name "%s" already exists.';
SErrInvalidResultCharacter = '"%s" is not a valid return type indicator';
ErrInvalidArgumentCount = 'Invalid argument count for function %s';
SErrInvalidArgumentType = 'Invalid type for argument %d: Expected %s, got %s';
SErrInvalidResultType = 'Invalid result type: %s';
SErrNotVariable = 'Identifier %s is not a variable';
SErrInactive = 'Operation not allowed while an expression is active';
SErrIFNeedsBoolean = 'First argument to IF must be of type boolean: %s';
SErrCaseNeeds3 = 'Case statement needs to have at least 4 arguments';
SErrCaseEvenCount = 'Case statement needs to have an even number of arguments';
SErrCaseLabelNotAConst = 'Case label %d "%s" is not a constant expression';
SErrCaseLabelType = 'Case label %d "%s" needs type %s, but has type %s';
SErrCaseValueType = 'Case value %d "%s" needs type %s, but has type %s';
{ ---------------------------------------------------------------------
Auxiliary functions
---------------------------------------------------------------------}
Procedure RaiseParserError(Msg : String);
begin
Raise EExprParser.Create(Msg);
end;
Procedure RaiseParserError(Fmt : String; Args : Array of const);
begin
Raise EExprParser.CreateFmt(Fmt,Args);
end;
Function TokenName (AToken : TTokenType) : String;
begin
Result:=GetEnumName(TypeInfo(TTokenType),Ord(AToken));
end;
Function ResultTypeName (AResult : TResultType) : String;
begin
Result:=GetEnumName(TypeInfo(TResultType),Ord(AResult));
end;
function CharToResultType(C: Char): TResultType;
begin
Case Upcase(C) of
'S' : Result:=rtString;
'D' : Result:=rtDateTime;
'B' : Result:=rtBoolean;
'I' : Result:=rtInteger;
'F' : Result:=rtFloat;
else
RaiseParserError(SErrInvalidResultCharacter,[C]);
end;
end;
Var
BuiltIns : TExprBuiltInManager;
Function BuiltinIdentifiers : TExprBuiltInManager;
begin
If (BuiltIns=Nil) then
BuiltIns:=TExprBuiltInManager.Create(Nil);
Result:=BuiltIns;
end;
Procedure FreeBuiltIns;
begin
FreeAndNil(Builtins);
end;
{ ---------------------------------------------------------------------
TFPExpressionScanner
---------------------------------------------------------------------}
function TFPExpressionScanner.IsAlpha(C: Char): Boolean;
begin
Result := C in ['A'..'Z', 'a'..'z'];
end;
constructor TFPExpressionScanner.Create;
begin
Source:='';
end;
procedure TFPExpressionScanner.SetSource(const AValue: String);
begin
FSource:=AValue;
LSource:=Length(FSource);
FTokenType:=ttEOF;
If LSource=0 then
FPos:=0
else
FPos:=1;
FChar:=Pchar(FSource);
FToken:='';
end;
function TFPExpressionScanner.NextPos: Char;
begin
Inc(FPos);
Inc(FChar);
Result:=FChar^;
end;
function TFPExpressionScanner.IsWordDelim(C: Char): Boolean;
begin
Result:=C in WordDelimiters;
end;
function TFPExpressionScanner.IsDelim(C: Char): Boolean;
begin
Result:=C in Delimiters;
end;
function TFPExpressionScanner.IsDigit(C: Char): Boolean;
begin
Result:=C in Digits;
end;
Procedure TFPExpressionScanner.SkipWhiteSpace;
begin
While (FChar^ in WhiteSpace) and (FPos<=LSource) do
NextPos;
end;
Function TFPExpressionScanner.DoDelimiter : TTokenType;
Var
B : Boolean;
C,D : Char;
begin
C:=FChar^;
FToken:=C;
B:=C in ['<','>'];
D:=C;
C:=NextPos;
if B and (C in ['=','>']) then
begin
FToken:=FToken+C;
NextPos;
If (D='>') then
Result:=ttLargerThanEqual
else if (C='>') then
Result:=ttUnequal
else
Result:=ttLessThanEqual;
end
else
Case D of
'+' : Result := ttPlus;
'-' : Result := ttMinus;
'<' : Result := ttLessThan;
'>' : Result := ttLargerThan;
'=' : Result := ttEqual;
'/' : Result := ttDiv;
'*' : Result := ttMul;
'(' : Result := ttLeft;
')' : Result := ttRight;
',' : Result := ttComma;
'^' : Result := ttPower;
else
ScanError(Format(SUnknownDelimiter,[D]));
end;
end;
Procedure TFPExpressionScanner.ScanError(Msg : String);
begin
Raise EExprScanner.Create(Msg)
end;
Function TFPExpressionScanner.DoString : TTokenType;
Function TerminatingChar(C : Char) : boolean;
begin
Result:=(C=cNull) or
((C=cSingleQuote) and
Not ((FPos<LSource) and (FSource[FPos+1]=cSingleQuote)));
end;
Var
C : Char;
begin
FToken := '';
C:=NextPos;
while not TerminatingChar(C) do
begin
FToken:=FToken+C;
If C=cSingleQuote then
NextPos;
C:=NextPos;
end;
if (C=cNull) then
ScanError(SBadQuotes);
Result := ttString;
FTokenType:=Result;
NextPos;
end;
function TFPExpressionScanner.GetCurrentChar: Char;
begin
If FChar<>Nil then
Result:=FChar^
else
Result:=#0;
end;
Function TFPExpressionScanner.DoNumber : TTokenType;
Var
C : Char;
X : TExprFloat;
I : Integer;
prevC: Char;
begin
C:=CurrentChar;
prevC := #0;
while (not IsWordDelim(C) or (prevC='E')) and (C<>cNull) do
begin
If Not ( IsDigit(C)
or ((FToken<>'') and (Upcase(C)='E'))
or ((FToken<>'') and (C in ['+','-']) and (prevC='E'))
)
then
ScanError(Format(SErrInvalidNumberChar,[C]));
FToken := FToken+C;
prevC := Upcase(C);
C:=NextPos;
end;
Val(FToken,X,I);
If (I<>0) then
ScanError(Format(SErrInvalidNumber,[FToken]));
Result:=ttNumber;
end;
Function TFPExpressionScanner.DoIdentifier : TTokenType;
Var
C : Char;
S : String;
begin
C:=CurrentChar;
while (not IsWordDelim(C)) and (C<>cNull) do
begin
FToken:=FToken+C;
C:=NextPos;
end;
S:=LowerCase(Token);
If (S='or') then
Result:=ttOr
else if (S='xor') then
Result:=ttXOr
else if (S='and') then
Result:=ttAnd
else if (S='true') then
Result:=ttTrue
else if (S='false') then
Result:=ttFalse
else if (S='not') then
Result:=ttnot
else if (S='if') then
Result:=ttif
else if (S='case') then
Result:=ttcase
else
Result:=ttIdentifier;
end;