blob: aa4bae35d1a43e8443b447d093a6962a6e078c2f [file] [log] [blame]
Nick Kledzikf60a9272012-12-12 20:46:15 +00001=====================
2YAML I/O
3=====================
4
5.. contents::
6 :local:
7
8Introduction to YAML
9====================
10
11YAML is a human readable data serialization language. The full YAML language
12spec can be read at `yaml.org
13<http://www.yaml.org/spec/1.2/spec.html#Introduction>`_. The simplest form of
14yaml is just "scalars", "mappings", and "sequences". A scalar is any number
15or string. The pound/hash symbol (#) begins a comment line. A mapping is
16a set of key-value pairs where the key ends with a colon. For example:
17
18.. code-block:: yaml
19
20 # a mapping
21 name: Tom
22 hat-size: 7
23
24A sequence is a list of items where each item starts with a leading dash ('-').
25For example:
26
27.. code-block:: yaml
28
29 # a sequence
30 - x86
31 - x86_64
32 - PowerPC
33
34You can combine mappings and sequences by indenting. For example a sequence
35of mappings in which one of the mapping values is itself a sequence:
36
37.. code-block:: yaml
38
39 # a sequence of mappings with one key's value being a sequence
40 - name: Tom
41 cpus:
42 - x86
43 - x86_64
44 - name: Bob
45 cpus:
46 - x86
47 - name: Dan
48 cpus:
49 - PowerPC
50 - x86
51
52Sometime sequences are known to be short and the one entry per line is too
53verbose, so YAML offers an alternate syntax for sequences called a "Flow
54Sequence" in which you put comma separated sequence elements into square
55brackets. The above example could then be simplified to :
56
57
58.. code-block:: yaml
59
60 # a sequence of mappings with one key's value being a flow sequence
61 - name: Tom
62 cpus: [ x86, x86_64 ]
63 - name: Bob
64 cpus: [ x86 ]
65 - name: Dan
66 cpus: [ PowerPC, x86 ]
67
68
69Introduction to YAML I/O
70========================
71
72The use of indenting makes the YAML easy for a human to read and understand,
73but having a program read and write YAML involves a lot of tedious details.
74The YAML I/O library structures and simplifies reading and writing YAML
75documents.
76
77YAML I/O assumes you have some "native" data structures which you want to be
78able to dump as YAML and recreate from YAML. The first step is to try
79writing example YAML for your data structures. You may find after looking at
80possible YAML representations that a direct mapping of your data structures
81to YAML is not very readable. Often the fields are not in the order that
82a human would find readable. Or the same information is replicated in multiple
83locations, making it hard for a human to write such YAML correctly.
84
85In relational database theory there is a design step called normalization in
86which you reorganize fields and tables. The same considerations need to
87go into the design of your YAML encoding. But, you may not want to change
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +000088your existing native data structures. Therefore, when writing out YAML
Nick Kledzikf60a9272012-12-12 20:46:15 +000089there may be a normalization step, and when reading YAML there would be a
90corresponding denormalization step.
91
92YAML I/O uses a non-invasive, traits based design. YAML I/O defines some
93abstract base templates. You specialize those templates on your data types.
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +000094For instance, if you have an enumerated type FooBar you could specialize
Nick Kledzikf60a9272012-12-12 20:46:15 +000095ScalarEnumerationTraits on that type and define the enumeration() method:
96
97.. code-block:: c++
98
99 using llvm::yaml::ScalarEnumerationTraits;
100 using llvm::yaml::IO;
101
102 template <>
103 struct ScalarEnumerationTraits<FooBar> {
104 static void enumeration(IO &io, FooBar &value) {
105 ...
106 }
107 };
108
109
110As with all YAML I/O template specializations, the ScalarEnumerationTraits is used for
111both reading and writing YAML. That is, the mapping between in-memory enum
Daniel Dunbarbf2e7b52013-05-20 22:39:48 +0000112values and the YAML string representation is only in one place.
Nick Kledzikf60a9272012-12-12 20:46:15 +0000113This assures that the code for writing and parsing of YAML stays in sync.
114
115To specify a YAML mappings, you define a specialization on
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000116llvm::yaml::MappingTraits.
Nick Kledzikf60a9272012-12-12 20:46:15 +0000117If your native data structure happens to be a struct that is already normalized,
118then the specialization is simple. For example:
119
120.. code-block:: c++
121
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000122 using llvm::yaml::MappingTraits;
Nick Kledzikf60a9272012-12-12 20:46:15 +0000123 using llvm::yaml::IO;
124
125 template <>
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000126 struct MappingTraits<Person> {
Nick Kledzikf60a9272012-12-12 20:46:15 +0000127 static void mapping(IO &io, Person &info) {
128 io.mapRequired("name", info.name);
129 io.mapOptional("hat-size", info.hatSize);
130 }
131 };
132
133
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000134A YAML sequence is automatically inferred if you data type has begin()/end()
Nick Kledzikf60a9272012-12-12 20:46:15 +0000135iterators and a push_back() method. Therefore any of the STL containers
136(such as std::vector<>) will automatically translate to YAML sequences.
137
138Once you have defined specializations for your data types, you can
139programmatically use YAML I/O to write a YAML document:
140
141.. code-block:: c++
142
143 using llvm::yaml::Output;
144
145 Person tom;
146 tom.name = "Tom";
147 tom.hatSize = 8;
148 Person dan;
149 dan.name = "Dan";
150 dan.hatSize = 7;
151 std::vector<Person> persons;
152 persons.push_back(tom);
153 persons.push_back(dan);
154
155 Output yout(llvm::outs());
156 yout << persons;
157
158This would write the following:
159
160.. code-block:: yaml
161
162 - name: Tom
163 hat-size: 8
164 - name: Dan
165 hat-size: 7
166
167And you can also read such YAML documents with the following code:
168
169.. code-block:: c++
170
171 using llvm::yaml::Input;
172
173 typedef std::vector<Person> PersonList;
174 std::vector<PersonList> docs;
175
176 Input yin(document.getBuffer());
177 yin >> docs;
178
179 if ( yin.error() )
180 return;
181
182 // Process read document
183 for ( PersonList &pl : docs ) {
184 for ( Person &person : pl ) {
185 cout << "name=" << person.name;
186 }
187 }
188
189One other feature of YAML is the ability to define multiple documents in a
190single file. That is why reading YAML produces a vector of your document type.
191
192
193
194Error Handling
195==============
196
197When parsing a YAML document, if the input does not match your schema (as
198expressed in your XxxTraits<> specializations). YAML I/O
199will print out an error message and your Input object's error() method will
200return true. For instance the following document:
201
202.. code-block:: yaml
203
204 - name: Tom
205 shoe-size: 12
206 - name: Dan
207 hat-size: 7
208
209Has a key (shoe-size) that is not defined in the schema. YAML I/O will
210automatically generate this error:
211
212.. code-block:: yaml
213
214 YAML:2:2: error: unknown key 'shoe-size'
215 shoe-size: 12
216 ^~~~~~~~~
217
218Similar errors are produced for other input not conforming to the schema.
219
220
221Scalars
222=======
223
224YAML scalars are just strings (i.e. not a sequence or mapping). The YAML I/O
225library provides support for translating between YAML scalars and specific
226C++ types.
227
228
229Built-in types
230--------------
231The following types have built-in support in YAML I/O:
232
233* bool
234* float
235* double
236* StringRef
John Thompson48e018a2013-11-19 17:28:21 +0000237* std::string
Nick Kledzikf60a9272012-12-12 20:46:15 +0000238* int64_t
239* int32_t
240* int16_t
241* int8_t
242* uint64_t
243* uint32_t
244* uint16_t
245* uint8_t
246
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000247That is, you can use those types in fields of MappingTraits or as element type
Nick Kledzikf60a9272012-12-12 20:46:15 +0000248in sequence. When reading, YAML I/O will validate that the string found
249is convertible to that type and error out if not.
250
251
252Unique types
253------------
254Given that YAML I/O is trait based, the selection of how to convert your data
255to YAML is based on the type of your data. But in C++ type matching, typedefs
256do not generate unique type names. That means if you have two typedefs of
257unsigned int, to YAML I/O both types look exactly like unsigned int. To
258facilitate make unique type names, YAML I/O provides a macro which is used
259like a typedef on built-in types, but expands to create a class with conversion
260operators to and from the base type. For example:
261
262.. code-block:: c++
263
264 LLVM_YAML_STRONG_TYPEDEF(uint32_t, MyFooFlags)
265 LLVM_YAML_STRONG_TYPEDEF(uint32_t, MyBarFlags)
266
267This generates two classes MyFooFlags and MyBarFlags which you can use in your
268native data structures instead of uint32_t. They are implicitly
269converted to and from uint32_t. The point of creating these unique types
270is that you can now specify traits on them to get different YAML conversions.
271
272Hex types
273---------
274An example use of a unique type is that YAML I/O provides fixed sized unsigned
275integers that are written with YAML I/O as hexadecimal instead of the decimal
276format used by the built-in integer types:
277
278* Hex64
279* Hex32
280* Hex16
281* Hex8
282
283You can use llvm::yaml::Hex32 instead of uint32_t and the only different will
284be that when YAML I/O writes out that type it will be formatted in hexadecimal.
285
286
287ScalarEnumerationTraits
288-----------------------
289YAML I/O supports translating between in-memory enumerations and a set of string
290values in YAML documents. This is done by specializing ScalarEnumerationTraits<>
291on your enumeration type and define a enumeration() method.
292For instance, suppose you had an enumeration of CPUs and a struct with it as
293a field:
294
295.. code-block:: c++
296
297 enum CPUs {
298 cpu_x86_64 = 5,
299 cpu_x86 = 7,
300 cpu_PowerPC = 8
301 };
302
303 struct Info {
304 CPUs cpu;
305 uint32_t flags;
306 };
307
308To support reading and writing of this enumeration, you can define a
309ScalarEnumerationTraits specialization on CPUs, which can then be used
310as a field type:
311
312.. code-block:: c++
313
314 using llvm::yaml::ScalarEnumerationTraits;
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000315 using llvm::yaml::MappingTraits;
Nick Kledzikf60a9272012-12-12 20:46:15 +0000316 using llvm::yaml::IO;
317
318 template <>
319 struct ScalarEnumerationTraits<CPUs> {
320 static void enumeration(IO &io, CPUs &value) {
321 io.enumCase(value, "x86_64", cpu_x86_64);
322 io.enumCase(value, "x86", cpu_x86);
323 io.enumCase(value, "PowerPC", cpu_PowerPC);
324 }
325 };
326
327 template <>
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000328 struct MappingTraits<Info> {
Nick Kledzikf60a9272012-12-12 20:46:15 +0000329 static void mapping(IO &io, Info &info) {
330 io.mapRequired("cpu", info.cpu);
331 io.mapOptional("flags", info.flags, 0);
332 }
333 };
334
Ed Maste8ed40ce2015-04-14 20:52:58 +0000335When reading YAML, if the string found does not match any of the strings
Nick Kledzikf60a9272012-12-12 20:46:15 +0000336specified by enumCase() methods, an error is automatically generated.
337When writing YAML, if the value being written does not match any of the values
338specified by the enumCase() methods, a runtime assertion is triggered.
339
340
341BitValue
342--------
343Another common data structure in C++ is a field where each bit has a unique
344meaning. This is often used in a "flags" field. YAML I/O has support for
345converting such fields to a flow sequence. For instance suppose you
346had the following bit flags defined:
347
348.. code-block:: c++
349
350 enum {
351 flagsPointy = 1
352 flagsHollow = 2
353 flagsFlat = 4
354 flagsRound = 8
355 };
356
Sean Silva0d65a762013-06-04 23:36:41 +0000357 LLVM_YAML_STRONG_TYPEDEF(uint32_t, MyFlags)
Nick Kledzikf60a9272012-12-12 20:46:15 +0000358
359To support reading and writing of MyFlags, you specialize ScalarBitSetTraits<>
360on MyFlags and provide the bit values and their names.
361
362.. code-block:: c++
363
364 using llvm::yaml::ScalarBitSetTraits;
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000365 using llvm::yaml::MappingTraits;
Nick Kledzikf60a9272012-12-12 20:46:15 +0000366 using llvm::yaml::IO;
367
368 template <>
369 struct ScalarBitSetTraits<MyFlags> {
370 static void bitset(IO &io, MyFlags &value) {
371 io.bitSetCase(value, "hollow", flagHollow);
372 io.bitSetCase(value, "flat", flagFlat);
373 io.bitSetCase(value, "round", flagRound);
374 io.bitSetCase(value, "pointy", flagPointy);
375 }
376 };
377
378 struct Info {
379 StringRef name;
380 MyFlags flags;
381 };
382
383 template <>
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000384 struct MappingTraits<Info> {
Nick Kledzikf60a9272012-12-12 20:46:15 +0000385 static void mapping(IO &io, Info& info) {
386 io.mapRequired("name", info.name);
387 io.mapRequired("flags", info.flags);
388 }
389 };
390
391With the above, YAML I/O (when writing) will test mask each value in the
392bitset trait against the flags field, and each that matches will
393cause the corresponding string to be added to the flow sequence. The opposite
394is done when reading and any unknown string values will result in a error. With
395the above schema, a same valid YAML document is:
396
397.. code-block:: yaml
398
399 name: Tom
400 flags: [ pointy, flat ]
401
Simon Atanasyan84242dc2014-05-23 08:07:09 +0000402Sometimes a "flags" field might contains an enumeration part
403defined by a bit-mask.
404
405.. code-block:: c++
406
407 enum {
408 flagsFeatureA = 1,
409 flagsFeatureB = 2,
410 flagsFeatureC = 4,
411
412 flagsCPUMask = 24,
413
414 flagsCPU1 = 8,
415 flagsCPU2 = 16
416 };
417
418To support reading and writing such fields, you need to use the maskedBitSet()
419method and provide the bit values, their names and the enumeration mask.
420
421.. code-block:: c++
422
423 template <>
424 struct ScalarBitSetTraits<MyFlags> {
425 static void bitset(IO &io, MyFlags &value) {
426 io.bitSetCase(value, "featureA", flagsFeatureA);
427 io.bitSetCase(value, "featureB", flagsFeatureB);
428 io.bitSetCase(value, "featureC", flagsFeatureC);
429 io.maskedBitSetCase(value, "CPU1", flagsCPU1, flagsCPUMask);
430 io.maskedBitSetCase(value, "CPU2", flagsCPU2, flagsCPUMask);
431 }
432 };
433
434YAML I/O (when writing) will apply the enumeration mask to the flags field,
435and compare the result and values from the bitset. As in case of a regular
436bitset, each that matches will cause the corresponding string to be added
437to the flow sequence.
Nick Kledzikf60a9272012-12-12 20:46:15 +0000438
439Custom Scalar
440-------------
441Sometimes for readability a scalar needs to be formatted in a custom way. For
442instance your internal data structure may use a integer for time (seconds since
443some epoch), but in YAML it would be much nicer to express that integer in
444some time format (e.g. 4-May-2012 10:30pm). YAML I/O has a way to support
445custom formatting and parsing of scalar types by specializing ScalarTraits<> on
446your data type. When writing, YAML I/O will provide the native type and
447your specialization must create a temporary llvm::StringRef. When reading,
Daniel Dunbar06b9f9e2013-08-16 23:30:19 +0000448YAML I/O will provide an llvm::StringRef of scalar and your specialization
Nick Kledzikf60a9272012-12-12 20:46:15 +0000449must convert that to your native data type. An outline of a custom scalar type
450looks like:
451
452.. code-block:: c++
453
454 using llvm::yaml::ScalarTraits;
455 using llvm::yaml::IO;
456
457 template <>
458 struct ScalarTraits<MyCustomType> {
Alex Lorenz684379a2015-05-01 18:20:23 +0000459 static void output(const T &value, void*, llvm::raw_ostream &out) {
Nick Kledzikf60a9272012-12-12 20:46:15 +0000460 out << value; // do custom formatting here
461 }
Alex Lorenz684379a2015-05-01 18:20:23 +0000462 static StringRef input(StringRef scalar, void*, T &value) {
Nick Kledzikf60a9272012-12-12 20:46:15 +0000463 // do custom parsing here. Return the empty string on success,
464 // or an error message on failure.
David Majnemer77880332014-04-10 07:37:33 +0000465 return StringRef();
Nick Kledzikf60a9272012-12-12 20:46:15 +0000466 }
David Majnemer77880332014-04-10 07:37:33 +0000467 // Determine if this scalar needs quotes.
468 static bool mustQuote(StringRef) { return true; }
Nick Kledzikf60a9272012-12-12 20:46:15 +0000469 };
Alex Lorenz68e787b2015-05-14 23:08:22 +0000470
471Block Scalars
472-------------
473
474YAML block scalars are string literals that are represented in YAML using the
475literal block notation, just like the example shown below:
476
477.. code-block:: yaml
478
479 text: |
480 First line
481 Second line
482
483The YAML I/O library provides support for translating between YAML block scalars
484and specific C++ types by allowing you to specialize BlockScalarTraits<> on
485your data type. The library doesn't provide any built-in support for block
486scalar I/O for types like std::string and llvm::StringRef as they are already
487supported by YAML I/O and use the ordinary scalar notation by default.
488
489BlockScalarTraits specializations are very similar to the
490ScalarTraits specialization - YAML I/O will provide the native type and your
491specialization must create a temporary llvm::StringRef when writing, and
492it will also provide an llvm::StringRef that has the value of that block scalar
493and your specialization must convert that to your native data type when reading.
494An example of a custom type with an appropriate specialization of
495BlockScalarTraits is shown below:
496
497.. code-block:: c++
498
499 using llvm::yaml::BlockScalarTraits;
500 using llvm::yaml::IO;
501
502 struct MyStringType {
503 std::string Str;
504 };
505
506 template <>
507 struct BlockScalarTraits<MyStringType> {
508 static void output(const MyStringType &Value, void *Ctxt,
509 llvm::raw_ostream &OS) {
510 OS << Value.Str;
511 }
512
513 static StringRef input(StringRef Scalar, void *Ctxt,
514 MyStringType &Value) {
515 Value.Str = Scalar.str();
516 return StringRef();
517 }
518 };
519
Nick Kledzikf60a9272012-12-12 20:46:15 +0000520
521
522Mappings
523========
524
525To be translated to or from a YAML mapping for your type T you must specialize
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000526llvm::yaml::MappingTraits on T and implement the "void mapping(IO &io, T&)"
Nick Kledzikf60a9272012-12-12 20:46:15 +0000527method. If your native data structures use pointers to a class everywhere,
528you can specialize on the class pointer. Examples:
529
530.. code-block:: c++
531
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000532 using llvm::yaml::MappingTraits;
Nick Kledzikf60a9272012-12-12 20:46:15 +0000533 using llvm::yaml::IO;
534
535 // Example of struct Foo which is used by value
536 template <>
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000537 struct MappingTraits<Foo> {
Nick Kledzikf60a9272012-12-12 20:46:15 +0000538 static void mapping(IO &io, Foo &foo) {
539 io.mapOptional("size", foo.size);
540 ...
541 }
542 };
543
544 // Example of struct Bar which is natively always a pointer
545 template <>
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000546 struct MappingTraits<Bar*> {
Nick Kledzikf60a9272012-12-12 20:46:15 +0000547 static void mapping(IO &io, Bar *&bar) {
548 io.mapOptional("size", bar->size);
549 ...
550 }
551 };
552
553
554No Normalization
555----------------
556
557The mapping() method is responsible, if needed, for normalizing and
558denormalizing. In a simple case where the native data structure requires no
559normalization, the mapping method just uses mapOptional() or mapRequired() to
560bind the struct's fields to YAML key names. For example:
561
562.. code-block:: c++
563
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000564 using llvm::yaml::MappingTraits;
Nick Kledzikf60a9272012-12-12 20:46:15 +0000565 using llvm::yaml::IO;
566
567 template <>
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000568 struct MappingTraits<Person> {
Nick Kledzikf60a9272012-12-12 20:46:15 +0000569 static void mapping(IO &io, Person &info) {
570 io.mapRequired("name", info.name);
571 io.mapOptional("hat-size", info.hatSize);
572 }
573 };
574
575
576Normalization
577----------------
578
579When [de]normalization is required, the mapping() method needs a way to access
580normalized values as fields. To help with this, there is
581a template MappingNormalization<> which you can then use to automatically
582do the normalization and denormalization. The template is used to create
583a local variable in your mapping() method which contains the normalized keys.
584
585Suppose you have native data type
586Polar which specifies a position in polar coordinates (distance, angle):
587
588.. code-block:: c++
589
590 struct Polar {
591 float distance;
592 float angle;
593 };
594
595but you've decided the normalized YAML for should be in x,y coordinates. That
596is, you want the yaml to look like:
597
598.. code-block:: yaml
599
600 x: 10.3
601 y: -4.7
602
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000603You can support this by defining a MappingTraits that normalizes the polar
Nick Kledzikf60a9272012-12-12 20:46:15 +0000604coordinates to x,y coordinates when writing YAML and denormalizes x,y
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000605coordinates into polar when reading YAML.
Nick Kledzikf60a9272012-12-12 20:46:15 +0000606
607.. code-block:: c++
608
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000609 using llvm::yaml::MappingTraits;
Nick Kledzikf60a9272012-12-12 20:46:15 +0000610 using llvm::yaml::IO;
611
612 template <>
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000613 struct MappingTraits<Polar> {
Nick Kledzikf60a9272012-12-12 20:46:15 +0000614
615 class NormalizedPolar {
616 public:
617 NormalizedPolar(IO &io)
618 : x(0.0), y(0.0) {
619 }
620 NormalizedPolar(IO &, Polar &polar)
621 : x(polar.distance * cos(polar.angle)),
622 y(polar.distance * sin(polar.angle)) {
623 }
624 Polar denormalize(IO &) {
Daniel Dunbarbf2e7b52013-05-20 22:39:48 +0000625 return Polar(sqrt(x*x+y*y), arctan(x,y));
Nick Kledzikf60a9272012-12-12 20:46:15 +0000626 }
627
628 float x;
629 float y;
630 };
631
632 static void mapping(IO &io, Polar &polar) {
633 MappingNormalization<NormalizedPolar, Polar> keys(io, polar);
634
635 io.mapRequired("x", keys->x);
636 io.mapRequired("y", keys->y);
637 }
638 };
639
640When writing YAML, the local variable "keys" will be a stack allocated
Rui Ueyama0ad114c2013-09-11 05:22:01 +0000641instance of NormalizedPolar, constructed from the supplied polar object which
Nick Kledzikf60a9272012-12-12 20:46:15 +0000642initializes it x and y fields. The mapRequired() methods then write out the x
643and y values as key/value pairs.
644
645When reading YAML, the local variable "keys" will be a stack allocated instance
646of NormalizedPolar, constructed by the empty constructor. The mapRequired
647methods will find the matching key in the YAML document and fill in the x and y
648fields of the NormalizedPolar object keys. At the end of the mapping() method
649when the local keys variable goes out of scope, the denormalize() method will
650automatically be called to convert the read values back to polar coordinates,
651and then assigned back to the second parameter to mapping().
652
653In some cases, the normalized class may be a subclass of the native type and
654could be returned by the denormalize() method, except that the temporary
655normalized instance is stack allocated. In these cases, the utility template
656MappingNormalizationHeap<> can be used instead. It just like
657MappingNormalization<> except that it heap allocates the normalized object
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000658when reading YAML. It never destroys the normalized object. The denormalize()
Nick Kledzikf60a9272012-12-12 20:46:15 +0000659method can this return "this".
660
661
662Default values
663--------------
664Within a mapping() method, calls to io.mapRequired() mean that that key is
665required to exist when parsing YAML documents, otherwise YAML I/O will issue an
666error.
667
668On the other hand, keys registered with io.mapOptional() are allowed to not
669exist in the YAML document being read. So what value is put in the field
670for those optional keys?
671There are two steps to how those optional fields are filled in. First, the
672second parameter to the mapping() method is a reference to a native class. That
673native class must have a default constructor. Whatever value the default
674constructor initially sets for an optional field will be that field's value.
675Second, the mapOptional() method has an optional third parameter. If provided
676it is the value that mapOptional() should set that field to if the YAML document
677does not have that key.
678
679There is one important difference between those two ways (default constructor
680and third parameter to mapOptional). When YAML I/O generates a YAML document,
681if the mapOptional() third parameter is used, if the actual value being written
682is the same as (using ==) the default value, then that key/value is not written.
683
684
685Order of Keys
686--------------
687
688When writing out a YAML document, the keys are written in the order that the
689calls to mapRequired()/mapOptional() are made in the mapping() method. This
690gives you a chance to write the fields in an order that a human reader of
691the YAML document would find natural. This may be different that the order
692of the fields in the native class.
693
694When reading in a YAML document, the keys in the document can be in any order,
695but they are processed in the order that the calls to mapRequired()/mapOptional()
696are made in the mapping() method. That enables some interesting
697functionality. For instance, if the first field bound is the cpu and the second
698field bound is flags, and the flags are cpu specific, you can programmatically
699switch how the flags are converted to and from YAML based on the cpu.
700This works for both reading and writing. For example:
701
702.. code-block:: c++
703
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000704 using llvm::yaml::MappingTraits;
Nick Kledzikf60a9272012-12-12 20:46:15 +0000705 using llvm::yaml::IO;
706
707 struct Info {
708 CPUs cpu;
709 uint32_t flags;
710 };
711
712 template <>
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000713 struct MappingTraits<Info> {
Nick Kledzikf60a9272012-12-12 20:46:15 +0000714 static void mapping(IO &io, Info &info) {
715 io.mapRequired("cpu", info.cpu);
716 // flags must come after cpu for this to work when reading yaml
717 if ( info.cpu == cpu_x86_64 )
718 io.mapRequired("flags", *(My86_64Flags*)info.flags);
719 else
720 io.mapRequired("flags", *(My86Flags*)info.flags);
721 }
722 };
723
724
Nick Kledzik1e6033c2013-11-14 00:59:59 +0000725Tags
726----
727
728The YAML syntax supports tags as a way to specify the type of a node before
729it is parsed. This allows dynamic types of nodes. But the YAML I/O model uses
730static typing, so there are limits to how you can use tags with the YAML I/O
731model. Recently, we added support to YAML I/O for checking/setting the optional
Alp Toker171b0c32013-12-20 00:33:39 +0000732tag on a map. Using this functionality it is even possbile to support different
Nick Kledzik1e6033c2013-11-14 00:59:59 +0000733mappings, as long as they are convertable.
734
735To check a tag, inside your mapping() method you can use io.mapTag() to specify
736what the tag should be. This will also add that tag when writing yaml.
737
Nick Kledzik7cd45f22013-11-21 00:28:07 +0000738Validation
739----------
740
741Sometimes in a yaml map, each key/value pair is valid, but the combination is
742not. This is similar to something having no syntax errors, but still having
743semantic errors. To support semantic level checking, YAML I/O allows
744an optional ``validate()`` method in a MappingTraits template specialization.
745
746When parsing yaml, the ``validate()`` method is call *after* all key/values in
747the map have been processed. Any error message returned by the ``validate()``
748method during input will be printed just a like a syntax error would be printed.
749When writing yaml, the ``validate()`` method is called *before* the yaml
750key/values are written. Any error during output will trigger an ``assert()``
751because it is a programming error to have invalid struct values.
752
753
754.. code-block:: c++
755
756 using llvm::yaml::MappingTraits;
757 using llvm::yaml::IO;
758
759 struct Stuff {
760 ...
761 };
762
763 template <>
764 struct MappingTraits<Stuff> {
765 static void mapping(IO &io, Stuff &stuff) {
766 ...
767 }
768 static StringRef validate(IO &io, Stuff &stuff) {
769 // Look at all fields in 'stuff' and if there
770 // are any bad values return a string describing
771 // the error. Otherwise return an empty string.
772 return StringRef();
773 }
774 };
775
Alex Lorenzb1225082015-05-04 20:11:40 +0000776Flow Mapping
777------------
778A YAML "flow mapping" is a mapping that uses the inline notation
779(e.g { x: 1, y: 0 } ) when written to YAML. To specify that a type should be
780written in YAML using flow mapping, your MappingTraits specialization should
781add "static const bool flow = true;". For instance:
782
783.. code-block:: c++
784
785 using llvm::yaml::MappingTraits;
786 using llvm::yaml::IO;
787
788 struct Stuff {
789 ...
790 };
791
792 template <>
793 struct MappingTraits<Stuff> {
794 static void mapping(IO &io, Stuff &stuff) {
795 ...
796 }
797
798 static const bool flow = true;
799 }
800
Nick Kledzik1e6033c2013-11-14 00:59:59 +0000801
Nick Kledzikf60a9272012-12-12 20:46:15 +0000802Sequence
803========
804
805To be translated to or from a YAML sequence for your type T you must specialize
806llvm::yaml::SequenceTraits on T and implement two methods:
Dmitri Gribenkoe8131122013-01-19 20:34:20 +0000807``size_t size(IO &io, T&)`` and
808``T::value_type& element(IO &io, T&, size_t indx)``. For example:
Nick Kledzikf60a9272012-12-12 20:46:15 +0000809
810.. code-block:: c++
811
812 template <>
813 struct SequenceTraits<MySeq> {
814 static size_t size(IO &io, MySeq &list) { ... }
Rui Ueyama539b1df2013-09-12 01:43:21 +0000815 static MySeqEl &element(IO &io, MySeq &list, size_t index) { ... }
Nick Kledzikf60a9272012-12-12 20:46:15 +0000816 };
817
818The size() method returns how many elements are currently in your sequence.
819The element() method returns a reference to the i'th element in the sequence.
820When parsing YAML, the element() method may be called with an index one bigger
821than the current size. Your element() method should allocate space for one
822more element (using default constructor if element is a C++ object) and returns
823a reference to that new allocated space.
824
825
826Flow Sequence
827-------------
828A YAML "flow sequence" is a sequence that when written to YAML it uses the
829inline notation (e.g [ foo, bar ] ). To specify that a sequence type should
830be written in YAML as a flow sequence, your SequenceTraits specialization should
831add "static const bool flow = true;". For instance:
832
833.. code-block:: c++
834
835 template <>
836 struct SequenceTraits<MyList> {
837 static size_t size(IO &io, MyList &list) { ... }
Rui Ueyama539b1df2013-09-12 01:43:21 +0000838 static MyListEl &element(IO &io, MyList &list, size_t index) { ... }
Nick Kledzikf60a9272012-12-12 20:46:15 +0000839
840 // The existence of this member causes YAML I/O to use a flow sequence
841 static const bool flow = true;
842 };
843
844With the above, if you used MyList as the data type in your native data
Ed Maste8ed40ce2015-04-14 20:52:58 +0000845structures, then when converted to YAML, a flow sequence of integers
Nick Kledzikf60a9272012-12-12 20:46:15 +0000846will be used (e.g. [ 10, -3, 4 ]).
847
848
849Utility Macros
850--------------
Alex Rosenberg7f5af7f2013-02-18 02:44:09 +0000851Since a common source of sequences is std::vector<>, YAML I/O provides macros:
Nick Kledzikf60a9272012-12-12 20:46:15 +0000852LLVM_YAML_IS_SEQUENCE_VECTOR() and LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR() which
853can be used to easily specify SequenceTraits<> on a std::vector type. YAML
854I/O does not partial specialize SequenceTraits on std::vector<> because that
855would force all vectors to be sequences. An example use of the macros:
856
857.. code-block:: c++
858
859 std::vector<MyType1>;
860 std::vector<MyType2>;
861 LLVM_YAML_IS_SEQUENCE_VECTOR(MyType1)
862 LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(MyType2)
863
864
865
866Document List
867=============
868
869YAML allows you to define multiple "documents" in a single YAML file. Each
870new document starts with a left aligned "---" token. The end of all documents
871is denoted with a left aligned "..." token. Many users of YAML will never
872have need for multiple documents. The top level node in their YAML schema
873will be a mapping or sequence. For those cases, the following is not needed.
874But for cases where you do want multiple documents, you can specify a
875trait for you document list type. The trait has the same methods as
876SequenceTraits but is named DocumentListTraits. For example:
877
878.. code-block:: c++
879
880 template <>
881 struct DocumentListTraits<MyDocList> {
882 static size_t size(IO &io, MyDocList &list) { ... }
883 static MyDocType element(IO &io, MyDocList &list, size_t index) { ... }
884 };
885
886
887User Context Data
888=================
889When an llvm::yaml::Input or llvm::yaml::Output object is created their
890constructors take an optional "context" parameter. This is a pointer to
891whatever state information you might need.
892
893For instance, in a previous example we showed how the conversion type for a
894flags field could be determined at runtime based on the value of another field
895in the mapping. But what if an inner mapping needs to know some field value
896of an outer mapping? That is where the "context" parameter comes in. You
897can set values in the context in the outer map's mapping() method and
898retrieve those values in the inner map's mapping() method.
899
900The context value is just a void*. All your traits which use the context
901and operate on your native data types, need to agree what the context value
902actually is. It could be a pointer to an object or struct which your various
903traits use to shared context sensitive information.
904
905
906Output
907======
908
909The llvm::yaml::Output class is used to generate a YAML document from your
910in-memory data structures, using traits defined on your data types.
911To instantiate an Output object you need an llvm::raw_ostream, and optionally
912a context pointer:
913
914.. code-block:: c++
915
916 class Output : public IO {
917 public:
918 Output(llvm::raw_ostream &, void *context=NULL);
919
920Once you have an Output object, you can use the C++ stream operator on it
921to write your native data as YAML. One thing to recall is that a YAML file
922can contain multiple "documents". If the top level data structure you are
923streaming as YAML is a mapping, scalar, or sequence, then Output assumes you
924are generating one document and wraps the mapping output
925with "``---``" and trailing "``...``".
926
927.. code-block:: c++
928
929 using llvm::yaml::Output;
930
931 void dumpMyMapDoc(const MyMapType &info) {
932 Output yout(llvm::outs());
933 yout << info;
934 }
935
936The above could produce output like:
937
938.. code-block:: yaml
939
940 ---
941 name: Tom
942 hat-size: 7
943 ...
944
945On the other hand, if the top level data structure you are streaming as YAML
946has a DocumentListTraits specialization, then Output walks through each element
947of your DocumentList and generates a "---" before the start of each element
948and ends with a "...".
949
950.. code-block:: c++
951
952 using llvm::yaml::Output;
953
954 void dumpMyMapDoc(const MyDocListType &docList) {
955 Output yout(llvm::outs());
956 yout << docList;
957 }
958
959The above could produce output like:
960
961.. code-block:: yaml
962
963 ---
964 name: Tom
965 hat-size: 7
966 ---
967 name: Tom
968 shoe-size: 11
969 ...
970
971Input
972=====
973
974The llvm::yaml::Input class is used to parse YAML document(s) into your native
975data structures. To instantiate an Input
976object you need a StringRef to the entire YAML file, and optionally a context
977pointer:
978
979.. code-block:: c++
980
981 class Input : public IO {
982 public:
983 Input(StringRef inputContent, void *context=NULL);
984
985Once you have an Input object, you can use the C++ stream operator to read
986the document(s). If you expect there might be multiple YAML documents in
987one file, you'll need to specialize DocumentListTraits on a list of your
988document type and stream in that document list type. Otherwise you can
989just stream in the document type. Also, you can check if there was
990any syntax errors in the YAML be calling the error() method on the Input
991object. For example:
992
993.. code-block:: c++
994
995 // Reading a single document
996 using llvm::yaml::Input;
997
998 Input yin(mb.getBuffer());
999
1000 // Parse the YAML file
1001 MyDocType theDoc;
1002 yin >> theDoc;
1003
1004 // Check for error
1005 if ( yin.error() )
1006 return;
1007
1008
1009.. code-block:: c++
1010
1011 // Reading multiple documents in one file
1012 using llvm::yaml::Input;
1013
1014 LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(std::vector<MyDocType>)
1015
1016 Input yin(mb.getBuffer());
1017
1018 // Parse the YAML file
1019 std::vector<MyDocType> theDocList;
1020 yin >> theDocList;
1021
1022 // Check for error
1023 if ( yin.error() )
1024 return;
1025
1026