YamlIO.rst 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  1. =====================
  2. YAML I/O
  3. =====================
  4. .. contents::
  5. :local:
  6. Introduction to YAML
  7. ====================
  8. YAML is a human readable data serialization language. The full YAML language
  9. spec can be read at `yaml.org
  10. <http://www.yaml.org/spec/1.2/spec.html#Introduction>`_. The simplest form of
  11. yaml is just "scalars", "mappings", and "sequences". A scalar is any number
  12. or string. The pound/hash symbol (#) begins a comment line. A mapping is
  13. a set of key-value pairs where the key ends with a colon. For example:
  14. .. code-block:: yaml
  15. # a mapping
  16. name: Tom
  17. hat-size: 7
  18. A sequence is a list of items where each item starts with a leading dash ('-').
  19. For example:
  20. .. code-block:: yaml
  21. # a sequence
  22. - x86
  23. - x86_64
  24. - PowerPC
  25. You can combine mappings and sequences by indenting. For example a sequence
  26. of mappings in which one of the mapping values is itself a sequence:
  27. .. code-block:: yaml
  28. # a sequence of mappings with one key's value being a sequence
  29. - name: Tom
  30. cpus:
  31. - x86
  32. - x86_64
  33. - name: Bob
  34. cpus:
  35. - x86
  36. - name: Dan
  37. cpus:
  38. - PowerPC
  39. - x86
  40. Sometime sequences are known to be short and the one entry per line is too
  41. verbose, so YAML offers an alternate syntax for sequences called a "Flow
  42. Sequence" in which you put comma separated sequence elements into square
  43. brackets. The above example could then be simplified to :
  44. .. code-block:: yaml
  45. # a sequence of mappings with one key's value being a flow sequence
  46. - name: Tom
  47. cpus: [ x86, x86_64 ]
  48. - name: Bob
  49. cpus: [ x86 ]
  50. - name: Dan
  51. cpus: [ PowerPC, x86 ]
  52. Introduction to YAML I/O
  53. ========================
  54. The use of indenting makes the YAML easy for a human to read and understand,
  55. but having a program read and write YAML involves a lot of tedious details.
  56. The YAML I/O library structures and simplifies reading and writing YAML
  57. documents.
  58. YAML I/O assumes you have some "native" data structures which you want to be
  59. able to dump as YAML and recreate from YAML. The first step is to try
  60. writing example YAML for your data structures. You may find after looking at
  61. possible YAML representations that a direct mapping of your data structures
  62. to YAML is not very readable. Often the fields are not in the order that
  63. a human would find readable. Or the same information is replicated in multiple
  64. locations, making it hard for a human to write such YAML correctly.
  65. In relational database theory there is a design step called normalization in
  66. which you reorganize fields and tables. The same considerations need to
  67. go into the design of your YAML encoding. But, you may not want to change
  68. your existing native data structures. Therefore, when writing out YAML
  69. there may be a normalization step, and when reading YAML there would be a
  70. corresponding denormalization step.
  71. YAML I/O uses a non-invasive, traits based design. YAML I/O defines some
  72. abstract base templates. You specialize those templates on your data types.
  73. For instance, if you have an enumerated type FooBar you could specialize
  74. ScalarEnumerationTraits on that type and define the enumeration() method:
  75. .. code-block:: c++
  76. using llvm::yaml::ScalarEnumerationTraits;
  77. using llvm::yaml::IO;
  78. template <>
  79. struct ScalarEnumerationTraits<FooBar> {
  80. static void enumeration(IO &io, FooBar &value) {
  81. ...
  82. }
  83. };
  84. As with all YAML I/O template specializations, the ScalarEnumerationTraits is used for
  85. both reading and writing YAML. That is, the mapping between in-memory enum
  86. values and the YAML string representation is only in one place.
  87. This assures that the code for writing and parsing of YAML stays in sync.
  88. To specify a YAML mappings, you define a specialization on
  89. llvm::yaml::MappingTraits.
  90. If your native data structure happens to be a struct that is already normalized,
  91. then the specialization is simple. For example:
  92. .. code-block:: c++
  93. using llvm::yaml::MappingTraits;
  94. using llvm::yaml::IO;
  95. template <>
  96. struct MappingTraits<Person> {
  97. static void mapping(IO &io, Person &info) {
  98. io.mapRequired("name", info.name);
  99. io.mapOptional("hat-size", info.hatSize);
  100. }
  101. };
  102. A YAML sequence is automatically inferred if you data type has begin()/end()
  103. iterators and a push_back() method. Therefore any of the STL containers
  104. (such as std::vector<>) will automatically translate to YAML sequences.
  105. Once you have defined specializations for your data types, you can
  106. programmatically use YAML I/O to write a YAML document:
  107. .. code-block:: c++
  108. using llvm::yaml::Output;
  109. Person tom;
  110. tom.name = "Tom";
  111. tom.hatSize = 8;
  112. Person dan;
  113. dan.name = "Dan";
  114. dan.hatSize = 7;
  115. std::vector<Person> persons;
  116. persons.push_back(tom);
  117. persons.push_back(dan);
  118. Output yout(llvm::outs());
  119. yout << persons;
  120. This would write the following:
  121. .. code-block:: yaml
  122. - name: Tom
  123. hat-size: 8
  124. - name: Dan
  125. hat-size: 7
  126. And you can also read such YAML documents with the following code:
  127. .. code-block:: c++
  128. using llvm::yaml::Input;
  129. typedef std::vector<Person> PersonList;
  130. std::vector<PersonList> docs;
  131. Input yin(document.getBuffer());
  132. yin >> docs;
  133. if ( yin.error() )
  134. return;
  135. // Process read document
  136. for ( PersonList &pl : docs ) {
  137. for ( Person &person : pl ) {
  138. cout << "name=" << person.name;
  139. }
  140. }
  141. One other feature of YAML is the ability to define multiple documents in a
  142. single file. That is why reading YAML produces a vector of your document type.
  143. Error Handling
  144. ==============
  145. When parsing a YAML document, if the input does not match your schema (as
  146. expressed in your XxxTraits<> specializations). YAML I/O
  147. will print out an error message and your Input object's error() method will
  148. return true. For instance the following document:
  149. .. code-block:: yaml
  150. - name: Tom
  151. shoe-size: 12
  152. - name: Dan
  153. hat-size: 7
  154. Has a key (shoe-size) that is not defined in the schema. YAML I/O will
  155. automatically generate this error:
  156. .. code-block:: yaml
  157. YAML:2:2: error: unknown key 'shoe-size'
  158. shoe-size: 12
  159. ^~~~~~~~~
  160. Similar errors are produced for other input not conforming to the schema.
  161. Scalars
  162. =======
  163. YAML scalars are just strings (i.e. not a sequence or mapping). The YAML I/O
  164. library provides support for translating between YAML scalars and specific
  165. C++ types.
  166. Built-in types
  167. --------------
  168. The following types have built-in support in YAML I/O:
  169. * bool
  170. * float
  171. * double
  172. * StringRef
  173. * std::string
  174. * int64_t
  175. * int32_t
  176. * int16_t
  177. * int8_t
  178. * uint64_t
  179. * uint32_t
  180. * uint16_t
  181. * uint8_t
  182. That is, you can use those types in fields of MappingTraits or as element type
  183. in sequence. When reading, YAML I/O will validate that the string found
  184. is convertible to that type and error out if not.
  185. Unique types
  186. ------------
  187. Given that YAML I/O is trait based, the selection of how to convert your data
  188. to YAML is based on the type of your data. But in C++ type matching, typedefs
  189. do not generate unique type names. That means if you have two typedefs of
  190. unsigned int, to YAML I/O both types look exactly like unsigned int. To
  191. facilitate make unique type names, YAML I/O provides a macro which is used
  192. like a typedef on built-in types, but expands to create a class with conversion
  193. operators to and from the base type. For example:
  194. .. code-block:: c++
  195. LLVM_YAML_STRONG_TYPEDEF(uint32_t, MyFooFlags)
  196. LLVM_YAML_STRONG_TYPEDEF(uint32_t, MyBarFlags)
  197. This generates two classes MyFooFlags and MyBarFlags which you can use in your
  198. native data structures instead of uint32_t. They are implicitly
  199. converted to and from uint32_t. The point of creating these unique types
  200. is that you can now specify traits on them to get different YAML conversions.
  201. Hex types
  202. ---------
  203. An example use of a unique type is that YAML I/O provides fixed sized unsigned
  204. integers that are written with YAML I/O as hexadecimal instead of the decimal
  205. format used by the built-in integer types:
  206. * Hex64
  207. * Hex32
  208. * Hex16
  209. * Hex8
  210. You can use llvm::yaml::Hex32 instead of uint32_t and the only different will
  211. be that when YAML I/O writes out that type it will be formatted in hexadecimal.
  212. ScalarEnumerationTraits
  213. -----------------------
  214. YAML I/O supports translating between in-memory enumerations and a set of string
  215. values in YAML documents. This is done by specializing ScalarEnumerationTraits<>
  216. on your enumeration type and define a enumeration() method.
  217. For instance, suppose you had an enumeration of CPUs and a struct with it as
  218. a field:
  219. .. code-block:: c++
  220. enum CPUs {
  221. cpu_x86_64 = 5,
  222. cpu_x86 = 7,
  223. cpu_PowerPC = 8
  224. };
  225. struct Info {
  226. CPUs cpu;
  227. uint32_t flags;
  228. };
  229. To support reading and writing of this enumeration, you can define a
  230. ScalarEnumerationTraits specialization on CPUs, which can then be used
  231. as a field type:
  232. .. code-block:: c++
  233. using llvm::yaml::ScalarEnumerationTraits;
  234. using llvm::yaml::MappingTraits;
  235. using llvm::yaml::IO;
  236. template <>
  237. struct ScalarEnumerationTraits<CPUs> {
  238. static void enumeration(IO &io, CPUs &value) {
  239. io.enumCase(value, "x86_64", cpu_x86_64);
  240. io.enumCase(value, "x86", cpu_x86);
  241. io.enumCase(value, "PowerPC", cpu_PowerPC);
  242. }
  243. };
  244. template <>
  245. struct MappingTraits<Info> {
  246. static void mapping(IO &io, Info &info) {
  247. io.mapRequired("cpu", info.cpu);
  248. io.mapOptional("flags", info.flags, 0);
  249. }
  250. };
  251. When reading YAML, if the string found does not match any of the strings
  252. specified by enumCase() methods, an error is automatically generated.
  253. When writing YAML, if the value being written does not match any of the values
  254. specified by the enumCase() methods, a runtime assertion is triggered.
  255. BitValue
  256. --------
  257. Another common data structure in C++ is a field where each bit has a unique
  258. meaning. This is often used in a "flags" field. YAML I/O has support for
  259. converting such fields to a flow sequence. For instance suppose you
  260. had the following bit flags defined:
  261. .. code-block:: c++
  262. enum {
  263. flagsPointy = 1
  264. flagsHollow = 2
  265. flagsFlat = 4
  266. flagsRound = 8
  267. };
  268. LLVM_YAML_STRONG_TYPEDEF(uint32_t, MyFlags)
  269. To support reading and writing of MyFlags, you specialize ScalarBitSetTraits<>
  270. on MyFlags and provide the bit values and their names.
  271. .. code-block:: c++
  272. using llvm::yaml::ScalarBitSetTraits;
  273. using llvm::yaml::MappingTraits;
  274. using llvm::yaml::IO;
  275. template <>
  276. struct ScalarBitSetTraits<MyFlags> {
  277. static void bitset(IO &io, MyFlags &value) {
  278. io.bitSetCase(value, "hollow", flagHollow);
  279. io.bitSetCase(value, "flat", flagFlat);
  280. io.bitSetCase(value, "round", flagRound);
  281. io.bitSetCase(value, "pointy", flagPointy);
  282. }
  283. };
  284. struct Info {
  285. StringRef name;
  286. MyFlags flags;
  287. };
  288. template <>
  289. struct MappingTraits<Info> {
  290. static void mapping(IO &io, Info& info) {
  291. io.mapRequired("name", info.name);
  292. io.mapRequired("flags", info.flags);
  293. }
  294. };
  295. With the above, YAML I/O (when writing) will test mask each value in the
  296. bitset trait against the flags field, and each that matches will
  297. cause the corresponding string to be added to the flow sequence. The opposite
  298. is done when reading and any unknown string values will result in a error. With
  299. the above schema, a same valid YAML document is:
  300. .. code-block:: yaml
  301. name: Tom
  302. flags: [ pointy, flat ]
  303. Sometimes a "flags" field might contains an enumeration part
  304. defined by a bit-mask.
  305. .. code-block:: c++
  306. enum {
  307. flagsFeatureA = 1,
  308. flagsFeatureB = 2,
  309. flagsFeatureC = 4,
  310. flagsCPUMask = 24,
  311. flagsCPU1 = 8,
  312. flagsCPU2 = 16
  313. };
  314. To support reading and writing such fields, you need to use the maskedBitSet()
  315. method and provide the bit values, their names and the enumeration mask.
  316. .. code-block:: c++
  317. template <>
  318. struct ScalarBitSetTraits<MyFlags> {
  319. static void bitset(IO &io, MyFlags &value) {
  320. io.bitSetCase(value, "featureA", flagsFeatureA);
  321. io.bitSetCase(value, "featureB", flagsFeatureB);
  322. io.bitSetCase(value, "featureC", flagsFeatureC);
  323. io.maskedBitSetCase(value, "CPU1", flagsCPU1, flagsCPUMask);
  324. io.maskedBitSetCase(value, "CPU2", flagsCPU2, flagsCPUMask);
  325. }
  326. };
  327. YAML I/O (when writing) will apply the enumeration mask to the flags field,
  328. and compare the result and values from the bitset. As in case of a regular
  329. bitset, each that matches will cause the corresponding string to be added
  330. to the flow sequence.
  331. Custom Scalar
  332. -------------
  333. Sometimes for readability a scalar needs to be formatted in a custom way. For
  334. instance your internal data structure may use a integer for time (seconds since
  335. some epoch), but in YAML it would be much nicer to express that integer in
  336. some time format (e.g. 4-May-2012 10:30pm). YAML I/O has a way to support
  337. custom formatting and parsing of scalar types by specializing ScalarTraits<> on
  338. your data type. When writing, YAML I/O will provide the native type and
  339. your specialization must create a temporary llvm::StringRef. When reading,
  340. YAML I/O will provide an llvm::StringRef of scalar and your specialization
  341. must convert that to your native data type. An outline of a custom scalar type
  342. looks like:
  343. .. code-block:: c++
  344. using llvm::yaml::ScalarTraits;
  345. using llvm::yaml::IO;
  346. template <>
  347. struct ScalarTraits<MyCustomType> {
  348. static void output(const T &value, void*, llvm::raw_ostream &out) {
  349. out << value; // do custom formatting here
  350. }
  351. static StringRef input(StringRef scalar, void*, T &value) {
  352. // do custom parsing here. Return the empty string on success,
  353. // or an error message on failure.
  354. return StringRef();
  355. }
  356. // Determine if this scalar needs quotes.
  357. static bool mustQuote(StringRef) { return true; }
  358. };
  359. Block Scalars
  360. -------------
  361. YAML block scalars are string literals that are represented in YAML using the
  362. literal block notation, just like the example shown below:
  363. .. code-block:: yaml
  364. text: |
  365. First line
  366. Second line
  367. The YAML I/O library provides support for translating between YAML block scalars
  368. and specific C++ types by allowing you to specialize BlockScalarTraits<> on
  369. your data type. The library doesn't provide any built-in support for block
  370. scalar I/O for types like std::string and llvm::StringRef as they are already
  371. supported by YAML I/O and use the ordinary scalar notation by default.
  372. BlockScalarTraits specializations are very similar to the
  373. ScalarTraits specialization - YAML I/O will provide the native type and your
  374. specialization must create a temporary llvm::StringRef when writing, and
  375. it will also provide an llvm::StringRef that has the value of that block scalar
  376. and your specialization must convert that to your native data type when reading.
  377. An example of a custom type with an appropriate specialization of
  378. BlockScalarTraits is shown below:
  379. .. code-block:: c++
  380. using llvm::yaml::BlockScalarTraits;
  381. using llvm::yaml::IO;
  382. struct MyStringType {
  383. std::string Str;
  384. };
  385. template <>
  386. struct BlockScalarTraits<MyStringType> {
  387. static void output(const MyStringType &Value, void *Ctxt,
  388. llvm::raw_ostream &OS) {
  389. OS << Value.Str;
  390. }
  391. static StringRef input(StringRef Scalar, void *Ctxt,
  392. MyStringType &Value) {
  393. Value.Str = Scalar.str();
  394. return StringRef();
  395. }
  396. };
  397. Mappings
  398. ========
  399. To be translated to or from a YAML mapping for your type T you must specialize
  400. llvm::yaml::MappingTraits on T and implement the "void mapping(IO &io, T&)"
  401. method. If your native data structures use pointers to a class everywhere,
  402. you can specialize on the class pointer. Examples:
  403. .. code-block:: c++
  404. using llvm::yaml::MappingTraits;
  405. using llvm::yaml::IO;
  406. // Example of struct Foo which is used by value
  407. template <>
  408. struct MappingTraits<Foo> {
  409. static void mapping(IO &io, Foo &foo) {
  410. io.mapOptional("size", foo.size);
  411. ...
  412. }
  413. };
  414. // Example of struct Bar which is natively always a pointer
  415. template <>
  416. struct MappingTraits<Bar*> {
  417. static void mapping(IO &io, Bar *&bar) {
  418. io.mapOptional("size", bar->size);
  419. ...
  420. }
  421. };
  422. No Normalization
  423. ----------------
  424. The mapping() method is responsible, if needed, for normalizing and
  425. denormalizing. In a simple case where the native data structure requires no
  426. normalization, the mapping method just uses mapOptional() or mapRequired() to
  427. bind the struct's fields to YAML key names. For example:
  428. .. code-block:: c++
  429. using llvm::yaml::MappingTraits;
  430. using llvm::yaml::IO;
  431. template <>
  432. struct MappingTraits<Person> {
  433. static void mapping(IO &io, Person &info) {
  434. io.mapRequired("name", info.name);
  435. io.mapOptional("hat-size", info.hatSize);
  436. }
  437. };
  438. Normalization
  439. ----------------
  440. When [de]normalization is required, the mapping() method needs a way to access
  441. normalized values as fields. To help with this, there is
  442. a template MappingNormalization<> which you can then use to automatically
  443. do the normalization and denormalization. The template is used to create
  444. a local variable in your mapping() method which contains the normalized keys.
  445. Suppose you have native data type
  446. Polar which specifies a position in polar coordinates (distance, angle):
  447. .. code-block:: c++
  448. struct Polar {
  449. float distance;
  450. float angle;
  451. };
  452. but you've decided the normalized YAML for should be in x,y coordinates. That
  453. is, you want the yaml to look like:
  454. .. code-block:: yaml
  455. x: 10.3
  456. y: -4.7
  457. You can support this by defining a MappingTraits that normalizes the polar
  458. coordinates to x,y coordinates when writing YAML and denormalizes x,y
  459. coordinates into polar when reading YAML.
  460. .. code-block:: c++
  461. using llvm::yaml::MappingTraits;
  462. using llvm::yaml::IO;
  463. template <>
  464. struct MappingTraits<Polar> {
  465. class NormalizedPolar {
  466. public:
  467. NormalizedPolar(IO &io)
  468. : x(0.0), y(0.0) {
  469. }
  470. NormalizedPolar(IO &, Polar &polar)
  471. : x(polar.distance * cos(polar.angle)),
  472. y(polar.distance * sin(polar.angle)) {
  473. }
  474. Polar denormalize(IO &) {
  475. return Polar(sqrt(x*x+y*y), arctan(x,y));
  476. }
  477. float x;
  478. float y;
  479. };
  480. static void mapping(IO &io, Polar &polar) {
  481. MappingNormalization<NormalizedPolar, Polar> keys(io, polar);
  482. io.mapRequired("x", keys->x);
  483. io.mapRequired("y", keys->y);
  484. }
  485. };
  486. When writing YAML, the local variable "keys" will be a stack allocated
  487. instance of NormalizedPolar, constructed from the supplied polar object which
  488. initializes it x and y fields. The mapRequired() methods then write out the x
  489. and y values as key/value pairs.
  490. When reading YAML, the local variable "keys" will be a stack allocated instance
  491. of NormalizedPolar, constructed by the empty constructor. The mapRequired
  492. methods will find the matching key in the YAML document and fill in the x and y
  493. fields of the NormalizedPolar object keys. At the end of the mapping() method
  494. when the local keys variable goes out of scope, the denormalize() method will
  495. automatically be called to convert the read values back to polar coordinates,
  496. and then assigned back to the second parameter to mapping().
  497. In some cases, the normalized class may be a subclass of the native type and
  498. could be returned by the denormalize() method, except that the temporary
  499. normalized instance is stack allocated. In these cases, the utility template
  500. MappingNormalizationHeap<> can be used instead. It just like
  501. MappingNormalization<> except that it heap allocates the normalized object
  502. when reading YAML. It never destroys the normalized object. The denormalize()
  503. method can this return "this".
  504. Default values
  505. --------------
  506. Within a mapping() method, calls to io.mapRequired() mean that that key is
  507. required to exist when parsing YAML documents, otherwise YAML I/O will issue an
  508. error.
  509. On the other hand, keys registered with io.mapOptional() are allowed to not
  510. exist in the YAML document being read. So what value is put in the field
  511. for those optional keys?
  512. There are two steps to how those optional fields are filled in. First, the
  513. second parameter to the mapping() method is a reference to a native class. That
  514. native class must have a default constructor. Whatever value the default
  515. constructor initially sets for an optional field will be that field's value.
  516. Second, the mapOptional() method has an optional third parameter. If provided
  517. it is the value that mapOptional() should set that field to if the YAML document
  518. does not have that key.
  519. There is one important difference between those two ways (default constructor
  520. and third parameter to mapOptional). When YAML I/O generates a YAML document,
  521. if the mapOptional() third parameter is used, if the actual value being written
  522. is the same as (using ==) the default value, then that key/value is not written.
  523. Order of Keys
  524. --------------
  525. When writing out a YAML document, the keys are written in the order that the
  526. calls to mapRequired()/mapOptional() are made in the mapping() method. This
  527. gives you a chance to write the fields in an order that a human reader of
  528. the YAML document would find natural. This may be different that the order
  529. of the fields in the native class.
  530. When reading in a YAML document, the keys in the document can be in any order,
  531. but they are processed in the order that the calls to mapRequired()/mapOptional()
  532. are made in the mapping() method. That enables some interesting
  533. functionality. For instance, if the first field bound is the cpu and the second
  534. field bound is flags, and the flags are cpu specific, you can programmatically
  535. switch how the flags are converted to and from YAML based on the cpu.
  536. This works for both reading and writing. For example:
  537. .. code-block:: c++
  538. using llvm::yaml::MappingTraits;
  539. using llvm::yaml::IO;
  540. struct Info {
  541. CPUs cpu;
  542. uint32_t flags;
  543. };
  544. template <>
  545. struct MappingTraits<Info> {
  546. static void mapping(IO &io, Info &info) {
  547. io.mapRequired("cpu", info.cpu);
  548. // flags must come after cpu for this to work when reading yaml
  549. if ( info.cpu == cpu_x86_64 )
  550. io.mapRequired("flags", *(My86_64Flags*)info.flags);
  551. else
  552. io.mapRequired("flags", *(My86Flags*)info.flags);
  553. }
  554. };
  555. Tags
  556. ----
  557. The YAML syntax supports tags as a way to specify the type of a node before
  558. it is parsed. This allows dynamic types of nodes. But the YAML I/O model uses
  559. static typing, so there are limits to how you can use tags with the YAML I/O
  560. model. Recently, we added support to YAML I/O for checking/setting the optional
  561. tag on a map. Using this functionality it is even possbile to support different
  562. mappings, as long as they are convertable.
  563. To check a tag, inside your mapping() method you can use io.mapTag() to specify
  564. what the tag should be. This will also add that tag when writing yaml.
  565. Validation
  566. ----------
  567. Sometimes in a yaml map, each key/value pair is valid, but the combination is
  568. not. This is similar to something having no syntax errors, but still having
  569. semantic errors. To support semantic level checking, YAML I/O allows
  570. an optional ``validate()`` method in a MappingTraits template specialization.
  571. When parsing yaml, the ``validate()`` method is call *after* all key/values in
  572. the map have been processed. Any error message returned by the ``validate()``
  573. method during input will be printed just a like a syntax error would be printed.
  574. When writing yaml, the ``validate()`` method is called *before* the yaml
  575. key/values are written. Any error during output will trigger an ``assert()``
  576. because it is a programming error to have invalid struct values.
  577. .. code-block:: c++
  578. using llvm::yaml::MappingTraits;
  579. using llvm::yaml::IO;
  580. struct Stuff {
  581. ...
  582. };
  583. template <>
  584. struct MappingTraits<Stuff> {
  585. static void mapping(IO &io, Stuff &stuff) {
  586. ...
  587. }
  588. static StringRef validate(IO &io, Stuff &stuff) {
  589. // Look at all fields in 'stuff' and if there
  590. // are any bad values return a string describing
  591. // the error. Otherwise return an empty string.
  592. return StringRef();
  593. }
  594. };
  595. Flow Mapping
  596. ------------
  597. A YAML "flow mapping" is a mapping that uses the inline notation
  598. (e.g { x: 1, y: 0 } ) when written to YAML. To specify that a type should be
  599. written in YAML using flow mapping, your MappingTraits specialization should
  600. add "static const bool flow = true;". For instance:
  601. .. code-block:: c++
  602. using llvm::yaml::MappingTraits;
  603. using llvm::yaml::IO;
  604. struct Stuff {
  605. ...
  606. };
  607. template <>
  608. struct MappingTraits<Stuff> {
  609. static void mapping(IO &io, Stuff &stuff) {
  610. ...
  611. }
  612. static const bool flow = true;
  613. }
  614. Flow mappings are subject to line wrapping according to the Output object
  615. configuration.
  616. Sequence
  617. ========
  618. To be translated to or from a YAML sequence for your type T you must specialize
  619. llvm::yaml::SequenceTraits on T and implement two methods:
  620. ``size_t size(IO &io, T&)`` and
  621. ``T::value_type& element(IO &io, T&, size_t indx)``. For example:
  622. .. code-block:: c++
  623. template <>
  624. struct SequenceTraits<MySeq> {
  625. static size_t size(IO &io, MySeq &list) { ... }
  626. static MySeqEl &element(IO &io, MySeq &list, size_t index) { ... }
  627. };
  628. The size() method returns how many elements are currently in your sequence.
  629. The element() method returns a reference to the i'th element in the sequence.
  630. When parsing YAML, the element() method may be called with an index one bigger
  631. than the current size. Your element() method should allocate space for one
  632. more element (using default constructor if element is a C++ object) and returns
  633. a reference to that new allocated space.
  634. Flow Sequence
  635. -------------
  636. A YAML "flow sequence" is a sequence that when written to YAML it uses the
  637. inline notation (e.g [ foo, bar ] ). To specify that a sequence type should
  638. be written in YAML as a flow sequence, your SequenceTraits specialization should
  639. add "static const bool flow = true;". For instance:
  640. .. code-block:: c++
  641. template <>
  642. struct SequenceTraits<MyList> {
  643. static size_t size(IO &io, MyList &list) { ... }
  644. static MyListEl &element(IO &io, MyList &list, size_t index) { ... }
  645. // The existence of this member causes YAML I/O to use a flow sequence
  646. static const bool flow = true;
  647. };
  648. With the above, if you used MyList as the data type in your native data
  649. structures, then when converted to YAML, a flow sequence of integers
  650. will be used (e.g. [ 10, -3, 4 ]).
  651. Flow sequences are subject to line wrapping according to the Output object
  652. configuration.
  653. Utility Macros
  654. --------------
  655. Since a common source of sequences is std::vector<>, YAML I/O provides macros:
  656. LLVM_YAML_IS_SEQUENCE_VECTOR() and LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR() which
  657. can be used to easily specify SequenceTraits<> on a std::vector type. YAML
  658. I/O does not partial specialize SequenceTraits on std::vector<> because that
  659. would force all vectors to be sequences. An example use of the macros:
  660. .. code-block:: c++
  661. std::vector<MyType1>;
  662. std::vector<MyType2>;
  663. LLVM_YAML_IS_SEQUENCE_VECTOR(MyType1)
  664. LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(MyType2)
  665. Document List
  666. =============
  667. YAML allows you to define multiple "documents" in a single YAML file. Each
  668. new document starts with a left aligned "---" token. The end of all documents
  669. is denoted with a left aligned "..." token. Many users of YAML will never
  670. have need for multiple documents. The top level node in their YAML schema
  671. will be a mapping or sequence. For those cases, the following is not needed.
  672. But for cases where you do want multiple documents, you can specify a
  673. trait for you document list type. The trait has the same methods as
  674. SequenceTraits but is named DocumentListTraits. For example:
  675. .. code-block:: c++
  676. template <>
  677. struct DocumentListTraits<MyDocList> {
  678. static size_t size(IO &io, MyDocList &list) { ... }
  679. static MyDocType element(IO &io, MyDocList &list, size_t index) { ... }
  680. };
  681. User Context Data
  682. =================
  683. When an llvm::yaml::Input or llvm::yaml::Output object is created their
  684. constructors take an optional "context" parameter. This is a pointer to
  685. whatever state information you might need.
  686. For instance, in a previous example we showed how the conversion type for a
  687. flags field could be determined at runtime based on the value of another field
  688. in the mapping. But what if an inner mapping needs to know some field value
  689. of an outer mapping? That is where the "context" parameter comes in. You
  690. can set values in the context in the outer map's mapping() method and
  691. retrieve those values in the inner map's mapping() method.
  692. The context value is just a void*. All your traits which use the context
  693. and operate on your native data types, need to agree what the context value
  694. actually is. It could be a pointer to an object or struct which your various
  695. traits use to shared context sensitive information.
  696. Output
  697. ======
  698. The llvm::yaml::Output class is used to generate a YAML document from your
  699. in-memory data structures, using traits defined on your data types.
  700. To instantiate an Output object you need an llvm::raw_ostream, an optional
  701. context pointer and an optional wrapping column:
  702. .. code-block:: c++
  703. class Output : public IO {
  704. public:
  705. Output(llvm::raw_ostream &, void *context = NULL, int WrapColumn = 70);
  706. Once you have an Output object, you can use the C++ stream operator on it
  707. to write your native data as YAML. One thing to recall is that a YAML file
  708. can contain multiple "documents". If the top level data structure you are
  709. streaming as YAML is a mapping, scalar, or sequence, then Output assumes you
  710. are generating one document and wraps the mapping output
  711. with "``---``" and trailing "``...``".
  712. The WrapColumn parameter will cause the flow mappings and sequences to
  713. line-wrap when they go over the supplied column. Pass 0 to completely
  714. suppress the wrapping.
  715. .. code-block:: c++
  716. using llvm::yaml::Output;
  717. void dumpMyMapDoc(const MyMapType &info) {
  718. Output yout(llvm::outs());
  719. yout << info;
  720. }
  721. The above could produce output like:
  722. .. code-block:: yaml
  723. ---
  724. name: Tom
  725. hat-size: 7
  726. ...
  727. On the other hand, if the top level data structure you are streaming as YAML
  728. has a DocumentListTraits specialization, then Output walks through each element
  729. of your DocumentList and generates a "---" before the start of each element
  730. and ends with a "...".
  731. .. code-block:: c++
  732. using llvm::yaml::Output;
  733. void dumpMyMapDoc(const MyDocListType &docList) {
  734. Output yout(llvm::outs());
  735. yout << docList;
  736. }
  737. The above could produce output like:
  738. .. code-block:: yaml
  739. ---
  740. name: Tom
  741. hat-size: 7
  742. ---
  743. name: Tom
  744. shoe-size: 11
  745. ...
  746. Input
  747. =====
  748. The llvm::yaml::Input class is used to parse YAML document(s) into your native
  749. data structures. To instantiate an Input
  750. object you need a StringRef to the entire YAML file, and optionally a context
  751. pointer:
  752. .. code-block:: c++
  753. class Input : public IO {
  754. public:
  755. Input(StringRef inputContent, void *context=NULL);
  756. Once you have an Input object, you can use the C++ stream operator to read
  757. the document(s). If you expect there might be multiple YAML documents in
  758. one file, you'll need to specialize DocumentListTraits on a list of your
  759. document type and stream in that document list type. Otherwise you can
  760. just stream in the document type. Also, you can check if there was
  761. any syntax errors in the YAML be calling the error() method on the Input
  762. object. For example:
  763. .. code-block:: c++
  764. // Reading a single document
  765. using llvm::yaml::Input;
  766. Input yin(mb.getBuffer());
  767. // Parse the YAML file
  768. MyDocType theDoc;
  769. yin >> theDoc;
  770. // Check for error
  771. if ( yin.error() )
  772. return;
  773. .. code-block:: c++
  774. // Reading multiple documents in one file
  775. using llvm::yaml::Input;
  776. LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(std::vector<MyDocType>)
  777. Input yin(mb.getBuffer());
  778. // Parse the YAML file
  779. std::vector<MyDocType> theDocList;
  780. yin >> theDocList;
  781. // Check for error
  782. if ( yin.error() )
  783. return;