-
Notifications
You must be signed in to change notification settings - Fork 3
/
TemplatePro.pas
2822 lines (2614 loc) · 81.3 KB
/
TemplatePro.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
// ***************************************************************************
//
// Copyright (c) 2016-2024 Daniele Teti
//
// https://github.com/danieleteti/templatepro
//
// ***************************************************************************
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ***************************************************************************
unit TemplatePro;
interface
uses
System.Generics.Collections,
System.Classes,
System.SysUtils,
System.TypInfo,
Data.DB,
System.DateUtils,
System.RTTI;
const
TEMPLATEPRO_VERSION = '0.6';
type
ETProException = class(Exception)
end;
ETProCompilerException = class(ETProException)
end;
ETProRenderException = class(ETProException)
end;
ETProDuckTypingException = class(ETProException)
end;
TIfThenElseIndex = record
IfIndex, ElseIndex: Int64;
end;
TTokenType = (
ttContent, ttInclude, ttFor, ttEndFor, ttIfThen, ttBoolExpression, ttElse, ttEndIf, ttStartTag, ttComment,
ttLiteralString, ttEndTag, ttValue, ttFilterName, ttFilterParameter, ttLineBreak, ttSystemVersion, ttEOF);
const
TOKEN_TYPE_DESCR: array [Low(TTokenType)..High(TTokenType)] of string =
('ttContent', 'ttInclude', 'ttFor', 'ttEndFor', 'ttIfThen', 'ttBoolExpression', 'ttElse', 'ttEndIf', 'ttStartTag', 'ttComment',
'ttLiteralString', 'ttEndTag', 'ttValue', 'ttFilterName', 'ttFilterParameter', 'ttLineBreak', 'ttSystemVersion', 'ttEOF');
type
TToken = packed record
TokenType: TTokenType;
Value1: String;
Value2: String;
Ref1, Ref2: Int64;
class function Create(TokType: TTokenType; Value1: String; Value2: String; Ref1: Int64 = -1; Ref2: Int64 = -1): TToken; static;
function TokenTypeAsString: String;
function ToString: String;
procedure SaveToBytes(const aBytes: TBinaryWriter);
class function CreateFromBytes(const aBytes: TBinaryReader): TToken; static;
end;
TTokenWalkProc = reference to procedure(const Index: Integer; const Token: TToken);
TTProTemplateFunction = function(const aValue: TValue; const aParameters: TArray<string>): TValue;
TTProVariablesInfo = (viSimpleType, viObject, viDataSet, viListOfObject, viJSONObject, viIterable);
TTProVariablesInfos = set of TTProVariablesInfo;
TVarDataSource = class
protected
VarValue: TValue;
VarOption: TTProVariablesInfos;
constructor Create(const VarValue: TValue; const VarOption: TTProVariablesInfos);
end;
TTProVariables = class(TObjectDictionary<string, TVarDataSource>)
public
constructor Create;
end;
TTProCompiledTemplateGetValueEvent = reference to procedure(const DataSource, Members: string; var Value: TValue; var Handled: Boolean);
ITProCompiledTemplate = interface
['{0BE04DE7-6930-456B-86EE-BFD407BA6C46}']
function Render: String;
procedure ForEachToken(const TokenProc: TTokenWalkProc);
procedure ClearData;
procedure SetData(const Name: String; Value: TValue); overload;
procedure AddFilter(const FunctionName: string; const FunctionImpl: TTProTemplateFunction);
procedure DumpToFile(const FileName: String);
procedure SaveToFile(const FileName: String);
function GetOnGetValue: TTProCompiledTemplateGetValueEvent;
procedure SetOnGetValue(const Value: TTProCompiledTemplateGetValueEvent);
property OnGetValue: TTProCompiledTemplateGetValueEvent read GetOnGetValue write SetOnGetValue;
end;
TTProCompiledTemplateEvent = reference to procedure(const TemplateProCompiledTemplate: ITProCompiledTemplate);
TLoopStackItem = class
protected
DataSourceName: String;
LoopExpression: String;
FullPath: String;
IteratorName: String;
IteratorPosition: Integer;
function IncrementIteratorPosition: Integer;
constructor Create(DataSourceName: String; LoopExpression: String; FullPath: String; IteratorName: String);
end;
TTProCompiledTemplate = class(TInterfacedObject, ITProCompiledTemplate)
private
fTokens: TList<TToken>;
fVariables: TTProVariables;
fTemplateFunctions: TDictionary<string, TTProTemplateFunction>;
fLoopsStack: TObjectList<TLoopStackItem>;
fOnGetValue: TTProCompiledTemplateGetValueEvent;
function PeekLoop: TLoopStackItem;
procedure PopLoop;
procedure PushLoop(const LoopStackItem: TLoopStackItem);
function LoopStackIsEmpty: Boolean;
function WalkThroughLoopStack(const VarName: String; out BaseVarName: String; out FullPath: String): Boolean;
constructor Create(Tokens: TList<TToken>);
procedure Error(const aMessage: String); overload;
procedure Error(const aMessage: String; const Params: array of const); overload;
function IsTruthy(const Value: TValue): Boolean;
function GetVarAsString(const Name: string): string;
function GetTValueVarAsString(const Value: TValue; const VarName: string = ''): String;
function GetVarAsTValue(const aName: string): TValue;
// function EvaluateIfExpression(aIdentifier: string): Boolean;
function EvaluateIfExpressionAt(var Idx: UInt64): Boolean;
function GetVariables: TTProVariables;
procedure SplitVariableName(const VariableWithMember: String; out VarName, VarMembers: String);
function ExecuteFilter(aFunctionName: string; aParameters: TArray<string>; aValue: TValue): TValue;
procedure CheckParNumber(const aHowManyPars: Integer; const aParameters: TArray<string>); overload;
procedure CheckParNumber(const aMinParNumber, aMaxParNumber: Integer; const aParameters: TArray<string>); overload;
function GetPseudoVariable(const VarIterator: Integer; const PseudoVarName: String): TValue; overload;
function IsAnIterator(const VarName: String; out DataSourceName: String; out CurrentIterator: TLoopStackItem): Boolean;
function GetOnGetValue: TTProCompiledTemplateGetValueEvent;
function EvaluateValue(var Idx: UInt64; out MustBeEncoded: Boolean): TValue;
procedure SetOnGetValue(const Value: TTProCompiledTemplateGetValueEvent);
procedure DoOnGetValue(const DataSource, Members: string; var Value: TValue; var Handled: Boolean);
public
destructor Destroy; override;
function Render: String;
procedure ForEachToken(const TokenProc: TTokenWalkProc);
procedure ClearData;
procedure SaveToFile(const FileName: String);
class function CreateFromFile(const FileName: String): ITProCompiledTemplate;
procedure SetData(const Name: String; Value: TValue); overload;
procedure AddFilter(const FunctionName: string; const FunctionImpl: TTProTemplateFunction);
procedure DumpToFile(const FileName: String);
property OnGetValue: TTProCompiledTemplateGetValueEvent read GetOnGetValue write SetOnGetValue;
end;
TTProCompiler = class
strict private
function MatchStartTag: Boolean;
function MatchEndTag: Boolean;
function MatchVariable(var aIdentifier: string): Boolean;
function MatchFilterParamValue(var aParamValue: string): Boolean;
function MatchSymbol(const aSymbol: string): Boolean;
function MatchSpace: Boolean;
function MatchString(out aStringValue: string): Boolean;
procedure InternalMatchFilter(lIdentifier: String; var lStartVerbatim: UInt64; const CurrToken: TTokenType; aTokens: TList<TToken>; const lRef2: Integer);
function GetFunctionParameters: TArray<String>;
private
fInputString: string;
fCharIndex: Int64;
fCurrentLine: Integer;
fEncoding: TEncoding;
fCurrentFileName: String;
procedure Error(const aMessage: string);
function Step: Char;
function CurrentChar: Char;
function GetSubsequentText: String;
procedure InternalCompileIncludedTemplate(const aTemplate: string; const aTokens: TList<TToken>; const aFileNameRefPath: String);
procedure FixJumps(const aTokens: TList<TToken>);
procedure Compile(const aTemplate: string; const aTokens: TList<TToken>; const aFileNameRefPath: String); overload;
public
function Compile(const aTemplate: string; const aFileNameRefPath: String = ''): ITProCompiledTemplate; overload;
constructor Create(aEncoding: TEncoding = nil);
end;
ITProWrappedList = interface
['{C1963FBF-1E42-4E2A-A17A-27F3945F13ED}']
function GetItem(const AIndex: Integer): TObject;
procedure Add(const AObject: TObject);
function Count: Integer;
procedure Clear;
function IsWrappedList: Boolean; overload;
function ItemIsObject(const AIndex: Integer; out AValue: TValue): Boolean;
end;
TTProConfiguration = class sealed
private
class var fOnContextConfiguration: TTProCompiledTemplateEvent;
protected
class procedure RegisterHandlers(const TemplateProCompiledTemplate: ITProCompiledTemplate);
public
class property OnContextConfiguration: TTProCompiledTemplateEvent read fOnContextConfiguration write fOnContextConfiguration;
end;
function HTMLEncode(s: string): string;
function HTMLSpecialCharsEncode(s: string): string;
implementation
uses
System.StrUtils, System.IOUtils, System.NetEncoding, System.Math,
JsonDataObjects, MVCFramework.Nullables;
const
Sign = ['-','+'];
Numbers = ['0'..'9'];
SignAndNumbers = Sign + Numbers;
IdenfierAllowedFirstChars = ['a' .. 'z', 'A' .. 'Z', '_', '@'];
IdenfierAllowedChars = ['a' .. 'z', 'A' .. 'Z', '_'] + Numbers;
ValueAllowedChars = IdenfierAllowedChars + [' ', '-', '+', '*', '.', '@', '/', '\']; // maybe a lot others
START_TAG = '{{';
END_TAG = '}}';
type
TTProRTTIUtils = class sealed
public
class function GetProperty(AObject: TObject; const APropertyName: string): TValue;
end;
TTProDuckTypedList = class(TInterfacedObject, ITProWrappedList)
private
FObjectAsDuck: TObject;
FObjType: TRttiType;
FAddMethod: TRttiMethod;
FClearMethod: TRttiMethod;
FCountProperty: TRttiProperty;
FGetItemMethod: TRttiMethod;
FGetCountMethod: TRttiMethod;
protected
procedure Add(const AObject: TObject);
procedure Clear;
function ItemIsObject(const AIndex: Integer; out AValue: TValue): Boolean;
public
constructor Create(const AObjectAsDuck: TObject); overload;
constructor Create(const AInterfaceAsDuck: IInterface); overload;
function IsWrappedList: Boolean; overload;
function Count: Integer;
procedure GetItemAsTValue(const AIndex: Integer; out AValue: TValue);
function GetItem(const AIndex: Integer): TObject;
class function CanBeWrappedAsList(const AObjectAsDuck: TObject): Boolean; overload; static;
class function CanBeWrappedAsList(const AObjectAsDuck: TObject; out AMVCList: ITProWrappedList): Boolean; overload; static;
class function CanBeWrappedAsList(const AInterfaceAsDuck: IInterface): Boolean; overload; static;
class function Wrap(const AObjectAsDuck: TObject): ITProWrappedList; static;
end;
var
GlContext: TRttiContext;
function WrapAsList(const AObject: TObject): ITProWrappedList;
begin
Result := TTProDuckTypedList.Wrap(AObject);
end;
{ TParser }
procedure TTProCompiledTemplate.AddFilter(const FunctionName: string; const FunctionImpl: TTProTemplateFunction);
begin
fTemplateFunctions.Add(FunctionName.ToLower, FunctionImpl);
end;
function TTProCompiledTemplate.GetOnGetValue: TTProCompiledTemplateGetValueEvent;
begin
Result := fOnGetValue;
end;
//function TTProCompiledTemplate.GetPseudoVariable(const Variable: TVarDataSource; const PseudoVarName: String): TValue;
//begin
// Result := GetPseudoVariable(Variable.VarIterator, PseudoVarName);
//end;
function TTProCompiledTemplate.GetPseudoVariable(const VarIterator: Integer; const PseudoVarName: String): TValue;
begin
if PseudoVarName = '@@index' then
begin
Result := VarIterator + 1;
end
else if PseudoVarName = '@@odd' then
begin
Result := (VarIterator + 1) mod 2 > 0;
end
else if PseudoVarName = '@@even' then
begin
Result := (VarIterator + 1) mod 2 = 0;
end
else
begin
Result := TValue.Empty;
end;
end;
function TTProCompiledTemplate.GetTValueVarAsString(const Value: TValue; const VarName: string): String;
var
lIsObject: Boolean;
lAsObject: TObject;
begin
if Value.IsEmpty then
begin
Exit('');
end;
lIsObject := False;
lAsObject := nil;
if Value.IsObject then
begin
lIsObject := True;
lAsObject := Value.AsObject;
end;
if lIsObject then
begin
if lAsObject is TField then
Result := TField(Value.AsObject).AsString
else if lAsObject is TJsonBaseObject then
Result := TJsonBaseObject(lAsObject).ToJSON()
else
Result := lAsObject.ToString;
end
else
begin
if Value.TypeInfo.Kind = tkRecord then
begin
if Value.TypeInfo = TypeInfo(NullableInt32) then
begin
Result := Value.AsType<NullableInt32>.Value.ToString;
end
else if Value.TypeInfo = TypeInfo(NullableUInt32) then
begin
Result := Value.AsType<NullableInt32>.Value.ToString;
end
else if Value.TypeInfo = TypeInfo(NullableInt16) then
begin
Result := Value.AsType<NullableInt16>.Value.ToString;
end
else if Value.TypeInfo = TypeInfo(NullableUInt16) then
begin
Result := Value.AsType<NullableUInt16>.Value.ToString;
end
else if Value.TypeInfo = TypeInfo(NullableInt64) then
begin
Result := Value.AsType<NullableInt64>.Value.ToString;
end
else if Value.TypeInfo = TypeInfo(NullableUInt64) then
begin
Result := Value.AsType<NullableUInt64>.Value.ToString;
end
else if Value.TypeInfo = TypeInfo(NullableString) then
begin
Result := Value.AsType<NullableString>.Value;
end
else if Value.TypeInfo = TypeInfo(NullableCurrency) then
begin
Result := Value.AsType<NullableCurrency>.Value.ToString;
end
else if Value.TypeInfo = TypeInfo(NullableBoolean) then
begin
Result := Value.AsType<NullableBoolean>.Value.ToString;
end
else if Value.TypeInfo = TypeInfo(NullableTDate) then
begin
Result := DateToISO8601(Value.AsType<NullableTDate>.Value);
end
else if Value.TypeInfo = TypeInfo(NullableTTime) then
begin
Result := DateToISO8601(Value.AsType<NullableTTime>.Value);
end
else if Value.TypeInfo = TypeInfo(NullableTDateTime) then
begin
Result := DateToISO8601(Value.AsType<NullableTDateTime>.Value);
end
else
begin
raise ETProException.Create('Unsupported type for variable "' + VarName + '"');
end;
end
else
begin
Result := Value.ToString;
end;
end;
end;
procedure TTProCompiledTemplate.CheckParNumber(const aMinParNumber, aMaxParNumber: Integer;
const aParameters: TArray<string>);
var
lParNumber: Integer;
begin
lParNumber := Length(aParameters);
if (lParNumber < aMinParNumber) or (lParNumber > aMaxParNumber) then
begin
if aMinParNumber = aMaxParNumber then
Error(Format('Expected %d parameters, got %d' , [aMinParNumber, lParNumber]))
else
Error(Format('Expected from %d to %d parameters, got %d', [aMinParNumber, aMaxParNumber, lParNumber]));
end;
end;
procedure TTProCompiler.InternalCompileIncludedTemplate(const aTemplate: string;
const aTokens: TList<TToken>; const aFileNameRefPath: String);
var
lCompiler: TTProCompiler;
begin
lCompiler := TTProCompiler.Create(fEncoding);
try
lCompiler.Compile(aTemplate, aTokens, aFileNameRefPath);
if aTokens[aTokens.Count - 1].TokenType <> ttEOF then
begin
Error('Included file ' + aFileNameRefPath + ' doesn''t terminate with EOF');
end;
aTokens.Delete(aTokens.Count - 1); // remove the EOF
finally
lCompiler.Free;
end;
end;
procedure TTProCompiler.InternalMatchFilter(lIdentifier: String; var lStartVerbatim: UInt64; const CurrToken: TTokenType; aTokens: TList<TToken>; const lRef2: Integer);
var
lFilterName: string;
lFilterParamsCount: Integer;
lFilterParams: TArray<String>;
I: Integer;
begin
lFilterName := '';
lFilterParamsCount := -1; {-1 means "no filter applied to value"}
if MatchSymbol('|') then
begin
if not MatchVariable(lFilterName) then
Error('Invalid function name applied to variable or literal string "' + lIdentifier + '"');
lFilterParams := GetFunctionParameters;
lFilterParamsCount := Length(lFilterParams);
end;
if not MatchEndTag then
begin
Error('Expected end tag "' + END_TAG + '" near ' + GetSubsequentText);
end;
lStartVerbatim := fCharIndex;
aTokens.Add(TToken.Create(CurrToken, lIdentifier, '', lFilterParamsCount, lRef2));
//add function with params
if not lFilterName.IsEmpty then
begin
aTokens.Add(TToken.Create(ttFilterName, lFilterName, '', lFilterParamsCount));
if lFilterParamsCount > 0 then
begin
for I := 0 to lFilterParamsCount -1 do
begin
aTokens.Add(TToken.Create(ttFilterParameter, lFilterParams[I], ''));
end;
end;
end;
end;
constructor TTProCompiler.Create(aEncoding: TEncoding = nil);
begin
inherited Create;
if aEncoding = nil then
fEncoding := TEncoding.UTF8 { default encoding }
else
fEncoding := aEncoding;
end;
function TTProCompiler.CurrentChar: Char;
begin
Result := fInputString.Chars[fCharIndex]
end;
function TTProCompiler.MatchEndTag: Boolean;
begin
Result := MatchSymbol(END_TAG);
end;
function TTProCompiler.MatchVariable(var aIdentifier: string): Boolean;
var
lTmp: String;
begin
aIdentifier := '';
lTmp := '';
Result := False;
if CharInSet(fInputString.Chars[fCharIndex], IdenfierAllowedFirstChars) then
begin
lTmp := fInputString.Chars[fCharIndex];
Inc(fCharIndex);
if lTmp = '@' then
begin
if fInputString.Chars[fCharIndex] = '@' then
begin
lTmp := '@@';
Inc(fCharIndex);
end;
end;
while CharInSet(fInputString.Chars[fCharIndex], IdenfierAllowedChars) do
begin
lTmp := lTmp + fInputString.Chars[fCharIndex];
Inc(fCharIndex);
end;
Result := True;
aIdentifier := lTmp;
end;
if Result then
begin
while MatchSymbol('.') do
begin
lTmp := '';
if not MatchVariable(lTmp) then
begin
Error('Expected identifier after "' + aIdentifier + '" - got ' + GetSubsequentText);
end;
aIdentifier := aIdentifier + '.' + lTmp;
end;
end;
end;
function TTProCompiler.MatchFilterParamValue(var aParamValue: string): Boolean;
var
lTmp: String;
begin
lTmp := '';
Result := False;
if MatchString(aParamValue) then
begin
Result := True;
end else if CharInSet(fInputString.Chars[fCharIndex], SignAndNumbers) then
begin
lTmp := fInputString.Chars[fCharIndex];
Inc(fCharIndex);
while CharInSet(fInputString.Chars[fCharIndex], Numbers) do
begin
lTmp := lTmp + fInputString.Chars[fCharIndex];
Inc(fCharIndex);
end;
Result := True;
aParamValue := lTmp.Trim;
end;
// if CharInSet(fInputString.Chars[fCharIndex], IdenfierAllowedChars) then
// begin
// while CharInSet(fInputString.Chars[fCharIndex], ValueAllowedChars) do
// begin
// lTmp := lTmp + fInputString.Chars[fCharIndex];
// Inc(fCharIndex);
// end;
// Result := True;
// aParamValue := lTmp.Trim;
// end;
end;
function TTProCompiler.MatchSpace: Boolean;
begin
Result := MatchSymbol(' ');
while MatchSymbol(' ') do;
end;
function TTProCompiler.MatchStartTag: Boolean;
begin
Result := MatchSymbol(START_TAG);
end;
function TTProCompiler.MatchString(out aStringValue: String): Boolean;
begin
aStringValue := '';
Result := MatchSymbol('"');
if Result then
begin
while not MatchSymbol('"') do //no escape so far
begin
if CurrentChar = #0 then
begin
Error('Unclosed string at the end of file');
end;
aStringValue := aStringValue + CurrentChar;
Step;
end;
end;
end;
function TTProCompiler.MatchSymbol(const aSymbol: string): Boolean;
var
lSymbolIndex: Integer;
lSavedCharIndex: Int64;
lSymbolLength: Integer;
begin
if aSymbol.IsEmpty then
Exit(True);
lSavedCharIndex := fCharIndex;
lSymbolIndex := 0;
lSymbolLength := Length(aSymbol);
while (fInputString.Chars[fCharIndex] = aSymbol.Chars[lSymbolIndex]) and (lSymbolIndex < lSymbolLength) do
begin
Inc(fCharIndex);
Inc(lSymbolIndex);
end;
Result := (lSymbolIndex > 0) and (lSymbolIndex = lSymbolLength);
if not Result then
fCharIndex := lSavedCharIndex;
end;
function TTProCompiler.Step: Char;
begin
Inc(fCharIndex);
Result := CurrentChar;
end;
function TTProCompiler.Compile(const aTemplate: string; const aFileNameRefPath: String): ITProCompiledTemplate;
var
lTokens: TList<TToken>;
lFileNameRefPath: string;
begin
if aFileNameRefPath.IsEmpty then
begin
lFileNameRefPath := TPath.Combine(TPath.GetDirectoryName(GetModuleName(HInstance)), 'main.template');
end
else
begin
lFileNameRefPath := TPath.GetFullPath(aFileNameRefPath);
end;
fCurrentFileName := lFileNameRefPath;
lTokens := TList<TToken>.Create;
try
Compile(aTemplate, lTokens, fCurrentFileName);
FixJumps(lTokens);
Result := TTProCompiledTemplate.Create(lTokens);
except
lTokens.Free;
raise;
end;
end;
procedure TTProCompiler.Compile(const aTemplate: string; const aTokens: TList<TToken>; const aFileNameRefPath: String);
var
lForStatementCount: Integer;
lIfStatementCount: Integer;
lLastToken: TTokenType;
lChar: Char;
lVarName: string;
lFuncName: string;
lIdentifier: string;
lIteratorName: string;
lStartVerbatim: UInt64;
lEndVerbatim: UInt64;
lNegation: Boolean;
lFuncParams: TArray<String>;
lFuncParamsCount: Integer;
I: Integer;
lIncludeFileContent: string;
lCurrentFileName: string;
lStringValue: string;
lRef2: Integer;
lContentOnThisLine: Integer;
begin
aTokens.Add(TToken.Create(ttSystemVersion, TEMPLATEPRO_VERSION, ''));
lLastToken := ttEOF;
lContentOnThisLine := 0;
fCurrentFileName := aFileNameRefPath;
fCharIndex := -1;
fCurrentLine := 1;
lIfStatementCount := -1;
lForStatementCount := -1;
fInputString := aTemplate;
lStartVerbatim := 0;
if fInputString.Length > 0 then
begin
Step;
end
else
begin
aTokens.Add(TToken.Create(ttEOF, '', ''));
fCharIndex := 1; {doesnt' execute while}
end;
while fCharIndex <= fInputString.Length do
begin
lChar := CurrentChar;
if lChar = #0 then //eof
begin
lEndVerbatim := fCharIndex;
if lEndVerbatim - lStartVerbatim > 0 then
begin
lLastToken := ttContent;
aTokens.Add(TToken.Create(lLastToken, fInputString.Substring(lStartVerbatim, lEndVerbatim - lStartVerbatim), ''));
end;
aTokens.Add(TToken.Create(ttEOF, '', ''));
Break;
end;
if MatchSymbol(sLineBreak) then {linebreak}
begin
lEndVerbatim := fCharIndex - Length(sLineBreak);
if lEndVerbatim - lStartVerbatim > 0 then
begin
Inc(lContentOnThisLine);
aTokens.Add(TToken.Create(ttContent, fInputString.Substring(lStartVerbatim, lEndVerbatim - lStartVerbatim), ''));
end;
lStartVerbatim := fCharIndex;
if lLastToken = ttLineBreak then Inc(lContentOnThisLine);
lLastToken := ttLineBreak;
if lContentOnThisLine > 0 then
begin
aTokens.Add(TToken.Create(lLastToken, '', ''));
end;
Inc(fCurrentLine);
lContentOnThisLine := 0;
end else if MatchStartTag then {starttag}
begin
lEndVerbatim := fCharIndex - Length(START_TAG);
if lEndVerbatim - lStartVerbatim > 0 then
begin
lLastToken := ttContent;
aTokens.Add(TToken.Create(lLastToken, fInputString.Substring(lStartVerbatim, lEndVerbatim - lStartVerbatim), ''));
end;
if CurrentChar = START_TAG[1] then
begin
lLastToken := ttContent;
aTokens.Add(TToken.Create(lLastToken, START_TAG, ''));
Inc(fCharIndex);
lStartVerbatim := fCharIndex;
Continue;
end;
if CurrentChar = ':' then //variable
begin
Step;
if MatchVariable(lVarName) then {variable}
begin
if lVarName.IsEmpty then
Error('Invalid variable name');
lFuncName := '';
lFuncParamsCount := -1; {-1 means "no filter applied to value"}
lRef2 := IfThen(MatchSymbol('$'),1,-1); // {{value$}} means no escaping
MatchSpace;
if MatchSymbol('|') then
begin
MatchSpace;
if not MatchVariable(lFuncName) then
Error('Invalid function name applied to variable ' + lVarName);
MatchSpace;
lFuncParams := GetFunctionParameters;
lFuncParamsCount := Length(lFuncParams);
MatchSpace;
end;
if not MatchEndTag then
begin
Error('Expected end tag "' + END_TAG + '" near ' + GetSubsequentText);
end;
lStartVerbatim := fCharIndex;
lLastToken := ttValue;
aTokens.Add(TToken.Create(lLastToken, lVarName, '', lFuncParamsCount, lRef2));
Inc(lContentOnThisLine);
//add function with params
if not lFuncName.IsEmpty then
begin
aTokens.Add(TToken.Create(ttFilterName, lFuncName, '', lFuncParamsCount));
if lFuncParamsCount > 0 then
begin
for I := 0 to lFuncParamsCount -1 do
begin
aTokens.Add(TToken.Create(ttFilterParameter, lFuncParams[I], ''));
end;
end;
end;
end; //matchvariable
end
else
begin
if MatchSymbol('for') then {loop}
begin
if not MatchSpace then
Error('Expected "space"');
if not MatchVariable(lIteratorName) then
Error('Expected iterator name after "for" - EXAMPLE: for iterator in iterable');
if not MatchSpace then
Error('Expected "space"');
if not MatchSymbol('in') then
Error('Expected "in" after "for" iterator');
if not MatchSpace then
Error('Expected "space"');
if not MatchVariable(lIdentifier) then
Error('Expected iterable "for"');
MatchSpace;
if not MatchEndTag then
Error('Expected closing tag for "for"');
// create another element in the sections stack
Inc(lForStatementCount);
lLastToken := ttFor;
if lIdentifier = lIteratorName then
begin
Error('loop data source and its iterator cannot have the same name: ' + lIdentifier)
end;
aTokens.Add(TToken.Create(lLastToken, lIdentifier, lIteratorName));
lStartVerbatim := fCharIndex;
end else if MatchSymbol('endfor') then {endfor}
begin
if not MatchEndTag then
Error('Expected closing tag');
if lForStatementCount = -1 then
begin
Error('endfor without loop');
end;
lLastToken := ttEndFor;
aTokens.Add(TToken.Create(lLastToken, '', ''));
Dec(lForStatementCount);
lStartVerbatim := fCharIndex;
end else if MatchSymbol('endif') then {endif}
begin
if lIfStatementCount = -1 then
begin
Error('"endif" without "if"');
end;
if not MatchEndTag then
begin
Error('Expected closing tag for "endif"');
end;
lLastToken := ttEndIf;
aTokens.Add(TToken.Create(lLastToken, '', ''));
Dec(lIfStatementCount);
lStartVerbatim := fCharIndex;
end else if MatchSymbol('if') then
begin
if not MatchSpace then
begin
Error('Expected <space> after "if"');
end;
lNegation := MatchSymbol('!');
MatchSpace;
if not MatchVariable(lIdentifier) then
Error('Expected identifier after "if"');
lFuncParamsCount := -1; {lFuncParamsCount = -1 means "no filter applied"}
lFuncName := '';
if MatchSymbol('|') then
begin
MatchSpace;
if not MatchVariable(lFuncName) then
Error('Invalid function name applied to variable ' + lVarName);
lFuncParams := GetFunctionParameters;
lFuncParamsCount := Length(lFuncParams);
end;
MatchSpace;
if not MatchEndTag then
Error('Expected closing tag for "if"');
if lNegation then
begin
lIdentifier := '!' + lIdentifier;
end;
lLastToken := ttIfThen;
aTokens.Add(TToken.Create(lLastToken, '' {lIdentifier}, ''));
Inc(lIfStatementCount);
lStartVerbatim := fCharIndex;
lLastToken := ttBoolExpression;
aTokens.Add(TToken.Create(lLastToken, lIdentifier, '', lFuncParamsCount, -1 {no html escape}));
//add function with params
if not lFuncName.IsEmpty then
begin
aTokens.Add(TToken.Create(ttFilterName, lFuncName, '', lFuncParamsCount));
if lFuncParamsCount > 0 then
begin
for I := 0 to lFuncParamsCount -1 do
begin
aTokens.Add(TToken.Create(ttFilterParameter, lFuncParams[I], ''));
end;
end;
end;
end else if MatchSymbol('else') then
begin
if not MatchEndTag then
Error('Expected closing tag for "else"');
lLastToken := ttElse;
aTokens.Add(TToken.Create(lLastToken, '', ''));
lStartVerbatim := fCharIndex;
end
else if MatchSymbol('include') then {include}
begin
if not MatchSpace then
Error('Expected "space" after "include"');
{In a future version we could implement a function call}
if not MatchString(lStringValue) then
begin
Error('Expected string after "include"');
end;
MatchSpace;
if not MatchEndTag then
Error('Expected closing tag for "include"');
// create another element in the sections stack
try
if TDirectory.Exists(aFileNameRefPath) then
begin
lCurrentFileName := TPath.GetFullPath(TPath.Combine(aFileNameRefPath, lStringValue));
end
else
begin
lCurrentFileName := TPath.GetFullPath(TPath.Combine(TPath.GetDirectoryName(aFileNameRefPath), lStringValue));
end;
lIncludeFileContent := TFile.ReadAllText(lCurrentFileName, fEncoding);
except
on E: Exception do
begin
Error('Cannot read "' + lStringValue + '"');
end;
end;
Inc(lContentOnThisLine);
InternalCompileIncludedTemplate(lIncludeFileContent, aTokens, lCurrentFileName);
lStartVerbatim := fCharIndex;
end
else if MatchSymbol('exit') then {exit}
begin
lLastToken := ttEOF;
aTokens.Add(TToken.Create(lLastToken, '', ''));
Break;
end
else if MatchString(lStringValue) then {string}
begin
lLastToken := ttLiteralString;
Inc(lContentOnThisLine);
lRef2 := IfThen(MatchSymbol('$'),1,-1); // {{value$}} means no escaping
MatchSpace;
InternalMatchFilter(lStringValue, lStartVerbatim, ttLiteralString, aTokens, lRef2);
end
else if MatchSymbol('#') then
begin
while not MatchEndTag do
begin
Step;
end;
lStartVerbatim := fCharIndex;
lLastToken := ttComment; {will not added into compiled template}
end
else
begin
lIdentifier := GetSubsequentText;
Error('Expected command, got "' + lIdentifier + '"');
end;
end;
end
else
begin
Step;
end;
end;
end;
function CapitalizeString(const s: string; const CapitalizeFirst: Boolean): string;
const
ALLOWEDCHARS = ['a' .. 'z', '_'];
var
index: Integer;
bCapitalizeNext: Boolean;
begin
bCapitalizeNext := CapitalizeFirst;
Result := lowercase(s);
if Result <> EmptyStr then
begin
for index := 1 to Length(Result) do