-
Notifications
You must be signed in to change notification settings - Fork 3
/
IniConfigs.pas
1160 lines (1024 loc) · 36.6 KB
/
IniConfigs.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) Peter Karpov 2010 - 2018.
Usage of the works is permitted provided that this instrument is retained with
the works, so that any entity that uses the works is notified of this instrument.
DISCLAIMER: THE WORKS ARE WITHOUT WARRANTY.
}
{$IFDEF FPC} {$MODE DELPHI} {$ENDIF}
unit IniConfigs; ////////////////////////////////////////////////////////////////////
{
>> Version: 1.3
>> Description
Unit for working with INI-style config files. Part of InvLibs unit collection.
>> Author
Peter Karpov
Email : [email protected]
Homepage : inversed.ru
GitHub : inversed-ru
Twitter : @inversed_ru
>> Usage
There are two ways to get values from configs.
1. Load a config from file with LoadConfig, then use getters to get individual
properties. You'll have to do all error checking yourself.
2. Make a load table by initializing a TLoadTable variable with InitLoadTable and
add all your variables to it using AddLoadParam. You can specify specific error-
checking functions for each variable or pass a nil if no checking is needed.
Finally call LoadFromConfig and it will try to load all your variables and return
a list of errors.
>> Performance
Hash tables are used for searching sections and properties, so performance on
large files is adequate.
>> Design decisions
While it is possible to support loading into variables of other types (byte,
smallint, single, ...), it leads to horrible amount of copypasta.
>> ToDo
- Describe config format in details
- Parameters with SI prefixes and dimensionality
- Support for fractions and thousand separators
- Saving TIniConfig to a file (requires saving all the comments intact)
>> Changelog
1.3 : 2018.09.09 ~ FreePascal compatibility
~ Arrays 1.2 compatibility
+ Missing routine comments
1.2.3 : 2011.10.14 ~ Moved to generic types
1.2 : 2011.04.02 * Case-sensitivity when reading booleans
1.1 : 2011.03.18 ~ StringUtils 2.0 compatibility
1.0 : 2011.03.06 + Stable fully featured version
+ Config loading, access to individual properties
+ Automated loading of properties into user variables
~ Uses universal lexer
~ Hash tables for section and property search
0.0 : 2011.02.01 + Work on the unit started
Notation: + added, - removed, * fixed, ~ changed
}
interface ///////////////////////////////////////////////////////////////////////////
uses
StringUtils,
StringLists,
HashTables,
HashFunctions,
Lexer;
type
TTokenPosition = TLexemePosition;
TPropertyType = (ptInt, ptReal, ptString, ptBool);
TPropertyValue =
record
PropertyType : TPropertyType;
IntValue : Integer;
RealValue : Real;
BoolValue : Boolean;
StringValue : AnsiString;
end;
TProperty =
record
Name : AnsiString;
Value : TPropertyValue;
Position : TTokenPosition;
end;
TProperties = array of TProperty;
PProperties = ^TProperties;
TSection =
record
Name : AnsiString;
NProperties : Integer;
Properties : TProperties;
HashProperties : THashTable;
end;
TSections = array of TSection;
PSections = ^TSections;
TIniConfig =
record
NSections : Integer;
Sections : TSections;
HashSections : THashTable;
end;
TPascalType = (
pasInteger, pasReal, pasBoolean, pasString, pasOther);
TLoadParameter =
record
ptrVar : Pointer;
VarType : TPascalType;
CfgPath : AnsiString;
ptrCheck : Pointer;
end;
TLoadTable = array of TLoadParameter;
ProcCheckInt = function(
VarInt : Integer
) : AnsiString;
ProcCheckReal = function(
VarReal : Real
) : AnsiString;
ProcCheckString = function(
VarString : AnsiString
) : AnsiString;
ProcOtherVar = function(
ptrVar : Pointer;
const S : AnsiString
) : AnsiString;
{-----------------------<< Parse, load >>-------------------------------------------}
// Load the Config file located at Path, return the Errors
procedure LoadConfig(
var Config : TIniConfig;
const Path : AnsiString;
var Errors : TStringList);
{-----------------------<< Getters >>-----------------------------------------------}
// Get the value of a property with FullName stored in Config or
// return Fail if it does not exist
function GetIntProperty(
var IntValue : Integer;
const Config : TIniConfig;
FullName : AnsiString
) : Boolean;
function GetRealProperty(
var RealValue : Real;
const Config : TIniConfig;
FullName : AnsiString
) : Boolean;
function GetBoolProperty(
var BoolValue : Boolean;
const Config : TIniConfig;
FullName : AnsiString
) : Boolean;
function GetStringProperty(
var StringValue : AnsiString;
const Config : TIniConfig;
FullName : AnsiString
) : Boolean;
{-----------------------<< Load tables >>-------------------------------------------}
// Initialize LoadTable
procedure InitLoadTable(
var LoadTable : TLoadTable);
// Load the variables specified in LoadTable from Config, return the Errors
procedure LoadFromConfig(
const LoadTable : TLoadTable;
const Config : TIniConfig;
var Errors : TStringList);
overload;
// Load the variables specified in LoadTable from a config file located at
// PathConfig, return the Errors
procedure LoadFromConfig(
const LoadTable : TLoadTable;
const PathConfig : AnsiString;
var Errors : TStringList);
overload;
{-----------------------<< Adding variables to a load table >>----------------------}
// Add a Variable with config file path CfgPath to the LoadTable. ProcCheck
// will be used during the loading to check the validity of the Variable.
procedure AddLoadParam(
var LoadTable : TLoadTable;
var Variable : Integer;
const CfgPath : AnsiString;
ProcCheck : ProcCheckInt);
overload;
procedure AddLoadParam(
var LoadTable : TLoadTable;
var Variable : Real;
const CfgPath : AnsiString;
ProcCheck : ProcCheckReal);
overload;
procedure AddLoadParam(
var LoadTable : TLoadTable;
var Variable : Boolean;
const CfgPath : AnsiString);
overload;
procedure AddLoadParam(
var LoadTable : TLoadTable;
var Variable : AnsiString;
const CfgPath : AnsiString;
ProcCheck : ProcCheckString);
overload;
// Add a variable pointed at by ptrVar with config file path CfgPath to the
// LoadTable. Process will be used during the loading to process the variable and
// check its validity.
procedure AddLoadParam(
var LoadTable : TLoadTable;
ptrVar : Pointer;
const CfgPath : AnsiString;
Process : ProcOtherVar);
overload;
{-----------------------<< Tests >>-------------------------------------------------}
// Create a random config file consisting of Size lines and located at Path
procedure MakeRandomConfig(
const Path : AnsiString;
Size : Integer);
implementation //////////////////////////////////////////////////////////////////////
uses
invSys,
Arrays,
RandVars,
Math;
type
TTokenType = (
tokEnd, tokDelimiter, tokSection, tokIdentifier,
tokInt, tokReal, tokString, tokBool);
TTokenValue =
record
IntValue : Integer;
RealValue : Real;
BoolValue : Boolean;
StringValue : AnsiString;
end;
TToken =
record
TokenType : TTokenType;
Value : TTokenValue;
Position : TTokenPosition;
end;
PToken = ^TToken;
TTokenStream =
record
N, iNowToken : Integer;
_ : array of TToken;
end;
PTokenStream = ^TTokenStream;
TSectionIndex = Integer;
TPropertyIndex = Integer;
const
InvalidSection = -1;
InvalidProperty = -1;
TokensValue = [tokInt, tokReal, tokBool, tokString];
Delimiter = '=';
Quote = '"';
Comment = ';';
OpenBracket = '[';
CloseBracket = ']';
DecimalDot = '.';
SectionDelimiter = '.';
ConstYes = 'yes';
ConstNo = 'no';
SymbolsFirstNumber = ['0' .. '9', '.', '-'];
SymbolsNumber = ['0' .. '9', '.', '-', '+', 'e', 'E'];
SymbolsIdentifier = ['a' .. 'z', 'A' .. 'Z', '0' .. '9', '_'];
Whitespace = [#0 .. ' '];
WhitespaceExceptBreaks = [#0 .. #9, #11, #12, #14 .. ' '];
ControlChars = [#0 .. #31];
LineBreaks = [#10, #13];
LineBreak = #10;
{-----------------------<< Lexer functions >>---------------------------------------}
// Return the address of the next token, allocate extra space if necessary
function GetNextTokenAddress(
ptrTokens : Pointer
) : Pointer;
var
Tokens : PTokenStream;
begin
Tokens := PTokenStream(ptrTokens);
Inc(Tokens.N);
if Tokens.N > Length(Tokens._) then
SetLength(Tokens._, 2 * Tokens.N);
Result := @Tokens._[Tokens.N - 1];
end;
// Classify a single-delimited Lexeme into a token
function ProcessSingleDelim(
ptrToken : Pointer;
const Lexeme : AnsiString;
const Position : TLexemePosition
) : AnsiString;
var
Token : PToken;
ErrorCodeInt,
ErrorCodeReal : Integer;
const
ErrorUnknownLexeme = 'unknown lexeme';
ErrorBadConstant = 'malformed constant';
begin
Result := '';
Token := PToken(ptrToken);
Token.Position := Position;
// Delimiter
if Lexeme[1] = Delimiter then
Token.TokenType := tokDelimiter
// Number
else if Lexeme[1] in SymbolsFirstNumber then
begin
Val(Lexeme, Token.Value. IntValue, ErrorCodeInt);
Val(Lexeme, Token.Value.RealValue, ErrorCodeReal);
if ErrorCodeReal = 0 then
begin
if ErrorCodeInt = 0 then
Token.TokenType := tokInt
else
Token.TokenType := tokReal;
end
else
Result := ErrorBadConstant;
end
// Identifier
else if Lexeme[1] in SymbolsIdentifier then
// Boolean constant
if SameText(Lexeme, ConstYes) or SameText(Lexeme, ConstNo) then
begin
Token.TokenType := tokBool;
Token.Value.BoolValue := SameText(Lexeme, ConstYes);
end
else
// Property
begin
Token.TokenType := tokIdentifier;
Token.Value.StringValue := Lexeme;
end
else
Result := ErrorUnknownLexeme;
end;
// Classify a pair-delimited lexeme into a token
function ProcessPairDelim(
ptrToken : Pointer;
const Lexeme : AnsiString;
const Position : TLexemePosition;
const DelimOpen,
DelimClose : AnsiString
) : AnsiString;
var
Token : PToken;
TempS : AnsiString;
const
ErrorUnknownLexeme = 'unknown lexeme';
ErrorBadSectionName = 'bad section name';
begin
Result := '';
Token := PToken(ptrToken);
Token.Position := Position;
// String
if (DelimOpen = Quote) and (DelimClose = Quote) then
begin
Token.TokenType := tokString;
Token.Value.StringValue := Lexeme;
end
// Section
else if (DelimOpen = OpenBracket) and
(DelimClose = CloseBracket) then
begin
Token.TokenType := tokSection;
TempS := Lexeme;
TrimWhitespaceSides(TempS);
if ContainsWhitespace(TempS) then
Result := ErrorBadSectionName
else
Token.Value.StringValue := TempS;
end
else
Result := ErrorUnknownLexeme;
end;
// Set the config language Delimiters for use by the lexer
procedure SetDelimiters(
var Delimiters : TDelimiters);
const
LineBreak = #10;
begin
InitDelimiters(Delimiters);
AddWhitespace(Delimiters);
AddSingleDelimiter(Delimiters, '=', {Skip:} False);
AddPairedDelimiter(
Delimiters,
Quote, {SkipOpen :} True,
Quote, {SkipClose :} True,
pairDoubleEscaped, {SkipInside:} False);
AddPairedDelimiter(
Delimiters,
';', {SkipOpen :} True,
LineBreak, {SkipClose :} True,
pairNonNesting, {SkipInside:} True);
AddPairedDelimiter(
Delimiters,
OpenBracket, {SkipOpen :} True,
CloseBracket, {SkipClose :} True,
pairNonNesting, {SkipInside:} False);
end;
// Set the procedures LexerProcs required by the lexer
procedure SetLexerProcs(
var LexerProcs : TLexerProcs);
begin
LexerProcs.GetNextTokenAddress := GetNextTokenAddress;
LexerProcs.ProcessSingleDelim := ProcessSingleDelim;
LexerProcs.ProcessPairDelim := ProcessPairDelim;
end;
{-----------------------<< Tokens >>------------------------------------------------}
// Initialize the tokens
procedure InitTokens(
var Tokens : TTokenStream);
begin
Tokens.N := 0;
Tokens.iNowToken := 0;
SetLength(Tokens._, 0);
end;
// Get the next Token from Tokens and return Success,
// or return Fail if the last token has been reached
function GetNextToken(
var Token : TToken;
var Tokens : TTokenStream
) : Boolean;
begin
with Tokens do
if iNowToken < N then
begin
Token := Tokens._[iNowToken];
Inc(iNowToken);
Result := Success;
end
else
Result := Fail;
end;
{-----------------------<< Sections >>----------------------------------------------}
// Return whether the section with a given Index at ptrSections^ is
// the same as ptrName^
function EqualSections(
ptrSections : Pointer;
Index : TObjectIndex;
ptrName : Pointer
) : Boolean;
begin
Result := PSections(ptrSections)^[Index].Name = PAnsiString(ptrName)^;
end;
// Return the index of a section with given SectionName in the Config or
// InvalidSection if it does not exist
function FindSection(
const Config : TIniConfig;
const SectionName : AnsiString
) : TSectionIndex;
begin
if LookupHashTable(
Result, @Config.Sections, Config.HashSections,
@SectionName, HashBernstein(SectionName), EqualSections) = Fail then
Result := InvalidSection;
end;
// Add a section with a given SectionName to the Config,
// or return Fail if it already exists
function AddSection(
var Config : TIniConfig;
const SectionName : AnsiString
) : Boolean;
begin
if FindSection(Config, SectionName) = InvalidSection then with Config do
begin
AddToHashTable( HashSections, NSections, HashBernstein(SectionName) );
Inc(NSections);
if Length(Sections) < NSections then
SetLength(Sections, 2 * NSections);
with Sections[NSections - 1] do
begin
Name := SectionName;
NProperties := 0;
SetLength(Properties, 0);
InitHashTable(HashProperties);
end;
Result := Success;
end
else
Result := Fail;
end;
{-----------------------<< Properties >>--------------------------------------------}
// Return whether the property with a given Index at ptrProperties^ is
// the same as ptrName^
function EqualProperties(
ptrProperties : Pointer;
Index : TObjectIndex;
ptrName : Pointer
) : Boolean;
begin
Result := PProperties(ptrProperties)^[Index].Name = PAnsiString(ptrName)^;
end;
// Return the index of a property with given PropertyName in the Config section
// specified by SectionIndex or InvalidProperty if it does not exist
function FindProperty(
const Config : TIniConfig;
SectionIndex : TSectionIndex;
const PropertyName : AnsiString
) : TPropertyIndex;
begin
with Config.Sections[SectionIndex] do
if LookupHashTable(
Result, @Properties, HashProperties,
@PropertyName, HashBernstein(PropertyName), EqualProperties) = Fail then
Result := InvalidProperty;
end;
// Add a property with given name and value to the Config section
// specified by SectionIndex, or return Fail if it already exists
function AddProperty(
var Config : TIniConfig;
SectionIndex : TSectionIndex;
const PropertyName : AnsiString;
const TokenValue : TToken
) : Boolean;
begin
Assert(TokenValue.TokenType in TokensValue, 'Non-value token');
Assert(SectionIndex < Config.NSections, 'Invalid section index');
if FindProperty(Config, SectionIndex, PropertyName) = InvalidProperty then
with Config.Sections[SectionIndex] do
begin
AddToHashTable( HashProperties, NProperties, HashBernstein(PropertyName) );
Inc(NProperties);
if NProperties > Length(Properties) then
SetLength(Properties, 2 * NProperties);
Properties[NProperties - 1].Name := PropertyName;
with Properties[NProperties - 1].Value do
case TokenValue.TokenType of
tokInt:
begin
PropertyType := ptInt;
IntValue := TokenValue.Value. IntValue;
RealValue := TokenValue.Value.RealValue;
end;
tokReal:
begin
PropertyType := ptReal;
RealValue := TokenValue.Value.RealValue;
end;
tokBool:
begin
PropertyType := ptBool;
BoolValue := TokenValue.Value.BoolValue;
end;
tokString:
begin
PropertyType := ptString;
StringValue := TokenValue.Value.StringValue;
end;
else
Assert(False, 'Non-value token');
end;
Result := Success;
end
else
Result := Fail;
end;
// Add a property with given name and value to the Config's last section
function AddPropertyLastSec(
var Config : TIniConfig;
const PropertyName : AnsiString;
const TokenValue : TToken
) : Boolean;
begin
Result := AddProperty(Config, Config.NSections - 1, PropertyName, TokenValue);
end;
{-----------------------<< Config >>------------------------------------------------}
// Initialize the Config, must be called before use
procedure InitConfig(
var Config : TIniConfig);
begin
with Config do
begin
NSections := 0;
SetLength(Sections, 0);
InitHashTable(HashSections);
end;
AddSection(Config, '');
end;
{-----------------------<< Addressation >>------------------------------------------}
// Split FullName into SectionName and PropertyName
procedure SplitCfgPath(
var SectionName : AnsiString;
var PropertyName : AnsiString;
const FullName : AnsiString);
var
PosDelimiter : Integer;
begin
PosDelimiter := Pos(SectionDelimiter, FullName);
SectionName := CopyRange(FullName, {From:} 1, {To:} PosDelimiter - 1);
PropertyName := CopyRange(
FullName, {From:} PosDelimiter + 1, {To:} Length(FullName) );
end;
// Get the property and section indices of a property with FullName or
// return Fail if it does not exist
function GetPropertyAddress(
var SectionIndex : TSectionIndex;
var PropertyIndex : TPropertyIndex;
const Config : TIniConfig;
const FullName : AnsiString
) : Boolean;
var
SectionName,
PropertyName : AnsiString;
begin
SplitCfgPath(SectionName, PropertyName, FullName);
SectionIndex := FindSection(Config, SectionName);
if SectionIndex = InvalidSection then
Result := Fail
else
begin
PropertyIndex := FindProperty(Config, SectionIndex, PropertyName);
if PropertyIndex = InvalidProperty then
Result := Fail else
Result := Success;
end;
end;
{-----------------------<< Getters >>-----------------------------------------------}
// Get the value of a property with FullName stored in Config or
// return Fail if it does not exist
function GetIntProperty(
var IntValue : Integer;
const Config : TIniConfig;
FullName : AnsiString
) : Boolean;
var
SectionIndex : TSectionIndex;
PropertyIndex : TPropertyIndex;
begin
Result := Fail;
if GetPropertyAddress(SectionIndex, PropertyIndex, Config, FullName) = Success then
with Config.Sections[SectionIndex].Properties[PropertyIndex] do
if Value.PropertyType = ptInt then
begin
IntValue := Value.IntValue;
Result := Success;
end;
end;
function GetRealProperty(
var RealValue : Real;
const Config : TIniConfig;
FullName : AnsiString
) : Boolean;
var
SectionIndex : TSectionIndex;
PropertyIndex : TPropertyIndex;
begin
Result := Fail;
if GetPropertyAddress(SectionIndex, PropertyIndex, Config, FullName) = Success then
with Config.Sections[SectionIndex].Properties[PropertyIndex] do
if (Value.PropertyType = ptInt) or (Value.PropertyType = ptReal) then
begin
RealValue := Value.RealValue;
Result := Success;
end;
end;
function GetBoolProperty(
var BoolValue : Boolean;
const Config : TIniConfig;
FullName : AnsiString
) : Boolean;
var
SectionIndex : TSectionIndex;
PropertyIndex : TPropertyIndex;
begin
Result := Fail;
if GetPropertyAddress(SectionIndex, PropertyIndex, Config, FullName) = Success then
with Config.Sections[SectionIndex].Properties[PropertyIndex] do
if Value.PropertyType = ptBool then
begin
BoolValue := Value.BoolValue;
Result := Success;
end;
end;
function GetStringProperty(
var StringValue : AnsiString;
const Config : TIniConfig;
FullName : AnsiString
) : Boolean;
var
SectionIndex : TSectionIndex;
PropertyIndex : TPropertyIndex;
begin
Result := Fail;
if GetPropertyAddress(SectionIndex, PropertyIndex, Config, FullName) = Success then
with Config.Sections[SectionIndex].Properties[PropertyIndex] do
if Value.PropertyType = ptString then
begin
StringValue := Value.StringValue;
Result := Success;
end;
end;
{-----------------------<< Parse, load >>-------------------------------------------}
// Parse the Tokens into a Config, return the Errors
procedure Parse(
var Config : TIniConfig;
var Tokens : TTokenStream;
var Errors : TStringList);
var
NowToken,
NextToken : TToken;
StrPosition : AnsiString;
const
ErrorDelimiterExpected = 'delimiter expected';
ErrorValueExpected = 'value expected';
ErrorUnexpectedToken = 'unexpected stuff';
ErrorSectionRedeclared = 'section redeclared';
ErrorPropertyRedeclared = 'property redeclared';
ErrorDelimiter = ': ';
begin
InitConfig(Config);
InitStringList(Errors);
while GetNextToken(NowToken, Tokens) = Success do
begin
StrPosition :=
PositionToString(NowToken.Position, {UpperCase:} True) + ErrorDelimiter;
case NowToken.TokenType of
tokSection:
if AddSection(Config, NowToken.Value.StringValue) = Fail then
AddToStringList(Errors, StrPosition + ErrorSectionRedeclared);
tokIdentifier:
if (GetNextToken(NextToken, Tokens) = Success) and
(NextToken.TokenType = tokDelimiter) then
begin
if (GetNextToken(NextToken, Tokens) = Success) and
(NextToken.TokenType in TokensValue) then
begin
if AddPropertyLastSec(
Config, NowToken.Value.StringValue, NextToken) = Fail then
AddToStringList(Errors, StrPosition + ErrorPropertyRedeclared);
end
else
AddToStringList(Errors, StrPosition + ErrorValueExpected);
end
else
AddToStringList(Errors, StrPosition + ErrorDelimiterExpected);
else
AddToStringList(Errors, StrPosition + ErrorUnexpectedToken);
end;
end;
end;
// Load the Config file located at Path, return the Errors
procedure LoadConfig(
var Config : TIniConfig;
const Path : AnsiString;
var Errors : TStringList);
var
Tokens : TTokenStream;
Input : AnsiString;
Delimiters : TDelimiters;
LexerProcs : TLexerProcs;
const
ErrorFile = 'Cannot open file ';
begin
if LoadString(Input, Path, {StripControl:} False) then
begin
SetDelimiters(Delimiters);
SetLexerProcs(LexerProcs);
InitTokens(Tokens);
Tokenize(@Tokens, Input, Delimiters, LexerProcs, Errors);
if Errors.N = 0 then
Parse(Config, Tokens, Errors);
end
else
AddToStringList(Errors, ErrorFile + Path);
end;
{-----------------------<< Load tables >>-------------------------------------------}
// Initialize LoadTable
procedure InitLoadTable(
var LoadTable : TLoadTable);
begin
SetLength(LoadTable, 0);
end;
// Load the variables specified in LoadTable from Config, return the Errors
procedure LoadFromConfig(
const LoadTable : TLoadTable;
const Config : TIniConfig;
var Errors : TStringList);
overload;
var
iVar : Integer;
VarInt : Integer;
VarReal : Real;
VarBool : Boolean;
VarString : AnsiString;
MsgNotFound,
MsgOverflow : AnsiString;
ptrInteger : PInteger;
ptrReal : PReal;
ptrBoolean : PBoolean;
ptrString : PAnsiString;
ErrorCheck : AnsiString;
NowFail : Boolean;
const
ErrorDelim = ': ';
ErrorNotFound = 'property not found';
ErrorOverflow = 'numeric overflow';
ErrorNoFunction = 'no function specified';
begin
InitStringList(Errors);
for iVar := 0 to Length(LoadTable) - 1 do with LoadTable[iVar] do
begin
// Get parameter from config
NowFail := False;
MsgNotFound := CfgPath + ErrorDelim + ErrorNotFound;
case VarType of
pasInteger:
NowFail := GetIntProperty(VarInt, Config, CfgPath) = Fail;
pasReal:
NowFail := GetRealProperty(VarReal, Config, CfgPath) = Fail;
pasBoolean:
NowFail := GetBoolProperty(VarBool, Config, CfgPath) = Fail;
pasString, pasOther:
NowFail := GetStringProperty(VarString, Config, CfgPath) = Fail;
else
Assert(False, 'Unknown variable type');
end;
if NowFail then
AddToStringList(Errors, MsgNotFound)
else
// Convert parameter into variable
begin
MsgOverflow := CfgPath + ErrorDelim + ErrorOverflow;
// #COPYPASTA need preprocessor
case VarType of
pasInteger:
begin
ptrInteger := PInteger(ptrVar);
ptrInteger^ := VarInt;
if ptrCheck <> nil then
begin
ErrorCheck := ProcCheckInt(ptrCheck)(VarInt);
if ErrorCheck <> '' then
AddToStringList(Errors, CfgPath + ErrorDelim + ErrorCheck);
end;
end;
pasReal:
begin
ptrReal := PReal(ptrVar);
ptrReal^ := VarReal;
if ptrCheck <> nil then
begin
ErrorCheck := ProcCheckReal(ptrCheck)(VarReal);
if ErrorCheck <> '' then
AddToStringList(Errors, CfgPath + ErrorDelim + ErrorCheck);
end;
end;
pasBoolean:
begin
ptrBoolean := PBoolean(ptrVar);
ptrBoolean^ := VarBool;
end;
pasString:
begin
ptrString := PAnsiString(ptrVar);
ptrString^ := VarString;
if ptrCheck <> nil then
begin
ErrorCheck := ProcCheckString(ptrCheck)(VarString);
if ErrorCheck <> '' then
AddToStringList(Errors, CfgPath + ErrorDelim + ErrorCheck);
end;
end;
pasOther:
if ptrCheck = nil then
AddToStringList(Errors, CfgPath + ErrorDelim + ErrorNoFunction)
else
begin
ErrorCheck := ProcOtherVar(ptrCheck)(ptrVar, VarString);
if ErrorCheck <> '' then
AddToStringList(Errors, CfgPath + ErrorDelim + ErrorCheck);
end;
else
Assert(False, 'Unknown variable type');
end;
end;
end;
end;
// Load the variables specified in LoadTable from a config file located at
// PathConfig, return the Errors
procedure LoadFromConfig(
const LoadTable : TLoadTable;
const PathConfig : AnsiString;
var Errors : TStringList);
overload;
var
Config : TIniConfig;
begin
LoadConfig(Config, PathConfig, Errors);
if Errors.N = 0 then
LoadFromConfig(LoadTable, Config, Errors);
end;
{-----------------------<< Adding variables to a load table >>----------------------}
// Add a variable of type VarType pointed at by ptrVar with config file path CfgPath