-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParser.YAML.pas
2320 lines (2188 loc) · 76.8 KB
/
Parser.YAML.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
{==============================================================================|
| Project : JSON/YAML Parser Tools for Object Pascal |
|==============================================================================|
| Content: YAML <--> JSON tooling |
|==============================================================================|
| Copyright (c) 2024, Vahid Nasehi Oskouei |
| All rights reserved. |
| |
| License: MIT License |
| |
| Remastered and rewritten version originally based on a work by: |
| Joao Costa, [email protected] |
| https://github.com./joao-m-costa/delphi-yaml-to-json |
| and reworked by: |
| Lu Wey (TMS Core) |
| https://github.com./LuWey/TextContainer |
| |
| Project download homepage: |
| https://github.com./biot2/Yaml.Json.Parser.pas |
| |
| History: |
| 2024-10-05 |
| - Support both Delphi and Free Pascal |
| - Added support for local tags |
| - Resolved issues with comments in the end of lines resolved |
| - Resolved issues with incorrent date/time format parsing resolved |
| - Added multiline binary support added |
| - JSON parser has beed replaced with Json Tools |
| - Switched unicode support to utf-8 (AnsiString) for better compatibility |
| between platforms |
| |
|==============================================================================|
| Requirements: Ararat Synapse (http://www.ararat.cz/synapse/) |
|==============================================================================}
unit Parser.YAML;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
SysUtils, Classes, DateUtils, Parser.JSON, Generics.Collections;
type
EYamlParsingException = class(Exception);
TYamlUtils = class
public
type
TYamlElement = record
Key: AnsiString;
Value: AnsiString;
Indent: Integer;
Literal: Boolean;
Alias: AnsiString;
Anchor: AnsiString;
LineNumber: Integer;
Tag: AnsiString;
class procedure Initialize(out Dest: TYamlElement); static;
class procedure Assign(var Dest: TYamlElement; const Src: TYamlElement); static;
procedure Clear;
end;
TYamlElements = TList<TYamlElement>;
TYamlTokenType = (tokenKey, tokenValue);
TBlockModifier = (blockNone, blockFolded, blockLiteral); // None, >, |
TChompModifier = (chompNone, chompClip, chompKeep); // None, -, +
TYamlIdentation = 2..8;
TJsonIdentation = 0..8;
private
// Utilities section
// -----------------
// Escape YAML text to JSON
class function InternalStringEscape(const AText: AnsiString): AnsiString;
// Try convert a timestamp value to a datetime UTC
class function InternalTryStrToDateTime(const AText: AnsiString; var ADate: TDateTime; AFormatSettings: TFormatSettings): Boolean;
// YAML to JSON section
// --------------------
// Read next text YAML line from strings
class function InternalYamlNextTextLine(AYAML: TStrings; var ARow, AIndent: Integer; AIgnoreBlanks: Boolean = True; AIgnoreComments: Boolean = True; AAutoTrim: Boolean = True): AnsiString;
// Retrieve what next text will be
class function InternalYamlNextText(AYAML: TStrings; var ARow, AIndent: Integer; AText: AnsiString; AIgnoreBlanks: Boolean = True; AIgnoreComments: Boolean = True; AAutoTrim: Boolean = True): AnsiString;
// Read next token from source, with multiline support
class function InternalYamlReadToken(AYAML: TStrings; var ARow, AIndent: Integer; var AText, ARemainer, AAlias, ATag: AnsiString; var ACollectionItem: Integer; var AIsLiteral: Boolean; AInArray: Boolean = False): TYamlTokenType;
// Find element containing an anchor by anchor name
class function InternalYamlFindAnchor(AElements: TYamlElements; AAnchorName: AnsiString): Integer;
// Resolve (pre-process) aliases to anchor values
class procedure InternalYamlResolveAliases(AElements: TYamlElements);
// Merge (pre-process) aliases with anchor values
class procedure InternalYamlResolveMerges(AElements: TYamlElements);
// Process an inline array from source
class procedure InternalYamlProcessArray(AYAML: TStrings; AElements: TYamlElements; var ARow, AIndent: Integer; var AText: AnsiString; AYesNoBool: Boolean; AAllowDuplicateKeys: Boolean);
// Process a collection (array) from source
class procedure InternalYamlProcessCollection(AYAML: TStrings; AElements: TYamlElements; var ARow, AIndent: Integer; var AText: AnsiString; AYesNoBool: Boolean; AAllowDuplicateKeys: Boolean);
// Process element pairs (key: value) from source
class procedure InternalYamlProcessElements(AYAML: TStrings; AElements: TYamlElements; var ARow, AIndent: Integer; var AText: AnsiString; AYesNoBool: Boolean; AAllowDuplicateKeys: Boolean);
// Format a YAML value to JSON
class function InternalYamlProcessJsonValue(AValue: AnsiString; ALiteral: Boolean; ATag: AnsiString; ALineNumber: Integer; AYesNoBool: Boolean): AnsiString;
// Convert the prepared TYamlElements list to JSON
class procedure InternalYamlToJson(AElements: TYamlElements; AJSON: TStrings; AIndentation: TJsonIdentation; AYesNoBool: Boolean);
// Entry point to parse YAML to JSON
class procedure InternalYamlParse(AYAML, AJSON: TStrings; AIndentation: TJsonIdentation; AYesNoBool: Boolean; AAllowDuplicateKeys: Boolean);
// JSON to YAML section
// --------------------
// Process JSON object to YAML (a touple)
class procedure InternalJsonObjToYaml(AJSON: TJsonNode; AOutStrings: TStrings; AIndentation: TYamlIdentation; var AIndent: Integer; AFromArray: Boolean = False; AYesNoBool: Boolean = False);
// Process JSON array to YAML
class procedure InternalJsonArrToYaml(AJSON: TJsonNode; AOutStrings: TStrings; AIndentation: TYamlIdentation; var AIndent: Integer; AFromArray: Boolean = False; AYesNoBool: Boolean = False);
// Convert a value from JSON to YAML
class function InternalJsonValueToYaml(AJSON: TJsonNode; AIndent: Integer = 0; AYesNoBool: Boolean = False): TArray<String>;
public
// JSON to YAML
class function JsonToYaml(AJSON: AnsiString; AIndentation: TYamlIdentation = 2; AYesNoBool: Boolean = False): AnsiString; overload;
class procedure JsonToYaml(AJSON: TStrings; AOutStrings: TStrings; AIndentation: TYamlIdentation = 2; AYesNoBool: Boolean = False); overload;
class function JsonToYaml(AJSON: TJsonNode; AIndentation: TYamlIdentation = 2; AYesNoBool: Boolean = False): AnsiString; overload;
class procedure JsonToYaml(AJSON: TJsonNode; AOutStrings: TStrings; AIndentation: TYamlIdentation = 2; AYesNoBool: Boolean = False); overload;
// YAML to JSON
class procedure YamlToJson(AYAML: TStrings; AOutStrings: TStrings; AIndentation: TJsonIdentation = 2; AYesNoBool: Boolean = True; AAllowDuplicateKeys: Boolean = True); overload;
class function YamlToJson(AYAML: AnsiString; AIndentation: TJsonIdentation = 2; AYesNoBool: Boolean = True; AAllowDuplicateKeys: Boolean = True): AnsiString; overload;
class function YamlToJson(AYAML: TStrings; AIndentation: TJsonIdentation = 2; AYesNoBool: Boolean = True; AAllowDuplicateKeys: Boolean = True): AnsiString; overload;
class function YamlToJsonValue(AYAML: AnsiString; AIndentation: TJsonIdentation = 0; AYesNoBool: Boolean = True; AAllowDuplicateKeys: Boolean = True): TJsonNode; overload;
class function YamlToJsonValue(AYAML: TStrings; AIndentation: TJsonIdentation = 0; AYesNoBool: Boolean = True; AAllowDuplicateKeys: Boolean = True): TJsonNode; overload;
// JSON tools
class function JsonMinify(AJSON: AnsiString): AnsiString; overload;
class function JsonMinify(AJSON: TStrings): AnsiString; overload;
end;
{##############################################################################}
implementation
uses synacode;
const
EYamlCollectionItemError = 'Yaml invalid collection item at line %d';
EYamlInvalidArrayError = 'Yaml invalid array at line %d';
EYamlInvalidIndentError = 'Yaml invalid identation an line %d';
EYamlAnchorAliasNameError = 'Yaml invalid alias/anchor name at line %d';
EYamlAnchorDuplicateError = 'Yaml duplicated anchor name at line %d';
EYamlCollectionBlockError = 'Yaml block modifiers can not be used for collection items at line %d';
EYamlInvalidBlockError = 'Yaml invalid block modifier at line %d';
EYamlUnclosedLiteralError = 'Yaml unclosed literal at line %d';
EYamlKeyNameEmptyError = 'Yaml empty key name at line %d';
EYamlKeyNameMultilineError = 'Yaml key names cannot be multiline at line %d';
EYamlKeyNameAnchorAliasError = 'Yaml aliases/anchors cannot be used for keys at line %d';
EYamlKeyNameInvalidCharError = 'Yaml invalid indicator "%s" for key al line %d';
EYamlAnchorAliasValueError = 'Yaml aliases for anchors cannot contain values at line %d';
EYamlUnconsumedContentError = 'Yaml unconsumed content at line %d';
EYamlUnclosedArrayError = 'Yaml unclosed array at line %d';
EYamlCollectionInArrayError = 'Yaml arrays cannot contain collection items at line %d';
EYamlDoubleKeyError = 'Yaml two keys for element at line %d';
EYamlExpectedKeyError = 'Yaml expected a key for element at line %d';
EYamlDuplicatedKeyError = 'Yaml duplicated key name at line %d';
EYamlAnchorNotFoundError = 'Yaml anchor "%s" not found for alias at line %d';
EYamlAliasRecursiveError = 'Yaml unsupported recursive alias "%s" found at line %d';
EYamlMergeInArrayError = 'Yaml merge indicator "<<" unsupported in arrays at line %d';
EYamlMergeInCollectionError = 'Yaml merge indicator "<<" unsupported in collections at line %d';
EYamlMergeSingleValueError = 'Yaml merge indicator "<<" unsupported for single values at line %d';
EYamlMergeInvalidError = 'Yaml invalid merge indicator "<<" without alias reference at line %d';
EYamlInvalidTagError = 'Yaml unreconized tag at line %d';
EYamlInvalidValueForTagError = 'Yaml invalid value type for tag at line %d';
const
LLiteralReplacer: AnsiString = chr(11) + chr(11);
LLiteralLineFeed: AnsiString = chr(14) + chr(14);
const
LTagMap: AnsiString = '!!map'; // Dictionary map {key: value}
LTagSeq: AnsiString = '!!seq'; // Sequence (an array or collection)
LTagStr: AnsiString = '!!str'; // Normal string (no conversion)
LTagNull: AnsiString = '!!null'; // Null (must be null)
LTagBool: AnsiString = '!!bool'; // Boolean (true/false)
LTagInt: AnsiString = '!!int'; // Integer numeric
LTagFloat: AnsiString = '!!float'; // Float numeric
LTagBin: AnsiString = '!!binary'; // Binary time (array of bytes)
LTagTime: AnsiString = '!!timestamp'; // Datetime type
// Sub-type TYamlElement
// ---------------------
class procedure TYamlUtils.TYamlElement.Initialize(out Dest: TYamlElement);
begin
Dest.Key := '';
Dest.Value := '';
Dest.Indent := -1;
Dest.Literal := False;
Dest.Alias := '';
Dest.Anchor := '';
Dest.LineNumber := 0;
Dest.Tag := '';
end;
class procedure TYamlUtils.TYamlElement.Assign(var Dest: TYamlElement; const Src: TYamlElement);
begin
Dest.Key := Src.Key;
Dest.Value := Src.Value;
Dest.Indent := Src.Indent;
Dest.Literal := Src.Literal;
Dest.Alias := Src.Alias;
Dest.Anchor := Src.Anchor;
Dest.LineNumber := Src.LineNumber;
Dest.Tag := Src.Tag;
end;
procedure TYamlUtils.TYamlElement.Clear;
begin
Key := '';
Value := '';
Indent := -1;
Literal := False;
Alias := '';
Anchor := '';
LineNumber := 0;
Tag := '';
end;
// TYamlUtils static class
// -----------------------
// Escape string for Yaml to Json conversion
// If ALiteral is true, the source is enclosed with double-quotes ("value") and backslash will not be escaped
class function TYamlUtils.InternalStringEscape(const AText: AnsiString): AnsiString;
var
T: AnsiString;
C: Ansistring;
begin
T := AText;
T := T.Replace('\', '\\'); // backslash
T := T.Replace('"', '\"'); // double quotes
T := T.Replace(#8, '\b'); // backspace
T := T.Replace(#9, '\t'); // tab
T := T.Replace(#10, '\n'); // line feed
T := T.Replace(#12, '\f'); // form feed
T := T.Replace(#13, '\r'); // cariage return
// WWY: Fixed issues with the next unicode char constants, e.g. "#$2028"
// When writing as before:
// T := T.Replace(#$2028, '\u2028')
// this crashes js and/or the browser! Wrapping them in Chr() fixes this.
C := #$C2#$85; // Chr($0085);
T := T.Replace(C, '\u0085'); // new line (unicode)
C := #$E2#$80#$A8; // Chr($2028);
T := T.Replace(C, '\u2028'); // line separator (unicode)
C := #$E2#$80#$A9; // Chr($2029);
T := T.Replace(C, '\u2029'); // paragraph separator (unicode)
T := T.Replace(LLiteralLineFeed, '\n'); // implicit line feed on literals
Result := T;
end;
// Try convert a timestamp value to a datetime UTC
class function TYamlUtils.InternalTryStrToDateTime(const AText: AnsiString; var ADate: TDateTime; AFormatSettings: TFormatSettings): Boolean;
var
Num: Integer;
T: AnsiString;
i: Integer;
begin
T := AText;
if TryStrToInt(T.Substring(0, 1), Num) then
begin
T := T.Replace('t', 'T');
T := T.Replace('z', 'Z');
// Check if we need to invert year i
i := T.IndexOf('-');
if i <= 2 then
T := T.Substring(i + 4, 4) + // Year
T.Substring(i, 1) + // Sep
T.Substring(i + 1, 2) + // Month
T.Substring(i, 1) + // Sep
T.Substring(0, i) + // Day
T.Substring(i + 8); // Remaining
// Try ISO8601 conversion, converting to UTC
{$IFNDEF PAS2JS}
Result := DateUtils.TryISO8601ToDate(T, ADate, True);
{$ELSE}
// Function TryRFC3339ToDateTime(const Avalue: AnsiString; out ADateTime: TDateTime): Boolean;
Result := DateUtils.TryRFC3339ToDateTime(LText, ADate);
{$ENDIF}
// Of try the usual way
if not Result then
Result := TryStrToDateTime(T, ADate, AFormatSettings);
end
else
Result := False;
end;
// YAML to JSON section
// --------------------
// Read next text YAML line from strings
class function TYamlUtils.InternalYamlNextTextLine(AYAML: TStrings; var ARow, AIndent: Integer; AIgnoreBlanks: Boolean = True; AIgnoreComments: Boolean = True; AAutoTrim: Boolean = True): AnsiString;
var
Row: Integer;
Found: Boolean;
T: AnsiString;
begin
Row := ARow;
Found := False;
while (Row < AYAML.Count - 1) and (not Found) do
begin
Inc(Row);
T := AYAML[Row].TrimLeft;
if not ((T.StartsWith('#') and AIgnoreComments) or (T.Trim.IsEmpty and AIgnoreBlanks)) then
begin
Found := True;
// If line is blank (in a multiline element), keep same indent
if not T.Trim.IsEmpty then
AIndent := AYAML[Row].Length - T.Length;
T := AYAML[Row];
end;
end;
if not Found then
begin
T := '';
Row := -1;
AIndent := -1;
end;
ARow := Row;
if AAutoTrim then
Result := T.Trim
else
Result := T;
end;
// Retrieve what next text will be
class function TYamlUtils.InternalYamlNextText(AYAML: TStrings; var ARow, AIndent: Integer; AText: AnsiString; AIgnoreBlanks: Boolean = True; AIgnoreComments: Boolean = True; AAutoTrim: Boolean = True): AnsiString;
begin
if (AText.IsEmpty) or AText.StartsWith('#') then
Result := InternalYamlNextTextLine(AYAML, ARow, AIndent, AIgnoreBlanks, AIgnoreComments, AAutoTrim)
else
Result := AText;
end;
// Read next token from source, with multiline support
class function TYamlUtils.InternalYamlReadToken(AYAML: TStrings; var ARow, AIndent: Integer; var AText, ARemainer, AAlias, ATag: AnsiString; var ACollectionItem: Integer; var AIsLiteral: Boolean; AInArray: Boolean = False): TYamlTokenType;
var
TokenType: TYamlTokenType;
T: AnsiString;
Row: Integer;
Indent: Integer;
BlockModifier: TBlockModifier;
ChompModifier: TChompModifier;
Literal: AnsiString;
LiteralMask: AnsiString;
LFLiteral: AnsiString;
Pos: Integer;
Found: Boolean;
NextRow: Integer;
NextIndent: Integer;
NextText: AnsiString;
PrevRow: Integer;
PrevIndent: Integer;
Lines: TStringList;
i, j: Integer;
LinesCount: Integer;
LeftMargin: Integer;
Margin: Integer;
begin
TokenType := TYamlTokenType.tokenValue;
T := AText;
Row := ARow;
Indent := AIndent;
PrevIndent := AIndent;
PrevRow := ARow;
BlockModifier := blockNone;
ChompModifier := chompNone;
Literal := '';
LiteralMask := '';
NextRow := -1;
NextIndent := -1;
NextText := '';
LinesCount := 0;
ACollectionItem := 0;
AIsLiteral := False;
ARemainer := '';
AAlias := '';
ATag := '';
if T.IsEmpty or T.StartsWith('#') then
T := InternalYamlNextTextLine(AYAML, Row, Indent, True, True);
// If reached EOF, exit
if Row < 0 then
begin
ARow := -1;
AIndent := -1;
AText := '';
Exit(TokenType);
end;
// Check for tags
if T.ToLower.Trim.Equals(LTagMap) or T.ToLower.StartsWith(LTagMap + ' ') then
ATag := LTagMap
else if T.ToLower.Trim.Equals(LTagSeq) or T.ToLower.StartsWith(LTagSeq + ' ') then
ATag := LTagSeq
else if T.ToLower.Trim.Equals(LTagStr) or T.ToLower.StartsWith(LTagStr + ' ') then
ATag := LTagStr
else if T.ToLower.Trim.Equals(LTagNull) or T.ToLower.StartsWith(LTagNull + ' ') then
ATag := LTagNull
else if T.ToLower.Trim.Equals(LTagBool) or T.ToLower.StartsWith(LTagBool + ' ') then
ATag := LTagBool
else if T.ToLower.Trim.Equals(LTagInt) or T.ToLower.StartsWith(LTagInt + ' ') then
ATag := LTagInt
else if T.ToLower.Trim.Equals(LTagFloat) or T.ToLower.StartsWith(LTagFloat + ' ') then
ATag := LTagFloat
else if T.ToLower.Trim.Equals(LTagBin) or T.ToLower.StartsWith(LTagBin + ' ') then
ATag := LTagBin
else if T.ToLower.Trim.Equals(LTagTime) or T.ToLower.StartsWith(LTagTime + ' ') then
ATag := LTagTime
else if T.ToLower.StartsWith('!!') then
raise EYamlParsingException.CreateFmt(EYamlInvalidTagError, [Row + 1])
else if T.StartsWith('!') then
ATag := T.Substring(0, T.IndexOf(' '));
if not ATag.IsEmpty then
begin
T := T.Substring(ATag.Length).TrimLeft;
if T.IsEmpty then
begin
ARow := Row;
AIndent := Indent;
AText := '';
Exit(TokenType);
end;
end;
// Check for inner array start/end/separator
if T.StartsWith('[') or (AInArray and (T.StartsWith(']') or T.StartsWith(','))) then
begin
ARemainer := T.Substring(1).Trim;
AText := T.Substring(0, 1);
ARow := Row;
AIndent := Indent;
Exit(TokenType);
end;
// Check if it is a collection item
if (T.StartsWith('- ')) and (not AInArray) then
begin
if not (T.StartsWith('- ') or T.Equals('-')) then
raise EYamlParsingException.CreateFmt(EYamlCollectionItemError, [Row + 1]);
ACollectionItem := (T.Substring(1).Length) - (T.Substring(1).TrimLeft().Length) + 1;
if ACollectionItem <= 0 then
ACollectionItem := 2;
T := T.Substring(1).Trim;
end;
// Check for alias/anchor/references
if T.StartsWith('&') or T.StartsWith('*') then
begin
if T.Substring(1).StartsWith(' ') then
raise EYamlParsingException.CreateFmt(EYamlAnchorAliasNameError, [Row + 1]);
if AInArray then
Pos := T.IndexOfAny([' ', ','])
else
Pos := T.IndexOf(' ');
if Pos >= 0 then
begin
AAlias := T.Substring(0, Pos).Trim;
T := T.Substring(Pos).Trim;
end
else
begin
AAlias := T;
T := '';
end;
// Evaluate that the alias is a valid name
if (not SysUtils.IsValidIdent(AAlias.Substring(1), False)) then
raise EYamlParsingException.CreateFmt(EYamlAnchorAliasNameError, [Row + 1]);
end;
// Check for block/folder modifiers, multiline related
// If they are present, this must be a value
if T.StartsWith('|') or T.StartsWith('>') then
begin
if ACollectionItem > 0 then
raise EYamlParsingException.CreateFmt(EYamlCollectionBlockError, [Row + 1]);
if T.StartsWith('|') then
BlockModifier := blockLiteral
else
BlockModifier := blockFolded;
T := T.Substring(1).Trim;
if T.StartsWith('+') or T.StartsWith('-') then
begin
if T.StartsWith('+') then
ChompModifier := chompKeep
else
ChompModifier := chompClip;
T := T.Substring(1).Trim;
end;
end;
// Check for literals (starting with " or with ' )
if T.StartsWith('"') then
begin
Literal := '"';
LiteralMask := '\"';
end
else if T.StartsWith('''') then
begin
Literal := '''';
LiteralMask := '''''';
end;
// Read the token, check if multilines are actually there, to avoid multiline strings processing if not needed
// When not found, multilines are present so we will have to keep reading
Found := False;
// Is it literal
if not Literal.IsEmpty then
begin
T := T.Substring(1).Replace(LiteralMask, LLiteralReplacer);
Pos := T.IndexOf(Literal);
// Closure found inline
if Pos >= 0 then
begin
Found := True;
ARemainer := T.Substring(Pos + 1).Replace(LLiteralReplacer, LiteralMask).Trim;
T := T.Substring(0, Pos).Replace(LLiteralReplacer, Literal);
end;
end
else
begin
// Check for inline array element termination
if AInArray then
begin
Pos := T.IndexOfAny([',', ']']);
if Pos >= 0 then
begin
Found := True;
ARemainer := T.Substring(Pos) + ARemainer;
T := T.Substring(0, Pos);
end;
end;
// Check for inline key: value termination
Pos := T.IndexOf(': ');
if (Pos < 0) and T.EndsWith(':') then
Pos := T.Length - 1;
if Pos >= 0 then
begin
Found := True;
ARemainer := T.Substring(Pos) + ARemainer;
T := T.Substring(0, Pos);
end;
// Still not found, so take a look at next row and evaluate termination
if not Found then
begin
NextRow := Row;
NextIndent := Indent;
NextText := InternalYamlNextText(AYAML, NextRow, NextIndent, ARemainer, True, True);
// EOF
if NextRow < 0 then
Found := True
// Collection item failure
else if (ACollectionItem > 0) and (NextRow = Row) then
raise EYamlParsingException.CreateFmt(EYamlCollectionItemError, [Row + 1])
// Another collection item at the same level
else if (ACollectionItem > 0) and (NextIndent = Indent) and (NextText.StartsWith('- ') or NextText.Equals('-')) then
Found := True
// A collection is starting
else if (ACollectionItem <= 0) and (NextIndent >= Indent) and (NextText.StartsWith('- ') or NextText.Equals('-')) then
Found := True
// New element or outdenting
else if (NextIndent <= AIndent) then
Found := True
// Indenting new key
else if (NextIndent > AIndent) and (NextText.EndsWith(':') or (NextText.IndexOf(': ') >= 0)) then
Found := True;
// In case multiline starts at next row
if (Row > PrevRow) and (PrevIndent < Indent) then
Indent := PrevIndent;
end;
end;
// Not found, go for multilines
if (not Found) and (Row >= 0) and (Row < AYAML.Count - 1) then
begin
NextRow := Row;
NextIndent := AIndent;
Lines := TStringList.Create;
try
if not T.IsEmpty then
Lines.Add(T);
while (not Found) and (NextRow >= 0) do
begin
T := InternalYamlNextTextLine(AYAML, NextRow, NextIndent, False, (not Literal.IsEmpty), False);
// Literal text, must find text closure
if (not Literal.IsEmpty) then
begin
T := T.Replace(LiteralMask, LLiteralReplacer);
Pos := T.IndexOf(Literal);
if Pos >= 0 then
begin
Found := True;
ARemainer := T.Substring(Pos + 1).Replace(LLiteralReplacer, LiteralMask).Trim;
Lines.Add(T.Substring(0, Pos));
end
else
Lines.Add(T);
Row := NextRow;
end
// Reached EOF
else if (NextRow < 0) then
Found := True
else
begin
// Outdenting or new element
if (NextIndent <= Indent) and (not AInArray) and (not T.Trim.IsEmpty) then
Found := True
// Another collection item at the same level
else if (ACollectionItem > 0) and (NextIndent = Indent) and (NextText.StartsWith('- ') or NextText.Equals('-')) then
Found := True
// Collection item starting
else if (ACollectionItem <= 0) and (not AInArray) and (NextIndent >= Indent) and (NextText.StartsWith('- ') or NextText.Equals('-')) then
Found := True
// Splitted line ending
else
begin
Pos := -1;
if AInArray then
Pos := T.IndexOfAny([',', ']', '[']);
if Pos < 0 then
Pos := T.IndexOf(': ');
if (Pos < 0) and T.EndsWith(':') then
Pos := T.Length - 1;
if Pos >= 0 then
begin
Found := True;
ARemainer := T.Substring(Pos).Trim;
Lines.Add(T.Substring(0, Pos));
end;
end;
// Not found inline, add new line
if (not Found) then
begin
Lines.Add(T);
Row := NextRow;
end;
end;
end;
// All lines were read.
// Process them according literal/scallar/chomp options
LinesCount := Lines.Count;
// Top empty lines are only kept if literal is " or we have a folder modified
if (Found) and (BlockModifier = blockNone) and (not Literal.Equals('"')) then
begin
while (Lines.Count > 0) and (Lines[0].Trim.IsEmpty) do
Lines.Delete(0);
end;
// Bottom empty lines are only kept if literal is " or chomp modifier is +
if (Found) and (ChompModifier <> chompKeep) and (not Literal.Equals('"')) then
begin
i := Lines.Count - 1;
while (i >= 0) and (Lines[i].Trim.IsEmpty) do
begin
Lines.Delete(i);
Dec(i);
end;
end;
// Compute multiline left alignment
if (Found) then
begin
LeftMargin := -1;
for i := 1 to Lines.Count - 1 do
begin
if not Lines[i].IsEmpty then
begin
T := Lines[i];
Margin := Lines[i].Length - Lines[i].TrimLeft.Length;
if (LeftMargin <= 0) or (Margin < LeftMargin) then
LeftMargin := Margin;
end;
end;
if Lines.Count > 0 then
Lines[0] := String.Create(' ', LeftMargin) + Lines[0];
for i := 0 to Lines.Count - 1 do
Lines[i] := Lines[i].Substring(LeftMargin);
end;
// Convert it back to a single text for json
if (Found) then
begin
T := '';
if ATag = LTagBin then
LFLiteral := ''
else
LFLiteral := LLiteralLineFeed;
for i := 0 to Lines.Count - 1 do
begin
if Lines[i].Trim.IsEmpty then
T := T + LFLiteral
else if BlockModifier = blockLiteral then
T := T + Lines[i] + LFLiteral
else if Lines[i].StartsWith(' ') and (BlockModifier <> blockNone) then
begin
if T.IsEmpty then
T := T + Lines[i] + LFLiteral
else if (i > 0) and (Lines[i - 1].Trim.IsEmpty or Lines[i - 1].StartsWith(' ')) then
T := T + Lines[i] + LFLiteral
else
T := T + LFLiteral + Lines[i] + LFLiteral;
end
else
begin
if not (T.IsEmpty or T.EndsWith(LFLiteral) or T.EndsWith(' ')) then
T := T + ' ';
if (BlockModifier = blockNone) then
T := T + Lines[i].Trim()
else
T := T + Lines[i];
end;
end;
if (BlockModifier = blockFolded) and (ChompModifier <> chompClip) then
T := T + LFLiteral;
if T.EndsWith(LFLiteral) and (ChompModifier = chompClip) then
T := T.Substring(0, T.Length - LFLiteral.Length);
if (not Literal.IsEmpty) then
T := T.Replace(LLiteralReplacer, Literal);
end;
finally
FreeAndNil(Lines);
end;
end;
// If unclosed literal element, raise
if (not Found) and (not Literal.IsEmpty) then
raise EYamlParsingException.CreateFmt(EYamlUnclosedLiteralError, [Row + 1]);
// Check for key type
if (ARemainer = ':') or ARemainer.StartsWith(': ') or (AInArray and ARemainer.StartsWith(':,')) then
begin
TokenType := TYamlTokenType.tokenKey;
ARemainer := ARemainer.Substring(1).Trim;
// Keys cannot be empty
if T.IsEmpty then
raise EYamlParsingException.CreateFmt(EYamlKeyNameEmptyError, [Row + 1]);
// Keys cannot be multiline
if LinesCount > 1 then
raise EYamlParsingException.CreateFmt(EYamlKeyNameMultilineError, [Row + 1]);
// Keys cannot have aliases/anchors
if not AAlias.IsEmpty then
raise EYamlParsingException.CreateFmt(EYamlKeyNameAnchorAliasError, [Row + 1]);
// Check accepted initial chars for keys
if SysUtils.CharInSet(T.Chars[0], ['[', ',', ']', '-', '&', '*', '|', '>', '+']) then
raise EYamlParsingException.CreateFmt(EYamlKeyNameInvalidCharError, [T.Substring(0, 1), Row + 1]);
end;
// Check for anchor reference with value
if (not AAlias.IsEmpty) and (AAlias.StartsWith('*')) and (not T.IsEmpty) then
raise EYamlParsingException.CreateFmt(EYamlAnchorAliasValueError, [Row + 1]);
AIsLiteral := not Literal.IsEmpty;
ARow := Row;
AIndent := Indent;
if AIsLiteral then
AText := InternalStringEscape(T)
else begin
j := T.IndexOf('# ');
if j >= 0 then
T := T.Remove(j).TrimRight;
AText := InternalStringEscape(T.Trim([' ']));
end;
Result := TokenType;
end;
// Find element containing an anchor by anchor name
class function TYamlUtils.InternalYamlFindAnchor(AElements: TYamlElements; AAnchorName: AnsiString): Integer;
var
i: Integer;
begin
if not AAnchorName.IsEmpty then
for i := 0 to AElements.Count - 1 do
if AElements[i].Anchor.Equals(AAnchorName) then
Exit(i);
Result := -1;
end;
// Resolve (pre-process) aliases to anchor values
class procedure TYamlUtils.InternalYamlResolveAliases(AElements: TYamlElements);
var
i: Integer;
Anchor: Integer;
Alias: Integer;
AliasName: AnsiString;
AliasElement: TYamlElement;
AnchorElement: TYamlElement;
Element: TYamlElement;
Done: Boolean;
RefIndent: Integer;
SubElements: TYamlElements;
begin
if AElements.Count = 0 then
Exit;
Done := False;
while not Done do
begin
Alias := -1;
AliasName := '';
i := 0;
while (AliasName.IsEmpty) and (i < AElements.Count) do
begin
if (not AElements[i].Alias.IsEmpty) and (not AElements[i].Key.Equals('<<')) then
begin
Alias := i;
AliasName := AElements[i].Alias;
AliasElement := AElements[i];
end
else
Inc(i);
end;
if AliasName.IsEmpty then
Done := True
else
begin
AliasElement.Alias := '';
AElements[Alias] := AliasElement;
// Find the enchor
Anchor := InternalYamlFindAnchor(AElements, AliasName);
if Anchor < 0 then
raise EYamlParsingException.CreateFmt(EYamlAnchorNotFoundError, [AliasName, AliasElement.LineNumber]);
AnchorElement := AElements[Anchor];
// Is it a single value reference ?
if not AnchorElement.Value.IsEmpty then
begin
AliasElement.Value := AnchorElement.Value;
AliasElement.Literal := AnchorElement.Literal;
AliasElement.Tag := AnchorElement.Tag;
AElements[Alias] := AliasElement;
end
// Is it a subchain reference ?
else
begin
RefIndent := AnchorElement.Indent;
SubElements := TYamlElements.Create;
try
i := Anchor + 1;
while (i > 0) and (i < AElements.Count) do
begin
if AElements[i].Indent > RefIndent then
begin
if (AElements[i].Alias = AliasName) then
raise EYamlParsingException.CreateFmt(EYamlAliasRecursiveError, [AliasName, AElements[i].LineNumber]);
Element := AElements[i];
Element.Indent := Element.Indent - RefIndent + AliasElement.Indent;
SubElements.Add(Element);
Inc(i);
end
else
i := -1;
end;
if SubElements.Count > 0 then
AElements.InsertRange(Alias + 1, SubElements);
finally
FreeAndNil(SubElements);
end;
end;
end;
end;
end;
// Merge (pre-process) aliases with anchor values
class procedure TYamlUtils.InternalYamlResolveMerges(AElements: TYamlElements);
var
i, j: Integer;
Anchor: Integer;
Alias: Integer;
AliasName: AnsiString;
AliasElement: TYamlElement;
AnchorElement: TYamlElement;
Done: Boolean;
Element: TYamlElement;
RefIndent: Integer;
BaseIndent: Integer;
RefParent: Integer;
SubElements: TYamlElements;
AnchorElements: TYamlElements;
MergeElements: TYamlElements;
Index: Integer;
Indent: Integer;
function __FindExistingElement(AList: TYamlElements; AElement: TYamlElement): Integer;
var
k: Integer;
begin
for k := 0 to AList.Count - 1 do
begin
if (AList[k].Indent = AElement.Indent) and
((not AElement.Key.IsEmpty and AElement.Key.Equals(AList[k].Key)) or
(AElement.Key.IsEmpty and AElement.Value.Equals(AList[k].Value))) then
Exit(k);
end;
Result := -1;
end;
begin
if AElements.Count = 0 then
Exit;
SubElements := nil;
MergeElements := nil;
try
SubElements := TYamlElements.Create;
AnchorElements := TYamlElements.Create;
MergeElements := TYamlElements.Create;
Done := False;
while not Done do
begin
Alias := -1;
AliasName := '';
i := 0;
while (AliasName.IsEmpty) and (i < AElements.Count) do
begin
if (not AElements[i].Alias.IsEmpty) and (AElements[i].Key.Equals('<<')) then
begin
Alias := i;
AliasName := AElements[i].Alias;
AliasElement := AElements[i];
end
else
Inc(i);
end;
if AliasName.IsEmpty then
Done := True
else
begin
// Find the enchor
Anchor := InternalYamlFindAnchor(AElements, AliasName);
if Anchor < 0 then
raise EYamlParsingException.CreateFmt(EYamlAnchorNotFoundError, [AliasName, AliasElement.LineNumber]);
AnchorElement := AElements[Anchor];
// Is it a single value reference ?
if not AnchorElement.Value.IsEmpty then
raise EYamlParsingException.CreateFmt(EYamlMergeSingleValueError, [AliasName, AliasElement.LineNumber]);
// Find the relative root
RefIndent := AliasElement.Indent;
BaseIndent := 0;
RefParent := -1;
i := Alias - 1;
while (i >= 0) and (RefParent = -1) do
begin
if AElements[i].Indent < RefIndent then
begin
RefParent := i;
BaseIndent := AElements[i].Indent;
end
else
Dec(i);
end;
// Get the anchor elements
RefIndent := AnchorElement.Indent;
AnchorElements.Clear;
i := Anchor + 1;
while (i > 0) and (i < AElements.Count) do
begin
if AElements[i].Indent > RefIndent then
begin
if (AElements[i].Alias = AliasName) then
raise EYamlParsingException.CreateFmt(EYamlAliasRecursiveError, [AliasName, AElements[i].LineNumber]);
Element := AElements[i];
Element.Indent := Element.Indent - RefIndent + BaseIndent;
AnchorElements.Add(Element);
Inc(i);
end
else
i := -1;
end;
// Read existing elements to merge with and removed them from chain (they will be reinserted after merging)
MergeElements.Clear;
RefIndent := AliasElement.Indent;
i := RefParent + 1;
while (i > 0) and (i < AElements.Count) do
begin
if AElements[i].Indent >= RefIndent then
begin
if not (AElements[i].Alias = AliasName) then
begin
Element := AElements[i];
MergeElements.Add(Element);
end;
AElements.Delete(i);
end
else
i := -1;
end;
// Remove existing arrays/collections from anchor elements as the do not merge
for i := 0 to MergeElements.Count - 1 do
begin
Element := MergeElements[i];
if not Element.Key.IsEmpty then
begin
Index := __FindExistingElement(AnchorElements, Element);
if (Index >= 0) and (Index < AnchorElements.Count - 1) and (AnchorElements[Index + 1].Key.IsEmpty) and (AnchorElements[Index + 1].Value.Equals('[')) then
begin
// Remove the array chain