-
Notifications
You must be signed in to change notification settings - Fork 19
/
Neslib.Yaml.pas
4159 lines (3476 loc) · 122 KB
/
Neslib.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
unit Neslib.Yaml;
(*< Neslib.Yaml - A YAML library for Delphi
Neslib.Yaml is a library for parsing and emitting YAML and constructing YAML
documents and streams.
Neslib.Yaml is build on top of the LibYaml library
(https://github.com/yaml/libyaml) and works on:
- Windows (32-bit and 64-bit)
- MacOS (32-bit and soon 64-bit)
- iOS (32-bit and 64-bit, no simulator)
- Android (32-bit and 64-bit later)
@bold(Installation and Dependencies)
To install:
> git clone --recursive https://github.com/neslib/Neslib.Yaml
This library only depends on the Neslib repository, which is included as
submodule with this repository.
For all platforms except MacOS 32-bit, there are no run-time dependencies: the
LibYaml library is linked directly into the executable. For MacOS 32-bit, you
need to deploy the "libyaml_mac32.dylib" library to the remote path
"Contents\MacOS\".
@bold(YAML in a Nutshell)
Here is a very brief introduction for YAML. For more detailed information take
a look at the official YAML site (https://yaml.org/) or one of the many
on-line resources such as https://camel.readthedocs.io/en/latest/yamlref.html.
YAML (short for "YAML Ain't Markup Language") is a data serialization
language. Unlike many other similar text-based languages (like JSON and XML) a
primary goal of YAML is to be human-readable and also easy to create by
humans. That's why its is commonly used for configuration files. However, it
can be used for all kinds of data, such as this example from the YAML
specification:
@preformatted(
invoice: 34843
date : 2001-01-23
bill-to: &id001
given : Chris
family : Dumars
address:
lines: |
458 Walkman Dr.
Suite #292
city : Royal Oak
state : MI
postal : 48046
ship-to: *id001
product:
- sku : BL394D
quantity : 4
description : Basketball
price : 450.00
- sku : BL4438H
quantity : 1
description : Super Hoop
price : 2392.00
tax : 251.42
total: 4443.52
comments: >
Late afternoon is best.
Backup contact is Nancy
Billsmer @ 338-4338.
)
A YAML document is a tree of values, called nodes (TYamlNode in this library).
There are 4 kinds of nodes:
@bold(Mappings)
Mappings are similar to Delphi dictionaries. A mapping is a collection of
key/value pairs. The root note of the sample document above is a mapping: it
maps the key "invoice" to the value "34843" and contains 7 other key/value
pairs (from "date" to "comments"). Both keys and values can be any YAML type,
although you probably want to stick to strings for keys.
Mappings can be written in block notation (as in the example) or flow notation
(using curly braces {}).
When using block notation, YAML uses indentation for scoping. Only spaces are
allowed for indentation (not tabs). The number of spaces doesn't matter as
long as all values at the same level use the same amount of spaces. In the
example, the value of the "bill-to" key is another mapping. This mapping is
indented to indicate that it belongs to the "bill-to" key.
@bold(Sequences)
Sequences are like Delphi arrays or lists. Small sequences can be written
using flow notation (using square brackets []). Larger or complex sequences
are usually written in block notation as in the example: the value of the
"product" key is a sequence of two products (a basketball and super hoop).
Each item in the sequence starts with a dash and a space.
In this example, each product in the sequence is a mapping of 4 key/value
pairs.
@bold(Aliases)
All nodes have at least two properties: a Tag and an Anchor. Tags are used to
describe the semantic type of a node. Tags are not that common, so I will skip
them in this introduction. Neslib.Yaml has full support for tags though.
An Anchor can be used to mark a node in the document. You can then later refer
back to this node using an Alias.
Anchors are prefixed with an ampersand (&). In the example, the value of the
"bill-to" key has an anchor called "id001" (the ampersand is not part of the
name). Later in the document, the "ship-to" key refers back to this anchor
using an Alias (an asterisk followed by the anchor name, eg. "*id001"). This
is a way of saying that the shipping address is the same as the billing
address. Note that an alias does *not* copy the referenced value; it really
just refers to another node.
Anchors *must* appear in the document before they can be referenced. Their
names *don't* have to be unique within the document; if an new anchor is
declared with the same name, it replaces the old anchor.
@bold(Scalars)
Scalars are the simplest types. Everything that is not a mapping, sequence or
alias is a scalar. In practice, scalars are just strings. All the keys in the
example above are string scalars, but a lot of the values are as well (such as
"34843", "2001-01-23" and "Chris").
The YAML 1.1 specification (which is what LibYaml uses) treats all these
scalars as strings, even if they are numbers or dates as in this example. You
can use tags to explicitly state that a specific scalar is of a specific type.
The TYamlNode record in this library provides methods like ToInteger and
ToDouble to (try to) convert to Delphi types, regardless of any tags that may
be attached to a node.
Scalars can be written in different "styles":
- The *plain* style is the most common style. It doesn't use any special
symbols. Most scalars in the example are in plain style.
- The *double-quoted* style is useful if you need escape sequences in the
text.
- The *single-quoted* style can be used if backslashes in text should not be
un-escaped (eg. when using Windows file paths).
- The *literal* style can be used for a block of text spanning multiple lines.
It starts with a pipe symbol (|). In the example above, the
"bill-to.address.lines" value is a literal. Any new-lines in a literal are
preserved.
- Finally, the *folded* style is similar to the literal style, but line breaks
are folded (replaced with spaces). It is used with the "comments" key in the
example.
There is much more to YAML, but this should cover many use cases.
@bold(Loading or Parsing YAML)
The main entry point to this library is the IYamlDocument or IYamlStream
interface.
A YAML file can contain multiple documents. If that is the case, you should
use an IYamlStream to load it. A stream is just a collection of documents (of
type IYamlDocument).
Most of the time though, a YAML file contains just a single document and it is
easier to start with a IYamlDocument. Loading a document is easy:
<source>
var
Doc: IYamlDocument;
begin
Doc := TYamlDocument.Load('invoice.yaml');
end;
</source>
You can load from a file or stream, or you can parse YAML text using the
TYamlDocument.Parse method.
You can now use the IYamlDocument.Root property to inspect the document. This
property is of type TYamlNode, which is the building block for all documents.
NOTE: TYamlNode is implemented as a record to keep it light-weight. All
nodes are "owner" by a document. This makes memory management fully
automatic: once a document goes out of scope, all its nodes will be freed
automatically. This does mean though that you should not "hang on" to nodes
after a document has gone out of scope. Doing so results in undefined
behavior or access violations.
For example, to access the price of the first product in the example above,
you can use the following code:
<source>
Price := Doc.Root.Values['product'].Nodes[0].Values['price'].ToDouble;
</source>
You use the Values property to access values by key in mapping. Likewise the
Nodes property is used to access values by index in a sequence, and one of the
ToXXX methods can be used to convert a scalar value to a Delphi datatype.
To check the type of a node, you can use the NodeType property or one of the
IsXXX properties (IsMapping, IsScalar etc.).
@bold(Constructing and Emitting YAML)
You can also create a YAML document from scratch and save it to a file or
convert it to YAML. To create a YAML document, use one of the
TYamlDocument.CreateXXX methods, depending on the type of root node you need.
If you want to reconstruct the example document, you would start out with a
mapping and call:
<source>
Doc := TYamlDocument.CreateMapping;
</source>
You can then start to add key/value pairs"
<source>
Doc.Root.AddOrSetValue('invoice', 34843);
Doc.Root.AddOrSetValue('date', '2001-01-23');
</source>
The AddOrSetValue method is used to add key/value pairs to a mapping. If the
node is not a mapping, then an EInvalidOperation exception will be raised.
To add a non-scalar value, use one of the other AddOrSetXXX methods:
<source>
var
Products: TYamlNode;
begin
Products := Doc.Root.AddOrSetSequence('product');
end;
</source>
This adds a sequence to the mapping with the key "product". You can then add
values to the sequence using one of the AddXXX methods. Again, an
EInvalidOperation exception will be raised if the node is not a sequence. In
the example, we need to add another mapping to this sequence:
<source>
var
Product: TYamlNode;
begin
Product := Products.AddMapping;
Product.AddOrSetValue('sku', 'BL394D');
Product.AddOrSetValue('quantity', 4);
// etc...
end;
</source>
Once you have constructed your document, you can save it to a file or stream
using the Save method, or convert it to YAML using the ToYaml method:
<source>
var
Yaml: String;
begin
Yaml := Doc.ToYaml;
end;
</source>
You can pass an optional TYamlOutputSettings record to customize the YAML
formatting.
@bold(More Information)
There is more to Neslib.Yaml than described above. For more details you look
at the documentation in this unit. Additional usage samples can be found in
the unit tests, especially in the Tests.Neslib.Yaml.Sample.pas file.
@bold(License)
Neslib.Yaml is licensed under the Simplified BSD License.
See License.txt for details. *)
{$SCOPEDENUMS ON}
interface
uses
System.Classes,
System.SysUtils,
System.Generics.Collections,
Neslib.Utf8,
Neslib.LibYaml;
type
{ Exception type that is raised on parsing errors. }
EYamlParserError = class(Exception)
{$REGION 'Internal Declarations'}
private
FLineNumber: Integer;
FColumnNumber: Integer;
FPosition: Integer;
private
constructor Create(const AParser: Pyaml_parser_t); overload;
constructor Create(const AParser: Pyaml_parser_t;
const AMsg: String); overload;
{$ENDREGION 'Internal Declarations'}
public
constructor Create(const AMsg: String); overload;
constructor Create(const AMsg: String; const ALineNumber,
AColumnNumber, APosition: Integer); overload;
{ The line number of the error in the source text, starting at 1. }
property LineNumber: Integer read FLineNumber;
{ The column number of the error in the source text, starting at 1. }
property ColumnNumber: Integer read FColumnNumber;
{ The position of the error in the source text, starting at 0.
The position is the offset (in characters) from the beginning of the
text. }
property Position: Integer read FPosition;
end;
type
{ Exception type that is raised on emitting (output) errors. }
EYamlEmitterError = class(Exception)
{$REGION 'Internal Declarations'}
private
constructor Create(const AEmitter: Pyaml_emitter_t); overload;
{$ENDREGION 'Internal Declarations'}
end;
type
{ Types of YAML nodes. }
TYamlNodeType = (
{ An unassigned node }
Null,
{ A scalar (a string value) }
Scalar,
{ A sequence (aka array) of other nodes }
Sequence,
{ A mapping (aka dictionary) or other nodes }
Mapping,
{ An alias to another node }
Alias);
type
{ Flags that apply to TYamlNode's of type Scalar }
TYamlScalarFlag = (
{ Is set if the node tag may be omitted whenever the scalar value is
presented in the Plain style. }
PlainImplicit,
{ Is set if the node tag may be omitted whenever the scalar value is
presented in any non-Plain style. }
QuotedImplicit);
TYamlScalarFlags = set of TYamlScalarFlag;
type
{ Style of a Scalar value as it appears in the YAML source, or as it should
be written to the YAML target. }
TYamlScalarStyle = (
{ When writing the value, the writer can choose any style it finds
appropriate. }
Any,
{ Plain style (regular string) }
Plain,
{ String enclosed in single quotes }
SingleQuoted,
{ String enclosed in double quotes }
DoubleQuoted,
{ Literal style (with the '|' symbol).
Newlines are preserved. }
Literal,
{ Folded style (with the '>' symbol).
Newlines become spaces. }
Folded);
type
{ Style of a Sequence value as it appears in the YAML source, or as it should
be written to the YAML target. }
TYamlSequenceStyle = (
{ When writing the sequence, the writer can choose any style it finds
appropriate. }
Any,
{ Block style, as in:
- value1
- value2
- etc... }
Block,
{ Flow style, as in:
[value1, value2, etc...] }
Flow);
type
{ Style of a Mapping value as it appears in the YAML source, or as it should
be written to the YAML target. }
TYamlMappingStyle = (
{ When writing the mapping, the writer can choose any style it finds
appropriate. }
Any,
{ Block style, as in:
key1: value1
key2: value2
etc... }
Block,
(* Flow style, as in:
{ key1: value1, key2: value2, etc... } *)
Flow);
type
{ Flags that apply to a IYamlDocument }
TYamlDocumentFlag = (
{ The document start indicator (---) is implicit.
It is not present in the input source, and should not be written to the
target. }
ImplicitStart,
{ The document end indicator (...) is implicit.
It is not present in the input source, and should not be written to the
target. }
ImplicitEnd);
TYamlDocumentFlags = set of TYamlDocumentFlag;
type
{ Line break types }
TYamlLineBreak = (
{ Let the writer choose the line break type. }
Any,
{ Use CR (Carriage Return) for line breaks (Mac style). }
CR,
{ Use LF (Line Feed) for line breaks (Unix style). }
LF,
{ Use CR+LF (Carriage Return + Line Feed) line breaks (Windows style). }
CRLF);
type
{ YAML version information. }
TYamlVersion = record
public
{ Major version number. 0 if not specified. }
Major: Integer;
{ Minor version number. 0 if not specified. }
Minor: Integer;
public
{ Initializes a version.
Parameters:
AMajor: Major version number. 0 if not specified.
AMinor: Minor version number. 0 if not specified. }
procedure Initialize(const AMajor: Integer = 0; const AMinor: Integer = 0); inline;
class function Create(const AMajor: Integer = 0; const AMinor: Integer = 0): TYamlVersion; static;
end;
const
(* Common YAML tags, as found in the YAML tag repository (https://yaml.org/type/) *)
{ Prefix of all common YAML tags }
YAML_TAG_PREFIX = 'tag:yaml.org,2002:';
(* Collection Types *)
{ Unordered set of key: value pairs without duplicates. }
YAML_TAG_MAP = YAML_TAG_PREFIX + 'map';
{ Ordered sequence of key: value pairs without duplicates. }
YAML_TAG_OAP = YAML_TAG_PREFIX + 'omap';
{ Ordered sequence of key: value pairs allowing duplicates. }
YAML_TAG_PAIRS = YAML_TAG_PREFIX + 'pairs';
{ Unordered set of non-equal values. }
YAML_TAG_SET = YAML_TAG_PREFIX + 'set';
{ Sequence of arbitrary values. }
YAML_TAG_SEQ = YAML_TAG_PREFIX + 'seq';
(* Scalar Types *)
{ A sequence of zero or more octets (8 bit values). }
YAML_TAG_BINARY = YAML_TAG_PREFIX + 'binary';
{ Mathematical Booleans. }
YAML_TAG_BOOL = YAML_TAG_PREFIX + 'bool';
{ Floating-point approximation to real numbers. }
YAML_TAG_FLOAT = YAML_TAG_PREFIX + 'float';
{ Mathematical integers. }
YAML_TAG_INT = YAML_TAG_PREFIX + 'int';
{ Specify one or more mappings to be merged with the current one. }
YAML_TAG_MERGE = YAML_TAG_PREFIX + 'merge';
{ Devoid of value. }
YAML_TAG_NULL = YAML_TAG_PREFIX + 'null';
{ A sequence of zero or more Unicode characters. }
YAML_TAG_STR = YAML_TAG_PREFIX + 'str';
{ A point in time. }
YAML_TAG_TIMESTAMP = YAML_TAG_PREFIX + 'timestamp';
{ Specify the default value of a mapping. }
YAML_TAG_VALUE = YAML_TAG_PREFIX + 'value';
{ Keys for encoding YAML in YAML. }
YAML_TAG_YAML = YAML_TAG_PREFIX + 'yaml';
type
{ A YAML tag directive }
TYamlTagDirective = record
public
{ The tag handle (eg. '!e!' in '%TAG !e! tag:e.com:') }
Handle: UTF8String;
{ The tag prefix (eg. 'tag:e.com:' in '%TAG !e! tag:e.com:') }
Prefix: UTF8String;
public
{ Initializes a tag directive.
Parameters:
AHandle: the tag handle.
APrefix: the tag prefix. }
procedure Initialize(const AHandle, APrefix: UTF8String); inline;
class function Create(const AHandle, APrefix: UTF8String): TYamlTagDirective; static;
end;
type
{ An array of YAML tag directives }
TYamlTagDirectives = TArray<TYamlTagDirective>;
type
{ Various settings to control YAML output. }
TYamlOutputSettings = record
public
{ Whether the output should be in "canonical" format as in the YAML
specification.
Defaults to False. }
Canonical: Boolean;
{ The indentation increment. That is, the number of spaces to use for
indentation.
Defaults to 2. }
Indent: Integer;
{ Preferred line with, or -1 for unlimited.
Defaults to -1. }
LineWidth: Integer;
{ Preferred line break.
Defaults to Any. }
LineBreak: TYamlLineBreak;
public
{ Initializes to default values. }
procedure Initialize; inline;
class function Create: TYamlOutputSettings; static;
end;
type
PYamlNode = ^TYamlNode;
PYamlElement = ^TYamlElement;
{ Allows for the use of non-string keys in YAML mappings.
You only need this interface if you need to add a value to a mapping using
a key that is not a string. Otherwise, it is easier to just use
TYamlNode.AddOrSetValue with a string key instead.
To create an object that implements this interface, use
TYamlNode.CreateSequenceKey, TYamlNode.CreateMappingKey,
TYamlNode.CreateAliasKey or TYamlNode.CreateScalarKey. }
IYamlKey = interface
['{799EA14F-081E-4C02-A50C-1260BD93F8E4}']
{$REGION 'Internal Declarations'}
function GetNode: PYamlNode;
{$ENDREGION 'Internal Declarations'}
{ Returns the YAML node for this key (actually a pointer to it). Depending
on the type of this node, you can start adding other nodes to it. }
property Node: PYamlNode read GetNode;
end;
{ The base type for the YAML object model. Every possible type of YAML node
can be represented with a TYamlNode record.
Memory management is automatic. All values are owned by a IYamlDocument,
which takes care of destroying these values when the document is
destroyed. }
TYamlNode = record
{$REGION 'Internal Declarations'}
private const
TYPE_BITS = 3;
TYPE_MASK = (1 shl TYPE_BITS) - 1;
VALUE_BITS = (SizeOf(UIntPtr) * 8) - TYPE_BITS;
VALUE_MASK = UIntPtr.MaxValue - TYPE_MASK;
private const
TYPE_NULL = UIntPtr(Ord(TYamlNodeType.Null));
TYPE_SCALAR = UIntPtr(Ord(TYamlNodeType.Scalar));
TYPE_SEQUENCE = UIntPtr(Ord(TYamlNodeType.Sequence));
TYPE_MAPPING = UIntPtr(Ord(TYamlNodeType.Mapping));
TYPE_ALIAS = UIntPtr(Ord(TYamlNodeType.Alias));
private const
EMPTY_HASH = -1;
private type
TAnchors = TDictionary<UTF8String, UIntPtr>;
private type
TNode = record
public
FAnchor: PUTF8Char;
FTag: PUTF8Char;
FHash: Integer;
function GetAnchor: String; inline;
function GetTag: String; inline;
procedure SetAnchor(const AValue: String);
procedure SetTag(const AValue: String);
public
procedure Init(const ASelf: UIntPtr; const AAnchors: TAnchors;
const AAnchor, ATag: PUTF8Char);
procedure Free; inline;
function Equals(const AOther: TNode): Boolean;
property Anchor: String read GetAnchor write SetAnchor;
property Tag: String read GetTag write SetTag;
end;
PNode = ^TNode;
private type
{ First two items *must* match TYamlScalarFlag }
TScalarFlag = (PlainImplicit, QuotedImplicit, OwnsValue);
TScalarFlags = set of TScalarFlag;
TScalar = record
private
FBase: TNode;
FValue: PUTF8Char;
FValueLength: Integer;
FFlags: TScalarFlags;
FStyle: TYamlScalarStyle;
function GetFlags: TYamlScalarFlags; inline;
procedure SetFlags(const AValue: TYamlScalarFlags); inline;
public
procedure Free; inline;
function CalculateHashCode: Integer;
function Equals(const AOther: TScalar; const AStrict: Boolean): Boolean;
procedure Emit(const AEmitter: Pyaml_emitter_t);
function ToBoolean(const ADefault: Boolean): Boolean;
function ToInt32(const ADefault: Int32): Int32;
function ToInt64(const ADefault: Int64): Int64;
function ToDouble(const ADefault: Double): Double; inline;
function ToString(const ADefault: String): String; inline;
property Flags: TYamlScalarFlags read GetFlags write SetFlags;
end;
PScalar = ^TScalar;
type
TSequence = record
private
FBase: TNode;
FNodes: PYamlNode;
FCount: Integer;
FCapacity: Integer;
FImplicit: Boolean;
FStyle: TYamlSequenceStyle;
private
procedure Grow;
public
procedure Free; inline;
function CalculateHashCode: Integer;
function Equals(const AOther: TSequence; const AStrict: Boolean): Boolean;
procedure Emit(const AEmitter: Pyaml_emitter_t);
procedure Add(const ANode: TYamlNode);
function Get(const AIndex: Integer): TYamlNode;
procedure Delete(const AIndex: Integer);
procedure Clear;
end;
PSequence = ^TSequence;
private type
TElement = record
public
Key: UIntPtr; // TYamlNode
Value: UIntPtr; // TYamlNode
public
procedure Free; inline;
function Equals(const AOther: TElement; const AStrict: Boolean): Boolean;
function GetHashCode: Integer; inline;
end;
PElement = ^TElement;
private type
TMapEntry = record
public
HashCode: Integer;
Key: UIntPtr; // TYamlNode
Index: Integer;
end;
PMapEntry = ^TMapEntry;
private type
TIndexMap = record
private
FEntries: PMapEntry;
FCount: Integer;
FCapacity: Integer;
FGrowThreshold: Integer;
private
procedure Resize(ANewSize: Integer);
public
procedure Free;
procedure Clear; inline;
function Get(const AKey: TYamlNode): Integer;
procedure Add(const AKey: TYamlNode; const AIndex: Integer);
end;
PIndexMap = ^TIndexMap;
private type
TMapping = record
private const
{ We use an FIndices map to map names to indices. However, for small
maps it is faster and more memory efficient to just perform a linear
search. So we only use the index map if the number of items reaches this
value. }
INDICES_COUNT_THRESHOLD = 12;
private const
{ We have optimized code for small key lengths. This code avoid dynamic
memory allocations. For larger key lengths, a slower path is used that
involves allocations. }
MAX_FAST_KEY_LENGTH = 32;
{ The maximum size an UTF-8 has to be to accomodate MAX_FAST_KEY_LENGTH
UTF-16 characters. A single UTF-16 character is encoded to a maximum of
3 UTF-8 characters. }
UTF8_BUFFER_SIZE = (MAX_FAST_KEY_LENGTH * 3) + 8;
private
FBase: TNode;
FElements: PElement;
FIndices: PIndexMap;
FCount: Integer;
FCapacity: Integer;
FImplicit: Boolean;
FStyle: TYamlMappingStyle;
private
procedure RebuildIndices;
public
procedure Free; inline;
function CalculateHashCode: Integer;
function Equals(const AOther: TMapping; const AStrict: Boolean): Boolean;
procedure Emit(const AEmitter: Pyaml_emitter_t);
procedure AddOrReplaceValue(const AKey, AValue: TYamlNode); overload;
procedure AddOrReplaceValue(const AKey: IYamlKey; const AValue: TYamlNode); overload;
procedure AddOrReplaceValue(const AKey: String; const AValue: TYamlNode); overload;
function GetElement(const AIndex: Integer): PYamlElement;
function GetValue(const AKey: TYamlNode): TYamlNode; overload;
function GetValue(const AKey: String): TYamlNode; overload;
function TryGetValue(const AKey: TYamlNode; out AValue: TYamlNode): Boolean; overload;
function TryGetValue(const AKey: String; out AValue: TYamlNode): Boolean; overload;
function IndexOfKey(const AKey: TYamlNode): Integer; overload;
function IndexOfKey(const AKey: String): Integer; overload;
function IndexOfKey(const AKey: PUTF8Char; const ALength: Integer): Integer; overload;
function IndexOfKeySlow(const AKey: String): Integer;
function Contains(const AKey: TYamlNode): Boolean; overload;
function Contains(const AKey: String): Boolean; overload;
procedure Remove(const AKey: TYamlNode); overload;
procedure Remove(const AKey: String); overload;
procedure Delete(const AIndex: Integer);
procedure Clear;
end;
PMapping = ^TMapping;
type
TAlias = record
private
FBase: TNode;
FTarget: UIntPtr; // TYamlNode
public
procedure Free; inline;
function CalculateHashCode: Integer;
function Equals(const AOther: TAlias; const AStrict: Boolean): Boolean;
procedure Emit(const AEmitter: Pyaml_emitter_t);
end;
PAlias = ^TAlias;
private
{ The lowest 2 bits of FBits contain the type of node. The other bits
contain a pointer to the actual implementation (PScalar, PSequence or
PMapping).
Note that the pointer value is calculated by setting the lowest 2 bits to
0. This is legal since Delphi always allocates dynamic memory at 8-byte
aligned addresses. }
FBits: UIntPtr;
function GetNodeType: TYamlNodeType; inline;
function GetIsNil: Boolean; inline;
function GetIsAlias: Boolean; inline;
function GetIsMapping: Boolean; inline;
function GetIsScalar: Boolean; inline;
function GetIsSequence: Boolean; inline;
function GetCount: Integer; inline;
function GetNode(const AIndex: Integer): TYamlNode; inline;
function GetValue(const AKey: String): TYamlNode; inline;
function GetValueByNode(const AKey: TYamlNode): TYamlNode; inline;
function GetElement(const AIndex: Integer): PYamlElement; inline;
function GetAnchor: String; inline;
function GetTag: String; inline;
procedure SetAnchor(const AValue: String);
procedure SetTag(const AValue: String);
function GetScalarStyle: TYamlScalarStyle; inline;
procedure SetScalarStyle(const AValue: TYamlScalarStyle); inline;
function GetScalarFlags: TYamlScalarFlags; inline;
procedure SetScalarFlags(const AValue: TYamlScalarFlags); inline;
function GetSequenceStyle: TYamlSequenceStyle; inline;
procedure SetSequenceStyle(const AValue: TYamlSequenceStyle); inline;
function GetMappingStyle: TYamlMappingStyle; inline;
procedure SetMappingStyle(const AValue: TYamlMappingStyle); inline;
function GetTarget: TYamlNode; inline;
private
class function ParseInternal(const AParser: Pyaml_parser_t;
const AAnchors: TAnchors; var ANodeEvent: yaml_event_t): TYamlNode; static;
private
class function CreateScalar(const AValue: UTF8String): TYamlNode; overload; static;
class function CreateScalar(const AValue: String): TYamlNode; overload; inline; static;
class function CreateScalar(const AValue: Boolean): TYamlNode; overload; inline; static;
class function CreateScalar(const AValue: PUTF8Char; const AValueLength: Integer;
const AOwnsValue: Boolean): TYamlNode; overload; static;
class function CreateScalar(const AAnchors: TAnchors;
var AEvent: yaml_scalar_event_t): TYamlNode; overload; static;
class function CreateSequence: TYamlNode; overload; static;
class function CreateSequence(const AAnchors: TAnchors;
var AEvent: yaml_sequence_start_event_t): TYamlNode; overload; static;
class function CreateMapping: TYamlNode; overload; static;
class function CreateMapping(const AAnchors: TAnchors;
var AEvent: yaml_mapping_start_event_t): TYamlNode; overload; static;
class function CreateAlias(const ATarget: TYamlNode): TYamlNode; static;
private
procedure Free;
function CalculateHashCode: Integer;
procedure Emit(const AEmitter: Pyaml_emitter_t);
function Equals(const AOther: TYamlNode; const AStrict: Boolean): Boolean;
{$ENDREGION 'Internal Declarations'}
public
{ Implicit operators that convert a TYamlNode to another type.
These operators never raise an exception, but return a zero-value (such as
0, False or an empty string) if the TYamlNode cannot be converted. }
class operator Implicit(const ANode: TYamlNode): Boolean; inline; static;
class operator Implicit(const ANode: TYamlNode): Int8; inline; static;
class operator Implicit(const ANode: TYamlNode): UInt8; inline; static;
class operator Implicit(const ANode: TYamlNode): Int16; inline; static;
class operator Implicit(const ANode: TYamlNode): UInt16; inline; static;
class operator Implicit(const ANode: TYamlNode): Int32; inline; static;
class operator Implicit(const ANode: TYamlNode): UInt32; inline; static;
class operator Implicit(const ANode: TYamlNode): Int64; inline; static;
class operator Implicit(const ANode: TYamlNode): UInt64; inline; static;
class operator Implicit(const ANode: TYamlNode): Single; inline; static;
class operator Implicit(const ANode: TYamlNode): Double; inline; static;
class operator Implicit(const ANode: TYamlNode): String; inline; static;
{ Tests two TYamlNode's for (in)equality, based on their data type. Performs
a "deep" equality testing, meaning that for mappings and sequences, it
also check for equality of the nodes this node owns.
The equality operators do *not* take Tag and Ancor into account. To check
these as well, use the StrictEquals method. }
class operator Equal(const ALeft, ARight: TYamlNode): Boolean; inline; static;
class operator NotEqual(const ALeft, ARight: TYamlNode): Boolean; inline; static;
{ Performs a strict equality test of two nodes. Unlike the overloaded '='
operator, this also checks for equality of the Tag and Anchor properties. }
function StrictEquals(const AOther: TYamlNode): Boolean; inline;
{ Get the hash code for this node. Will always be non-negative.
Does *not* take Tag, Anchor and other metadata into account. }
function GetHashCode: Integer; inline;
{ Converts the TYamlNode to another type if possible, or returns a default
value if conversion is not possible.
Parameters:
ADefault: (optional) default value to return in case the TYamlNode
cannot be converted.
Returns:
The converted value, or ADefault if the value cannot be converted.
Only Scalar and Alias nodes can be converted.
These methods never raise an exception. }
function ToBoolean(const ADefault: Boolean = False): Boolean;
function ToInteger(const ADefault: Integer = 0): Integer; inline; // Alias for ToInt32
function ToInt32(const ADefault: Int32 = 0): Int32;
function ToInt64(const ADefault: Int64 = 0): Int64;
function ToDouble(const ADefault: Double = 0): Double;
function ToString(const ADefault: String = ''): String;
{ The type of this node. }
property NodeType: TYamlNodeType read GetNodeType;
{ Whether this is an unassigned node }
property IsNil: Boolean read GetIsNil;
{ Whether this is a Scalar node (a string value) }
property IsScalar: Boolean read GetIsScalar;
{ Whether this is a Sequence node (an array of other nodes) }
property IsSequence: Boolean read GetIsSequence;
{ Whether this is a Mapping node (a dictionary of key/value pairs) }
property IsMapping: Boolean read GetIsMapping;
{ Whether this is an Alias node (an alias to another node) }
property IsAlias: Boolean read GetIsAlias;
{ The node anchor }
property Anchor: String read GetAnchor write SetAnchor;
{ The node tag. Should either start with ! (local tag) or be a valid
URL (global tag). }
property Tag: String read GetTag write SetTag;
public
(*************************************************************************)
(* The methods in this section only apply to Scalars (that is, if *)
(* IsScalar returns True). Unless stated otherwise, they raise an *)
(* EInvalidOperation exception if this is not Scalar. *)
(*************************************************************************)
{ The scalar style used (or to use) to format the node. }
property ScalarStyle: TYamlScalarStyle read GetScalarStyle write SetScalarStyle;
{ The scalar flags for this node }
property ScalarFlags: TYamlScalarFlags read GetScalarFlags write SetScalarFlags;
public
(*************************************************************************)
(* The methods in this section only apply to Sequences and Mappings *)
(* (that is, if IsSequence or IsMapping returns True). Unless stated *)
(* otherwise, they raise an EInvalidOperation exception if this is not *)
(* a Sequence of Mapping. *)
(*************************************************************************)
{ Deletes an item from a sequence or mapping.
Parameters:
AIndex: index of the item to delete.
Raises:
EInvalidOperation if this is not a sequence or mapping.
EArgumentOutOfRangeException if AIndex is out of bounds. }
procedure Delete(const AIndex: Integer); inline;
{ Clears the sequence or mapping.
Raises:
EInvalidOperation if this is not a sequence or mapping. }
procedure Clear; inline;
{ Returns the number of items in the sequence or mapping.
This property NEVER raises an exception. Instead, it returns 0 if this is
not a sequence or mapping. }
property Count: Integer read GetCount;
public
(*************************************************************************)
(* The methods in this section only apply to Sequences (that is, if *)
(* IsSequence returns True). Unless stated otherwise, they raise an *)
(* EInvalidOperation exception if this is not a Sequence. *)
(*************************************************************************)
{ Adds a value to the end of the sequence.
Parameters:
AValue: the value to add.
Returns:
The newly added node with this value.
Raises:
EInvalidOperation if this is not a sequence. }
function Add(const AValue: Boolean): TYamlNode; overload; inline;
function Add(const AValue: Int32): TYamlNode; overload; inline;
function Add(const AValue: UInt32): TYamlNode; overload; inline;
function Add(const AValue: Int64): TYamlNode; overload; inline;
function Add(const AValue: UInt64): TYamlNode; overload; inline;
function Add(const AValue: Single): TYamlNode; overload; inline;
function Add(const AValue: Double): TYamlNode; overload; inline;
function Add(const AValue: String): TYamlNode; overload; inline;
{ Creates a Sequence and adds it to the end of this Sequence.
Returns:
The newly created Sequence.
Raises:
EInvalidOperation if this is not a sequence. }
function AddSequence: TYamlNode; inline;
{ Creates a Mapping and adds it to the end of this Sequence.
Returns:
The newly created Mapping.
Raises:
EInvalidOperation if this is not a sequence. }
function AddMapping: TYamlNode; inline;
{ Creates an Alias and adds it to the end of this Sequence.
Parameters:
AAnchor: the anchor that the alias refers to.
Returns:
The newly created Alias.
Raises:
EInvalidOperation if this is not a sequence or AAnchor is null.
Note: AAnchor *must* belong to the same IYamlDocument as this node.
Behavior is undefined (or leads to crashes) if this is not the case. }
function AddAlias(const AAnchor: TYamlNode): TYamlNode; inline;
{ The nodes in this sequence.
Unlike the other sequence-methods, this property NEVER raises an
exception. Instead, it returns a Null value if this is not a Sequence or
AIndex is out of range.
This allows for chaining without having to check every intermediate step,
as in Foo.Items[1].Items[3].Items[2].ToInteger. }
property Nodes[const AIndex: Integer]: TYamlNode read GetNode;
{ The sequence style used (or to use) to format the node. }
property SequenceStyle: TYamlSequenceStyle read GetSequenceStyle write SetSequenceStyle;
public
(*************************************************************************)
(* The methods in this section only apply to Mappings (that is, if *)
(* IsMapping returns True). Unless stated otherwise, they raise an *)
(* EInvalidOperation exception if this is not a Mapping. *)
(*************************************************************************)
{ Creates a sequence key for use with one of the AddOrSet* methods.
You only need to use this method for non-string keys.
You can use the Node property of the returned key to add nodes to the
sequence. Only once the sequence has been completely initialized, should
you use it as a key for one of the AddOrSet* methods. }
class function CreateSequenceKey: IYamlKey; static;
{ Creates a mapping key for use with one of the AddOrSet* methods.
You only need to use this method for non-string keys.
You can use the Node property of the returned key to add key/value pairs
to the mapping. Only once the mapping has been completely initialized,
should you use it as a key for one of the AddOrSet* methods. }
class function CreateMappingKey: IYamlKey; static;