Revert r354244 "[DAGCombiner] Eliminate dead stores to stack."
[llvm-complete.git] / unittests / Support / YAMLIOTest.cpp
blobcf279ffd4c2d45542ce77dcd6912342a9d010a1c
1 //===- unittest/Support/YAMLIOTest.cpp ------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #include "llvm/ADT/StringMap.h"
10 #include "llvm/ADT/StringRef.h"
11 #include "llvm/ADT/Twine.h"
12 #include "llvm/Support/Casting.h"
13 #include "llvm/Support/Endian.h"
14 #include "llvm/Support/Format.h"
15 #include "llvm/Support/YAMLTraits.h"
16 #include "gmock/gmock.h"
17 #include "gtest/gtest.h"
19 using llvm::yaml::Hex16;
20 using llvm::yaml::Hex32;
21 using llvm::yaml::Hex64;
22 using llvm::yaml::Hex8;
23 using llvm::yaml::Input;
24 using llvm::yaml::IO;
25 using llvm::yaml::isNumeric;
26 using llvm::yaml::MappingNormalization;
27 using llvm::yaml::MappingTraits;
28 using llvm::yaml::Output;
29 using llvm::yaml::ScalarTraits;
30 using ::testing::StartsWith;
35 static void suppressErrorMessages(const llvm::SMDiagnostic &, void *) {
40 //===----------------------------------------------------------------------===//
41 // Test MappingTraits
42 //===----------------------------------------------------------------------===//
44 struct FooBar {
45 int foo;
46 int bar;
48 typedef std::vector<FooBar> FooBarSequence;
50 LLVM_YAML_IS_SEQUENCE_VECTOR(FooBar)
52 struct FooBarContainer {
53 FooBarSequence fbs;
56 namespace llvm {
57 namespace yaml {
58 template <>
59 struct MappingTraits<FooBar> {
60 static void mapping(IO &io, FooBar& fb) {
61 io.mapRequired("foo", fb.foo);
62 io.mapRequired("bar", fb.bar);
66 template <> struct MappingTraits<FooBarContainer> {
67 static void mapping(IO &io, FooBarContainer &fb) {
68 io.mapRequired("fbs", fb.fbs);
76 // Test the reading of a yaml mapping
78 TEST(YAMLIO, TestMapRead) {
79 FooBar doc;
81 Input yin("---\nfoo: 3\nbar: 5\n...\n");
82 yin >> doc;
84 EXPECT_FALSE(yin.error());
85 EXPECT_EQ(doc.foo, 3);
86 EXPECT_EQ(doc.bar, 5);
90 Input yin("{foo: 3, bar: 5}");
91 yin >> doc;
93 EXPECT_FALSE(yin.error());
94 EXPECT_EQ(doc.foo, 3);
95 EXPECT_EQ(doc.bar, 5);
99 TEST(YAMLIO, TestMalformedMapRead) {
100 FooBar doc;
101 Input yin("{foo: 3; bar: 5}", nullptr, suppressErrorMessages);
102 yin >> doc;
103 EXPECT_TRUE(!!yin.error());
107 // Test the reading of a yaml sequence of mappings
109 TEST(YAMLIO, TestSequenceMapRead) {
110 FooBarSequence seq;
111 Input yin("---\n - foo: 3\n bar: 5\n - foo: 7\n bar: 9\n...\n");
112 yin >> seq;
114 EXPECT_FALSE(yin.error());
115 EXPECT_EQ(seq.size(), 2UL);
116 FooBar& map1 = seq[0];
117 FooBar& map2 = seq[1];
118 EXPECT_EQ(map1.foo, 3);
119 EXPECT_EQ(map1.bar, 5);
120 EXPECT_EQ(map2.foo, 7);
121 EXPECT_EQ(map2.bar, 9);
125 // Test the reading of a map containing a yaml sequence of mappings
127 TEST(YAMLIO, TestContainerSequenceMapRead) {
129 FooBarContainer cont;
130 Input yin2("---\nfbs:\n - foo: 3\n bar: 5\n - foo: 7\n bar: 9\n...\n");
131 yin2 >> cont;
133 EXPECT_FALSE(yin2.error());
134 EXPECT_EQ(cont.fbs.size(), 2UL);
135 EXPECT_EQ(cont.fbs[0].foo, 3);
136 EXPECT_EQ(cont.fbs[0].bar, 5);
137 EXPECT_EQ(cont.fbs[1].foo, 7);
138 EXPECT_EQ(cont.fbs[1].bar, 9);
142 FooBarContainer cont;
143 Input yin("---\nfbs:\n...\n");
144 yin >> cont;
145 // Okay: Empty node represents an empty array.
146 EXPECT_FALSE(yin.error());
147 EXPECT_EQ(cont.fbs.size(), 0UL);
151 FooBarContainer cont;
152 Input yin("---\nfbs: !!null null\n...\n");
153 yin >> cont;
154 // Okay: null represents an empty array.
155 EXPECT_FALSE(yin.error());
156 EXPECT_EQ(cont.fbs.size(), 0UL);
160 FooBarContainer cont;
161 Input yin("---\nfbs: ~\n...\n");
162 yin >> cont;
163 // Okay: null represents an empty array.
164 EXPECT_FALSE(yin.error());
165 EXPECT_EQ(cont.fbs.size(), 0UL);
169 FooBarContainer cont;
170 Input yin("---\nfbs: null\n...\n");
171 yin >> cont;
172 // Okay: null represents an empty array.
173 EXPECT_FALSE(yin.error());
174 EXPECT_EQ(cont.fbs.size(), 0UL);
179 // Test the reading of a map containing a malformed yaml sequence
181 TEST(YAMLIO, TestMalformedContainerSequenceMapRead) {
183 FooBarContainer cont;
184 Input yin("---\nfbs:\n foo: 3\n bar: 5\n...\n", nullptr,
185 suppressErrorMessages);
186 yin >> cont;
187 // Error: fbs is not a sequence.
188 EXPECT_TRUE(!!yin.error());
189 EXPECT_EQ(cont.fbs.size(), 0UL);
193 FooBarContainer cont;
194 Input yin("---\nfbs: 'scalar'\n...\n", nullptr, suppressErrorMessages);
195 yin >> cont;
196 // This should be an error.
197 EXPECT_TRUE(!!yin.error());
198 EXPECT_EQ(cont.fbs.size(), 0UL);
203 // Test writing then reading back a sequence of mappings
205 TEST(YAMLIO, TestSequenceMapWriteAndRead) {
206 std::string intermediate;
208 FooBar entry1;
209 entry1.foo = 10;
210 entry1.bar = -3;
211 FooBar entry2;
212 entry2.foo = 257;
213 entry2.bar = 0;
214 FooBarSequence seq;
215 seq.push_back(entry1);
216 seq.push_back(entry2);
218 llvm::raw_string_ostream ostr(intermediate);
219 Output yout(ostr);
220 yout << seq;
224 Input yin(intermediate);
225 FooBarSequence seq2;
226 yin >> seq2;
228 EXPECT_FALSE(yin.error());
229 EXPECT_EQ(seq2.size(), 2UL);
230 FooBar& map1 = seq2[0];
231 FooBar& map2 = seq2[1];
232 EXPECT_EQ(map1.foo, 10);
233 EXPECT_EQ(map1.bar, -3);
234 EXPECT_EQ(map2.foo, 257);
235 EXPECT_EQ(map2.bar, 0);
240 // Test YAML filename handling.
242 static void testErrorFilename(const llvm::SMDiagnostic &Error, void *) {
243 EXPECT_EQ(Error.getFilename(), "foo.yaml");
246 TEST(YAMLIO, TestGivenFilename) {
247 auto Buffer = llvm::MemoryBuffer::getMemBuffer("{ x: 42 }", "foo.yaml");
248 Input yin(*Buffer, nullptr, testErrorFilename);
249 FooBar Value;
250 yin >> Value;
252 EXPECT_TRUE(!!yin.error());
255 struct WithStringField {
256 std::string str1;
257 std::string str2;
258 std::string str3;
261 namespace llvm {
262 namespace yaml {
263 template <> struct MappingTraits<WithStringField> {
264 static void mapping(IO &io, WithStringField &fb) {
265 io.mapRequired("str1", fb.str1);
266 io.mapRequired("str2", fb.str2);
267 io.mapRequired("str3", fb.str3);
270 } // namespace yaml
271 } // namespace llvm
273 TEST(YAMLIO, MultilineStrings) {
274 WithStringField Original;
275 Original.str1 = "a multiline string\nfoobarbaz";
276 Original.str2 = "another one\rfoobarbaz";
277 Original.str3 = "a one-line string";
279 std::string Serialized;
281 llvm::raw_string_ostream OS(Serialized);
282 Output YOut(OS);
283 YOut << Original;
285 auto Expected = "---\n"
286 "str1: 'a multiline string\n"
287 "foobarbaz'\n"
288 "str2: 'another one\r"
289 "foobarbaz'\n"
290 "str3: a one-line string\n"
291 "...\n";
292 ASSERT_EQ(Serialized, Expected);
294 // Also check it parses back without the errors.
295 WithStringField Deserialized;
297 Input YIn(Serialized);
298 YIn >> Deserialized;
299 ASSERT_FALSE(YIn.error())
300 << "Parsing error occurred during deserialization. Serialized string:\n"
301 << Serialized;
303 EXPECT_EQ(Original.str1, Deserialized.str1);
304 EXPECT_EQ(Original.str2, Deserialized.str2);
305 EXPECT_EQ(Original.str3, Deserialized.str3);
308 TEST(YAMLIO, NoQuotesForTab) {
309 WithStringField WithTab;
310 WithTab.str1 = "aba\tcaba";
311 std::string Serialized;
313 llvm::raw_string_ostream OS(Serialized);
314 Output YOut(OS);
315 YOut << WithTab;
317 auto ExpectedPrefix = "---\n"
318 "str1: aba\tcaba\n";
319 EXPECT_THAT(Serialized, StartsWith(ExpectedPrefix));
322 //===----------------------------------------------------------------------===//
323 // Test built-in types
324 //===----------------------------------------------------------------------===//
326 struct BuiltInTypes {
327 llvm::StringRef str;
328 std::string stdstr;
329 uint64_t u64;
330 uint32_t u32;
331 uint16_t u16;
332 uint8_t u8;
333 bool b;
334 int64_t s64;
335 int32_t s32;
336 int16_t s16;
337 int8_t s8;
338 float f;
339 double d;
340 Hex8 h8;
341 Hex16 h16;
342 Hex32 h32;
343 Hex64 h64;
346 namespace llvm {
347 namespace yaml {
348 template <>
349 struct MappingTraits<BuiltInTypes> {
350 static void mapping(IO &io, BuiltInTypes& bt) {
351 io.mapRequired("str", bt.str);
352 io.mapRequired("stdstr", bt.stdstr);
353 io.mapRequired("u64", bt.u64);
354 io.mapRequired("u32", bt.u32);
355 io.mapRequired("u16", bt.u16);
356 io.mapRequired("u8", bt.u8);
357 io.mapRequired("b", bt.b);
358 io.mapRequired("s64", bt.s64);
359 io.mapRequired("s32", bt.s32);
360 io.mapRequired("s16", bt.s16);
361 io.mapRequired("s8", bt.s8);
362 io.mapRequired("f", bt.f);
363 io.mapRequired("d", bt.d);
364 io.mapRequired("h8", bt.h8);
365 io.mapRequired("h16", bt.h16);
366 io.mapRequired("h32", bt.h32);
367 io.mapRequired("h64", bt.h64);
375 // Test the reading of all built-in scalar conversions
377 TEST(YAMLIO, TestReadBuiltInTypes) {
378 BuiltInTypes map;
379 Input yin("---\n"
380 "str: hello there\n"
381 "stdstr: hello where?\n"
382 "u64: 5000000000\n"
383 "u32: 4000000000\n"
384 "u16: 65000\n"
385 "u8: 255\n"
386 "b: false\n"
387 "s64: -5000000000\n"
388 "s32: -2000000000\n"
389 "s16: -32000\n"
390 "s8: -127\n"
391 "f: 137.125\n"
392 "d: -2.8625\n"
393 "h8: 0xFF\n"
394 "h16: 0x8765\n"
395 "h32: 0xFEDCBA98\n"
396 "h64: 0xFEDCBA9876543210\n"
397 "...\n");
398 yin >> map;
400 EXPECT_FALSE(yin.error());
401 EXPECT_TRUE(map.str.equals("hello there"));
402 EXPECT_TRUE(map.stdstr == "hello where?");
403 EXPECT_EQ(map.u64, 5000000000ULL);
404 EXPECT_EQ(map.u32, 4000000000U);
405 EXPECT_EQ(map.u16, 65000);
406 EXPECT_EQ(map.u8, 255);
407 EXPECT_EQ(map.b, false);
408 EXPECT_EQ(map.s64, -5000000000LL);
409 EXPECT_EQ(map.s32, -2000000000L);
410 EXPECT_EQ(map.s16, -32000);
411 EXPECT_EQ(map.s8, -127);
412 EXPECT_EQ(map.f, 137.125);
413 EXPECT_EQ(map.d, -2.8625);
414 EXPECT_EQ(map.h8, Hex8(255));
415 EXPECT_EQ(map.h16, Hex16(0x8765));
416 EXPECT_EQ(map.h32, Hex32(0xFEDCBA98));
417 EXPECT_EQ(map.h64, Hex64(0xFEDCBA9876543210LL));
422 // Test writing then reading back all built-in scalar types
424 TEST(YAMLIO, TestReadWriteBuiltInTypes) {
425 std::string intermediate;
427 BuiltInTypes map;
428 map.str = "one two";
429 map.stdstr = "three four";
430 map.u64 = 6000000000ULL;
431 map.u32 = 3000000000U;
432 map.u16 = 50000;
433 map.u8 = 254;
434 map.b = true;
435 map.s64 = -6000000000LL;
436 map.s32 = -2000000000;
437 map.s16 = -32000;
438 map.s8 = -128;
439 map.f = 3.25;
440 map.d = -2.8625;
441 map.h8 = 254;
442 map.h16 = 50000;
443 map.h32 = 3000000000U;
444 map.h64 = 6000000000LL;
446 llvm::raw_string_ostream ostr(intermediate);
447 Output yout(ostr);
448 yout << map;
452 Input yin(intermediate);
453 BuiltInTypes map;
454 yin >> map;
456 EXPECT_FALSE(yin.error());
457 EXPECT_TRUE(map.str.equals("one two"));
458 EXPECT_TRUE(map.stdstr == "three four");
459 EXPECT_EQ(map.u64, 6000000000ULL);
460 EXPECT_EQ(map.u32, 3000000000U);
461 EXPECT_EQ(map.u16, 50000);
462 EXPECT_EQ(map.u8, 254);
463 EXPECT_EQ(map.b, true);
464 EXPECT_EQ(map.s64, -6000000000LL);
465 EXPECT_EQ(map.s32, -2000000000L);
466 EXPECT_EQ(map.s16, -32000);
467 EXPECT_EQ(map.s8, -128);
468 EXPECT_EQ(map.f, 3.25);
469 EXPECT_EQ(map.d, -2.8625);
470 EXPECT_EQ(map.h8, Hex8(254));
471 EXPECT_EQ(map.h16, Hex16(50000));
472 EXPECT_EQ(map.h32, Hex32(3000000000U));
473 EXPECT_EQ(map.h64, Hex64(6000000000LL));
477 //===----------------------------------------------------------------------===//
478 // Test endian-aware types
479 //===----------------------------------------------------------------------===//
481 struct EndianTypes {
482 typedef llvm::support::detail::packed_endian_specific_integral<
483 float, llvm::support::little, llvm::support::unaligned>
484 ulittle_float;
485 typedef llvm::support::detail::packed_endian_specific_integral<
486 double, llvm::support::little, llvm::support::unaligned>
487 ulittle_double;
489 llvm::support::ulittle64_t u64;
490 llvm::support::ulittle32_t u32;
491 llvm::support::ulittle16_t u16;
492 llvm::support::little64_t s64;
493 llvm::support::little32_t s32;
494 llvm::support::little16_t s16;
495 ulittle_float f;
496 ulittle_double d;
499 namespace llvm {
500 namespace yaml {
501 template <> struct MappingTraits<EndianTypes> {
502 static void mapping(IO &io, EndianTypes &et) {
503 io.mapRequired("u64", et.u64);
504 io.mapRequired("u32", et.u32);
505 io.mapRequired("u16", et.u16);
506 io.mapRequired("s64", et.s64);
507 io.mapRequired("s32", et.s32);
508 io.mapRequired("s16", et.s16);
509 io.mapRequired("f", et.f);
510 io.mapRequired("d", et.d);
517 // Test the reading of all endian scalar conversions
519 TEST(YAMLIO, TestReadEndianTypes) {
520 EndianTypes map;
521 Input yin("---\n"
522 "u64: 5000000000\n"
523 "u32: 4000000000\n"
524 "u16: 65000\n"
525 "s64: -5000000000\n"
526 "s32: -2000000000\n"
527 "s16: -32000\n"
528 "f: 3.25\n"
529 "d: -2.8625\n"
530 "...\n");
531 yin >> map;
533 EXPECT_FALSE(yin.error());
534 EXPECT_EQ(map.u64, 5000000000ULL);
535 EXPECT_EQ(map.u32, 4000000000U);
536 EXPECT_EQ(map.u16, 65000);
537 EXPECT_EQ(map.s64, -5000000000LL);
538 EXPECT_EQ(map.s32, -2000000000L);
539 EXPECT_EQ(map.s16, -32000);
540 EXPECT_EQ(map.f, 3.25f);
541 EXPECT_EQ(map.d, -2.8625);
545 // Test writing then reading back all endian-aware scalar types
547 TEST(YAMLIO, TestReadWriteEndianTypes) {
548 std::string intermediate;
550 EndianTypes map;
551 map.u64 = 6000000000ULL;
552 map.u32 = 3000000000U;
553 map.u16 = 50000;
554 map.s64 = -6000000000LL;
555 map.s32 = -2000000000;
556 map.s16 = -32000;
557 map.f = 3.25f;
558 map.d = -2.8625;
560 llvm::raw_string_ostream ostr(intermediate);
561 Output yout(ostr);
562 yout << map;
566 Input yin(intermediate);
567 EndianTypes map;
568 yin >> map;
570 EXPECT_FALSE(yin.error());
571 EXPECT_EQ(map.u64, 6000000000ULL);
572 EXPECT_EQ(map.u32, 3000000000U);
573 EXPECT_EQ(map.u16, 50000);
574 EXPECT_EQ(map.s64, -6000000000LL);
575 EXPECT_EQ(map.s32, -2000000000L);
576 EXPECT_EQ(map.s16, -32000);
577 EXPECT_EQ(map.f, 3.25f);
578 EXPECT_EQ(map.d, -2.8625);
582 struct StringTypes {
583 llvm::StringRef str1;
584 llvm::StringRef str2;
585 llvm::StringRef str3;
586 llvm::StringRef str4;
587 llvm::StringRef str5;
588 llvm::StringRef str6;
589 llvm::StringRef str7;
590 llvm::StringRef str8;
591 llvm::StringRef str9;
592 llvm::StringRef str10;
593 llvm::StringRef str11;
594 std::string stdstr1;
595 std::string stdstr2;
596 std::string stdstr3;
597 std::string stdstr4;
598 std::string stdstr5;
599 std::string stdstr6;
600 std::string stdstr7;
601 std::string stdstr8;
602 std::string stdstr9;
603 std::string stdstr10;
604 std::string stdstr11;
605 std::string stdstr12;
608 namespace llvm {
609 namespace yaml {
610 template <>
611 struct MappingTraits<StringTypes> {
612 static void mapping(IO &io, StringTypes& st) {
613 io.mapRequired("str1", st.str1);
614 io.mapRequired("str2", st.str2);
615 io.mapRequired("str3", st.str3);
616 io.mapRequired("str4", st.str4);
617 io.mapRequired("str5", st.str5);
618 io.mapRequired("str6", st.str6);
619 io.mapRequired("str7", st.str7);
620 io.mapRequired("str8", st.str8);
621 io.mapRequired("str9", st.str9);
622 io.mapRequired("str10", st.str10);
623 io.mapRequired("str11", st.str11);
624 io.mapRequired("stdstr1", st.stdstr1);
625 io.mapRequired("stdstr2", st.stdstr2);
626 io.mapRequired("stdstr3", st.stdstr3);
627 io.mapRequired("stdstr4", st.stdstr4);
628 io.mapRequired("stdstr5", st.stdstr5);
629 io.mapRequired("stdstr6", st.stdstr6);
630 io.mapRequired("stdstr7", st.stdstr7);
631 io.mapRequired("stdstr8", st.stdstr8);
632 io.mapRequired("stdstr9", st.stdstr9);
633 io.mapRequired("stdstr10", st.stdstr10);
634 io.mapRequired("stdstr11", st.stdstr11);
635 io.mapRequired("stdstr12", st.stdstr12);
641 TEST(YAMLIO, TestReadWriteStringTypes) {
642 std::string intermediate;
644 StringTypes map;
645 map.str1 = "'aaa";
646 map.str2 = "\"bbb";
647 map.str3 = "`ccc";
648 map.str4 = "@ddd";
649 map.str5 = "";
650 map.str6 = "0000000004000000";
651 map.str7 = "true";
652 map.str8 = "FALSE";
653 map.str9 = "~";
654 map.str10 = "0.2e20";
655 map.str11 = "0x30";
656 map.stdstr1 = "'eee";
657 map.stdstr2 = "\"fff";
658 map.stdstr3 = "`ggg";
659 map.stdstr4 = "@hhh";
660 map.stdstr5 = "";
661 map.stdstr6 = "0000000004000000";
662 map.stdstr7 = "true";
663 map.stdstr8 = "FALSE";
664 map.stdstr9 = "~";
665 map.stdstr10 = "0.2e20";
666 map.stdstr11 = "0x30";
667 map.stdstr12 = "- match";
669 llvm::raw_string_ostream ostr(intermediate);
670 Output yout(ostr);
671 yout << map;
674 llvm::StringRef flowOut(intermediate);
675 EXPECT_NE(llvm::StringRef::npos, flowOut.find("'''aaa"));
676 EXPECT_NE(llvm::StringRef::npos, flowOut.find("'\"bbb'"));
677 EXPECT_NE(llvm::StringRef::npos, flowOut.find("'`ccc'"));
678 EXPECT_NE(llvm::StringRef::npos, flowOut.find("'@ddd'"));
679 EXPECT_NE(llvm::StringRef::npos, flowOut.find("''\n"));
680 EXPECT_NE(llvm::StringRef::npos, flowOut.find("'0000000004000000'\n"));
681 EXPECT_NE(llvm::StringRef::npos, flowOut.find("'true'\n"));
682 EXPECT_NE(llvm::StringRef::npos, flowOut.find("'FALSE'\n"));
683 EXPECT_NE(llvm::StringRef::npos, flowOut.find("'~'\n"));
684 EXPECT_NE(llvm::StringRef::npos, flowOut.find("'0.2e20'\n"));
685 EXPECT_NE(llvm::StringRef::npos, flowOut.find("'0x30'\n"));
686 EXPECT_NE(llvm::StringRef::npos, flowOut.find("'- match'\n"));
687 EXPECT_NE(std::string::npos, flowOut.find("'''eee"));
688 EXPECT_NE(std::string::npos, flowOut.find("'\"fff'"));
689 EXPECT_NE(std::string::npos, flowOut.find("'`ggg'"));
690 EXPECT_NE(std::string::npos, flowOut.find("'@hhh'"));
691 EXPECT_NE(std::string::npos, flowOut.find("''\n"));
692 EXPECT_NE(std::string::npos, flowOut.find("'0000000004000000'\n"));
695 Input yin(intermediate);
696 StringTypes map;
697 yin >> map;
699 EXPECT_FALSE(yin.error());
700 EXPECT_TRUE(map.str1.equals("'aaa"));
701 EXPECT_TRUE(map.str2.equals("\"bbb"));
702 EXPECT_TRUE(map.str3.equals("`ccc"));
703 EXPECT_TRUE(map.str4.equals("@ddd"));
704 EXPECT_TRUE(map.str5.equals(""));
705 EXPECT_TRUE(map.str6.equals("0000000004000000"));
706 EXPECT_TRUE(map.stdstr1 == "'eee");
707 EXPECT_TRUE(map.stdstr2 == "\"fff");
708 EXPECT_TRUE(map.stdstr3 == "`ggg");
709 EXPECT_TRUE(map.stdstr4 == "@hhh");
710 EXPECT_TRUE(map.stdstr5 == "");
711 EXPECT_TRUE(map.stdstr6 == "0000000004000000");
715 //===----------------------------------------------------------------------===//
716 // Test ScalarEnumerationTraits
717 //===----------------------------------------------------------------------===//
719 enum Colors {
720 cRed,
721 cBlue,
722 cGreen,
723 cYellow
726 struct ColorMap {
727 Colors c1;
728 Colors c2;
729 Colors c3;
730 Colors c4;
731 Colors c5;
732 Colors c6;
735 namespace llvm {
736 namespace yaml {
737 template <>
738 struct ScalarEnumerationTraits<Colors> {
739 static void enumeration(IO &io, Colors &value) {
740 io.enumCase(value, "red", cRed);
741 io.enumCase(value, "blue", cBlue);
742 io.enumCase(value, "green", cGreen);
743 io.enumCase(value, "yellow",cYellow);
746 template <>
747 struct MappingTraits<ColorMap> {
748 static void mapping(IO &io, ColorMap& c) {
749 io.mapRequired("c1", c.c1);
750 io.mapRequired("c2", c.c2);
751 io.mapRequired("c3", c.c3);
752 io.mapOptional("c4", c.c4, cBlue); // supplies default
753 io.mapOptional("c5", c.c5, cYellow); // supplies default
754 io.mapOptional("c6", c.c6, cRed); // supplies default
762 // Test reading enumerated scalars
764 TEST(YAMLIO, TestEnumRead) {
765 ColorMap map;
766 Input yin("---\n"
767 "c1: blue\n"
768 "c2: red\n"
769 "c3: green\n"
770 "c5: yellow\n"
771 "...\n");
772 yin >> map;
774 EXPECT_FALSE(yin.error());
775 EXPECT_EQ(cBlue, map.c1);
776 EXPECT_EQ(cRed, map.c2);
777 EXPECT_EQ(cGreen, map.c3);
778 EXPECT_EQ(cBlue, map.c4); // tests default
779 EXPECT_EQ(cYellow,map.c5); // tests overridden
780 EXPECT_EQ(cRed, map.c6); // tests default
785 //===----------------------------------------------------------------------===//
786 // Test ScalarBitSetTraits
787 //===----------------------------------------------------------------------===//
789 enum MyFlags {
790 flagNone = 0,
791 flagBig = 1 << 0,
792 flagFlat = 1 << 1,
793 flagRound = 1 << 2,
794 flagPointy = 1 << 3
796 inline MyFlags operator|(MyFlags a, MyFlags b) {
797 return static_cast<MyFlags>(
798 static_cast<uint32_t>(a) | static_cast<uint32_t>(b));
801 struct FlagsMap {
802 MyFlags f1;
803 MyFlags f2;
804 MyFlags f3;
805 MyFlags f4;
809 namespace llvm {
810 namespace yaml {
811 template <>
812 struct ScalarBitSetTraits<MyFlags> {
813 static void bitset(IO &io, MyFlags &value) {
814 io.bitSetCase(value, "big", flagBig);
815 io.bitSetCase(value, "flat", flagFlat);
816 io.bitSetCase(value, "round", flagRound);
817 io.bitSetCase(value, "pointy",flagPointy);
820 template <>
821 struct MappingTraits<FlagsMap> {
822 static void mapping(IO &io, FlagsMap& c) {
823 io.mapRequired("f1", c.f1);
824 io.mapRequired("f2", c.f2);
825 io.mapRequired("f3", c.f3);
826 io.mapOptional("f4", c.f4, MyFlags(flagRound));
834 // Test reading flow sequence representing bit-mask values
836 TEST(YAMLIO, TestFlagsRead) {
837 FlagsMap map;
838 Input yin("---\n"
839 "f1: [ big ]\n"
840 "f2: [ round, flat ]\n"
841 "f3: []\n"
842 "...\n");
843 yin >> map;
845 EXPECT_FALSE(yin.error());
846 EXPECT_EQ(flagBig, map.f1);
847 EXPECT_EQ(flagRound|flagFlat, map.f2);
848 EXPECT_EQ(flagNone, map.f3); // check empty set
849 EXPECT_EQ(flagRound, map.f4); // check optional key
854 // Test writing then reading back bit-mask values
856 TEST(YAMLIO, TestReadWriteFlags) {
857 std::string intermediate;
859 FlagsMap map;
860 map.f1 = flagBig;
861 map.f2 = flagRound | flagFlat;
862 map.f3 = flagNone;
863 map.f4 = flagNone;
865 llvm::raw_string_ostream ostr(intermediate);
866 Output yout(ostr);
867 yout << map;
871 Input yin(intermediate);
872 FlagsMap map2;
873 yin >> map2;
875 EXPECT_FALSE(yin.error());
876 EXPECT_EQ(flagBig, map2.f1);
877 EXPECT_EQ(flagRound|flagFlat, map2.f2);
878 EXPECT_EQ(flagNone, map2.f3);
879 //EXPECT_EQ(flagRound, map2.f4); // check optional key
885 //===----------------------------------------------------------------------===//
886 // Test ScalarTraits
887 //===----------------------------------------------------------------------===//
889 struct MyCustomType {
890 int length;
891 int width;
894 struct MyCustomTypeMap {
895 MyCustomType f1;
896 MyCustomType f2;
897 int f3;
901 namespace llvm {
902 namespace yaml {
903 template <>
904 struct MappingTraits<MyCustomTypeMap> {
905 static void mapping(IO &io, MyCustomTypeMap& s) {
906 io.mapRequired("f1", s.f1);
907 io.mapRequired("f2", s.f2);
908 io.mapRequired("f3", s.f3);
911 // MyCustomType is formatted as a yaml scalar. A value of
912 // {length=3, width=4} would be represented in yaml as "3 by 4".
913 template<>
914 struct ScalarTraits<MyCustomType> {
915 static void output(const MyCustomType &value, void* ctxt, llvm::raw_ostream &out) {
916 out << llvm::format("%d by %d", value.length, value.width);
918 static StringRef input(StringRef scalar, void* ctxt, MyCustomType &value) {
919 size_t byStart = scalar.find("by");
920 if ( byStart != StringRef::npos ) {
921 StringRef lenStr = scalar.slice(0, byStart);
922 lenStr = lenStr.rtrim();
923 if ( lenStr.getAsInteger(0, value.length) ) {
924 return "malformed length";
926 StringRef widthStr = scalar.drop_front(byStart+2);
927 widthStr = widthStr.ltrim();
928 if ( widthStr.getAsInteger(0, value.width) ) {
929 return "malformed width";
931 return StringRef();
933 else {
934 return "malformed by";
937 static QuotingType mustQuote(StringRef) { return QuotingType::Single; }
944 // Test writing then reading back custom values
946 TEST(YAMLIO, TestReadWriteMyCustomType) {
947 std::string intermediate;
949 MyCustomTypeMap map;
950 map.f1.length = 1;
951 map.f1.width = 4;
952 map.f2.length = 100;
953 map.f2.width = 400;
954 map.f3 = 10;
956 llvm::raw_string_ostream ostr(intermediate);
957 Output yout(ostr);
958 yout << map;
962 Input yin(intermediate);
963 MyCustomTypeMap map2;
964 yin >> map2;
966 EXPECT_FALSE(yin.error());
967 EXPECT_EQ(1, map2.f1.length);
968 EXPECT_EQ(4, map2.f1.width);
969 EXPECT_EQ(100, map2.f2.length);
970 EXPECT_EQ(400, map2.f2.width);
971 EXPECT_EQ(10, map2.f3);
976 //===----------------------------------------------------------------------===//
977 // Test BlockScalarTraits
978 //===----------------------------------------------------------------------===//
980 struct MultilineStringType {
981 std::string str;
984 struct MultilineStringTypeMap {
985 MultilineStringType name;
986 MultilineStringType description;
987 MultilineStringType ingredients;
988 MultilineStringType recipes;
989 MultilineStringType warningLabels;
990 MultilineStringType documentation;
991 int price;
994 namespace llvm {
995 namespace yaml {
996 template <>
997 struct MappingTraits<MultilineStringTypeMap> {
998 static void mapping(IO &io, MultilineStringTypeMap& s) {
999 io.mapRequired("name", s.name);
1000 io.mapRequired("description", s.description);
1001 io.mapRequired("ingredients", s.ingredients);
1002 io.mapRequired("recipes", s.recipes);
1003 io.mapRequired("warningLabels", s.warningLabels);
1004 io.mapRequired("documentation", s.documentation);
1005 io.mapRequired("price", s.price);
1009 // MultilineStringType is formatted as a yaml block literal scalar. A value of
1010 // "Hello\nWorld" would be represented in yaml as
1011 // |
1012 // Hello
1013 // World
1014 template <>
1015 struct BlockScalarTraits<MultilineStringType> {
1016 static void output(const MultilineStringType &value, void *ctxt,
1017 llvm::raw_ostream &out) {
1018 out << value.str;
1020 static StringRef input(StringRef scalar, void *ctxt,
1021 MultilineStringType &value) {
1022 value.str = scalar.str();
1023 return StringRef();
1029 LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(MultilineStringType)
1032 // Test writing then reading back custom values
1034 TEST(YAMLIO, TestReadWriteMultilineStringType) {
1035 std::string intermediate;
1037 MultilineStringTypeMap map;
1038 map.name.str = "An Item";
1039 map.description.str = "Hello\nWorld";
1040 map.ingredients.str = "SubItem 1\nSub Item 2\n\nSub Item 3\n";
1041 map.recipes.str = "\n\nTest 1\n\n\n";
1042 map.warningLabels.str = "";
1043 map.documentation.str = "\n\n";
1044 map.price = 350;
1046 llvm::raw_string_ostream ostr(intermediate);
1047 Output yout(ostr);
1048 yout << map;
1051 Input yin(intermediate);
1052 MultilineStringTypeMap map2;
1053 yin >> map2;
1055 EXPECT_FALSE(yin.error());
1056 EXPECT_EQ(map2.name.str, "An Item\n");
1057 EXPECT_EQ(map2.description.str, "Hello\nWorld\n");
1058 EXPECT_EQ(map2.ingredients.str, "SubItem 1\nSub Item 2\n\nSub Item 3\n");
1059 EXPECT_EQ(map2.recipes.str, "\n\nTest 1\n");
1060 EXPECT_TRUE(map2.warningLabels.str.empty());
1061 EXPECT_TRUE(map2.documentation.str.empty());
1062 EXPECT_EQ(map2.price, 350);
1067 // Test writing then reading back custom values
1069 TEST(YAMLIO, TestReadWriteBlockScalarDocuments) {
1070 std::string intermediate;
1072 std::vector<MultilineStringType> documents;
1073 MultilineStringType doc;
1074 doc.str = "Hello\nWorld";
1075 documents.push_back(doc);
1077 llvm::raw_string_ostream ostr(intermediate);
1078 Output yout(ostr);
1079 yout << documents;
1081 // Verify that the block scalar header was written out on the same line
1082 // as the document marker.
1083 EXPECT_NE(llvm::StringRef::npos, llvm::StringRef(ostr.str()).find("--- |"));
1086 Input yin(intermediate);
1087 std::vector<MultilineStringType> documents2;
1088 yin >> documents2;
1090 EXPECT_FALSE(yin.error());
1091 EXPECT_EQ(documents2.size(), size_t(1));
1092 EXPECT_EQ(documents2[0].str, "Hello\nWorld\n");
1096 TEST(YAMLIO, TestReadWriteBlockScalarValue) {
1097 std::string intermediate;
1099 MultilineStringType doc;
1100 doc.str = "Just a block\nscalar doc";
1102 llvm::raw_string_ostream ostr(intermediate);
1103 Output yout(ostr);
1104 yout << doc;
1107 Input yin(intermediate);
1108 MultilineStringType doc;
1109 yin >> doc;
1111 EXPECT_FALSE(yin.error());
1112 EXPECT_EQ(doc.str, "Just a block\nscalar doc\n");
1116 //===----------------------------------------------------------------------===//
1117 // Test flow sequences
1118 //===----------------------------------------------------------------------===//
1120 LLVM_YAML_STRONG_TYPEDEF(int, MyNumber)
1121 LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(MyNumber)
1122 LLVM_YAML_STRONG_TYPEDEF(llvm::StringRef, MyString)
1123 LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(MyString)
1125 namespace llvm {
1126 namespace yaml {
1127 template<>
1128 struct ScalarTraits<MyNumber> {
1129 static void output(const MyNumber &value, void *, llvm::raw_ostream &out) {
1130 out << value;
1133 static StringRef input(StringRef scalar, void *, MyNumber &value) {
1134 long long n;
1135 if ( getAsSignedInteger(scalar, 0, n) )
1136 return "invalid number";
1137 value = n;
1138 return StringRef();
1141 static QuotingType mustQuote(StringRef) { return QuotingType::None; }
1144 template <> struct ScalarTraits<MyString> {
1145 using Impl = ScalarTraits<StringRef>;
1146 static void output(const MyString &V, void *Ctx, raw_ostream &OS) {
1147 Impl::output(V, Ctx, OS);
1149 static StringRef input(StringRef S, void *Ctx, MyString &V) {
1150 return Impl::input(S, Ctx, V.value);
1152 static QuotingType mustQuote(StringRef S) {
1153 return Impl::mustQuote(S);
1159 struct NameAndNumbers {
1160 llvm::StringRef name;
1161 std::vector<MyString> strings;
1162 std::vector<MyNumber> single;
1163 std::vector<MyNumber> numbers;
1166 namespace llvm {
1167 namespace yaml {
1168 template <>
1169 struct MappingTraits<NameAndNumbers> {
1170 static void mapping(IO &io, NameAndNumbers& nn) {
1171 io.mapRequired("name", nn.name);
1172 io.mapRequired("strings", nn.strings);
1173 io.mapRequired("single", nn.single);
1174 io.mapRequired("numbers", nn.numbers);
1180 typedef std::vector<MyNumber> MyNumberFlowSequence;
1182 LLVM_YAML_IS_SEQUENCE_VECTOR(MyNumberFlowSequence)
1184 struct NameAndNumbersFlow {
1185 llvm::StringRef name;
1186 std::vector<MyNumberFlowSequence> sequenceOfNumbers;
1189 namespace llvm {
1190 namespace yaml {
1191 template <>
1192 struct MappingTraits<NameAndNumbersFlow> {
1193 static void mapping(IO &io, NameAndNumbersFlow& nn) {
1194 io.mapRequired("name", nn.name);
1195 io.mapRequired("sequenceOfNumbers", nn.sequenceOfNumbers);
1202 // Test writing then reading back custom values
1204 TEST(YAMLIO, TestReadWriteMyFlowSequence) {
1205 std::string intermediate;
1207 NameAndNumbers map;
1208 map.name = "hello";
1209 map.strings.push_back(llvm::StringRef("one"));
1210 map.strings.push_back(llvm::StringRef("two"));
1211 map.single.push_back(1);
1212 map.numbers.push_back(10);
1213 map.numbers.push_back(-30);
1214 map.numbers.push_back(1024);
1216 llvm::raw_string_ostream ostr(intermediate);
1217 Output yout(ostr);
1218 yout << map;
1220 // Verify sequences were written in flow style
1221 ostr.flush();
1222 llvm::StringRef flowOut(intermediate);
1223 EXPECT_NE(llvm::StringRef::npos, flowOut.find("one, two"));
1224 EXPECT_NE(llvm::StringRef::npos, flowOut.find("10, -30, 1024"));
1228 Input yin(intermediate);
1229 NameAndNumbers map2;
1230 yin >> map2;
1232 EXPECT_FALSE(yin.error());
1233 EXPECT_TRUE(map2.name.equals("hello"));
1234 EXPECT_EQ(map2.strings.size(), 2UL);
1235 EXPECT_TRUE(map2.strings[0].value.equals("one"));
1236 EXPECT_TRUE(map2.strings[1].value.equals("two"));
1237 EXPECT_EQ(map2.single.size(), 1UL);
1238 EXPECT_EQ(1, map2.single[0]);
1239 EXPECT_EQ(map2.numbers.size(), 3UL);
1240 EXPECT_EQ(10, map2.numbers[0]);
1241 EXPECT_EQ(-30, map2.numbers[1]);
1242 EXPECT_EQ(1024, map2.numbers[2]);
1248 // Test writing then reading back a sequence of flow sequences.
1250 TEST(YAMLIO, TestReadWriteSequenceOfMyFlowSequence) {
1251 std::string intermediate;
1253 NameAndNumbersFlow map;
1254 map.name = "hello";
1255 MyNumberFlowSequence single = { 0 };
1256 MyNumberFlowSequence numbers = { 12, 1, -512 };
1257 map.sequenceOfNumbers.push_back(single);
1258 map.sequenceOfNumbers.push_back(numbers);
1259 map.sequenceOfNumbers.push_back(MyNumberFlowSequence());
1261 llvm::raw_string_ostream ostr(intermediate);
1262 Output yout(ostr);
1263 yout << map;
1265 // Verify sequences were written in flow style
1266 // and that the parent sequence used '-'.
1267 ostr.flush();
1268 llvm::StringRef flowOut(intermediate);
1269 EXPECT_NE(llvm::StringRef::npos, flowOut.find("- [ 0 ]"));
1270 EXPECT_NE(llvm::StringRef::npos, flowOut.find("- [ 12, 1, -512 ]"));
1271 EXPECT_NE(llvm::StringRef::npos, flowOut.find("- [ ]"));
1275 Input yin(intermediate);
1276 NameAndNumbersFlow map2;
1277 yin >> map2;
1279 EXPECT_FALSE(yin.error());
1280 EXPECT_TRUE(map2.name.equals("hello"));
1281 EXPECT_EQ(map2.sequenceOfNumbers.size(), 3UL);
1282 EXPECT_EQ(map2.sequenceOfNumbers[0].size(), 1UL);
1283 EXPECT_EQ(0, map2.sequenceOfNumbers[0][0]);
1284 EXPECT_EQ(map2.sequenceOfNumbers[1].size(), 3UL);
1285 EXPECT_EQ(12, map2.sequenceOfNumbers[1][0]);
1286 EXPECT_EQ(1, map2.sequenceOfNumbers[1][1]);
1287 EXPECT_EQ(-512, map2.sequenceOfNumbers[1][2]);
1288 EXPECT_TRUE(map2.sequenceOfNumbers[2].empty());
1292 //===----------------------------------------------------------------------===//
1293 // Test normalizing/denormalizing
1294 //===----------------------------------------------------------------------===//
1296 LLVM_YAML_STRONG_TYPEDEF(uint32_t, TotalSeconds)
1298 typedef std::vector<TotalSeconds> SecondsSequence;
1300 LLVM_YAML_IS_SEQUENCE_VECTOR(TotalSeconds)
1303 namespace llvm {
1304 namespace yaml {
1305 template <>
1306 struct MappingTraits<TotalSeconds> {
1308 class NormalizedSeconds {
1309 public:
1310 NormalizedSeconds(IO &io)
1311 : hours(0), minutes(0), seconds(0) {
1313 NormalizedSeconds(IO &, TotalSeconds &secs)
1314 : hours(secs/3600),
1315 minutes((secs - (hours*3600))/60),
1316 seconds(secs % 60) {
1318 TotalSeconds denormalize(IO &) {
1319 return TotalSeconds(hours*3600 + minutes*60 + seconds);
1322 uint32_t hours;
1323 uint8_t minutes;
1324 uint8_t seconds;
1327 static void mapping(IO &io, TotalSeconds &secs) {
1328 MappingNormalization<NormalizedSeconds, TotalSeconds> keys(io, secs);
1330 io.mapOptional("hours", keys->hours, (uint32_t)0);
1331 io.mapOptional("minutes", keys->minutes, (uint8_t)0);
1332 io.mapRequired("seconds", keys->seconds);
1340 // Test the reading of a yaml sequence of mappings
1342 TEST(YAMLIO, TestReadMySecondsSequence) {
1343 SecondsSequence seq;
1344 Input yin("---\n - hours: 1\n seconds: 5\n - seconds: 59\n...\n");
1345 yin >> seq;
1347 EXPECT_FALSE(yin.error());
1348 EXPECT_EQ(seq.size(), 2UL);
1349 EXPECT_EQ(seq[0], 3605U);
1350 EXPECT_EQ(seq[1], 59U);
1355 // Test writing then reading back custom values
1357 TEST(YAMLIO, TestReadWriteMySecondsSequence) {
1358 std::string intermediate;
1360 SecondsSequence seq;
1361 seq.push_back(4000);
1362 seq.push_back(500);
1363 seq.push_back(59);
1365 llvm::raw_string_ostream ostr(intermediate);
1366 Output yout(ostr);
1367 yout << seq;
1370 Input yin(intermediate);
1371 SecondsSequence seq2;
1372 yin >> seq2;
1374 EXPECT_FALSE(yin.error());
1375 EXPECT_EQ(seq2.size(), 3UL);
1376 EXPECT_EQ(seq2[0], 4000U);
1377 EXPECT_EQ(seq2[1], 500U);
1378 EXPECT_EQ(seq2[2], 59U);
1383 //===----------------------------------------------------------------------===//
1384 // Test dynamic typing
1385 //===----------------------------------------------------------------------===//
1387 enum AFlags {
1393 enum BFlags {
1399 enum Kind {
1400 kindA,
1401 kindB
1404 struct KindAndFlags {
1405 KindAndFlags() : kind(kindA), flags(0) { }
1406 KindAndFlags(Kind k, uint32_t f) : kind(k), flags(f) { }
1407 Kind kind;
1408 uint32_t flags;
1411 typedef std::vector<KindAndFlags> KindAndFlagsSequence;
1413 LLVM_YAML_IS_SEQUENCE_VECTOR(KindAndFlags)
1415 namespace llvm {
1416 namespace yaml {
1417 template <>
1418 struct ScalarEnumerationTraits<AFlags> {
1419 static void enumeration(IO &io, AFlags &value) {
1420 io.enumCase(value, "a1", a1);
1421 io.enumCase(value, "a2", a2);
1422 io.enumCase(value, "a3", a3);
1425 template <>
1426 struct ScalarEnumerationTraits<BFlags> {
1427 static void enumeration(IO &io, BFlags &value) {
1428 io.enumCase(value, "b1", b1);
1429 io.enumCase(value, "b2", b2);
1430 io.enumCase(value, "b3", b3);
1433 template <>
1434 struct ScalarEnumerationTraits<Kind> {
1435 static void enumeration(IO &io, Kind &value) {
1436 io.enumCase(value, "A", kindA);
1437 io.enumCase(value, "B", kindB);
1440 template <>
1441 struct MappingTraits<KindAndFlags> {
1442 static void mapping(IO &io, KindAndFlags& kf) {
1443 io.mapRequired("kind", kf.kind);
1444 // Type of "flags" field varies depending on "kind" field.
1445 // Use memcpy here to avoid breaking strict aliasing rules.
1446 if (kf.kind == kindA) {
1447 AFlags aflags = static_cast<AFlags>(kf.flags);
1448 io.mapRequired("flags", aflags);
1449 kf.flags = aflags;
1450 } else {
1451 BFlags bflags = static_cast<BFlags>(kf.flags);
1452 io.mapRequired("flags", bflags);
1453 kf.flags = bflags;
1462 // Test the reading of a yaml sequence dynamic types
1464 TEST(YAMLIO, TestReadKindAndFlagsSequence) {
1465 KindAndFlagsSequence seq;
1466 Input yin("---\n - kind: A\n flags: a2\n - kind: B\n flags: b1\n...\n");
1467 yin >> seq;
1469 EXPECT_FALSE(yin.error());
1470 EXPECT_EQ(seq.size(), 2UL);
1471 EXPECT_EQ(seq[0].kind, kindA);
1472 EXPECT_EQ(seq[0].flags, (uint32_t)a2);
1473 EXPECT_EQ(seq[1].kind, kindB);
1474 EXPECT_EQ(seq[1].flags, (uint32_t)b1);
1478 // Test writing then reading back dynamic types
1480 TEST(YAMLIO, TestReadWriteKindAndFlagsSequence) {
1481 std::string intermediate;
1483 KindAndFlagsSequence seq;
1484 seq.push_back(KindAndFlags(kindA,a1));
1485 seq.push_back(KindAndFlags(kindB,b1));
1486 seq.push_back(KindAndFlags(kindA,a2));
1487 seq.push_back(KindAndFlags(kindB,b2));
1488 seq.push_back(KindAndFlags(kindA,a3));
1490 llvm::raw_string_ostream ostr(intermediate);
1491 Output yout(ostr);
1492 yout << seq;
1495 Input yin(intermediate);
1496 KindAndFlagsSequence seq2;
1497 yin >> seq2;
1499 EXPECT_FALSE(yin.error());
1500 EXPECT_EQ(seq2.size(), 5UL);
1501 EXPECT_EQ(seq2[0].kind, kindA);
1502 EXPECT_EQ(seq2[0].flags, (uint32_t)a1);
1503 EXPECT_EQ(seq2[1].kind, kindB);
1504 EXPECT_EQ(seq2[1].flags, (uint32_t)b1);
1505 EXPECT_EQ(seq2[2].kind, kindA);
1506 EXPECT_EQ(seq2[2].flags, (uint32_t)a2);
1507 EXPECT_EQ(seq2[3].kind, kindB);
1508 EXPECT_EQ(seq2[3].flags, (uint32_t)b2);
1509 EXPECT_EQ(seq2[4].kind, kindA);
1510 EXPECT_EQ(seq2[4].flags, (uint32_t)a3);
1515 //===----------------------------------------------------------------------===//
1516 // Test document list
1517 //===----------------------------------------------------------------------===//
1519 struct FooBarMap {
1520 int foo;
1521 int bar;
1523 typedef std::vector<FooBarMap> FooBarMapDocumentList;
1525 LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(FooBarMap)
1528 namespace llvm {
1529 namespace yaml {
1530 template <>
1531 struct MappingTraits<FooBarMap> {
1532 static void mapping(IO &io, FooBarMap& fb) {
1533 io.mapRequired("foo", fb.foo);
1534 io.mapRequired("bar", fb.bar);
1542 // Test the reading of a yaml mapping
1544 TEST(YAMLIO, TestDocRead) {
1545 FooBarMap doc;
1546 Input yin("---\nfoo: 3\nbar: 5\n...\n");
1547 yin >> doc;
1549 EXPECT_FALSE(yin.error());
1550 EXPECT_EQ(doc.foo, 3);
1551 EXPECT_EQ(doc.bar,5);
1557 // Test writing then reading back a sequence of mappings
1559 TEST(YAMLIO, TestSequenceDocListWriteAndRead) {
1560 std::string intermediate;
1562 FooBarMap doc1;
1563 doc1.foo = 10;
1564 doc1.bar = -3;
1565 FooBarMap doc2;
1566 doc2.foo = 257;
1567 doc2.bar = 0;
1568 std::vector<FooBarMap> docList;
1569 docList.push_back(doc1);
1570 docList.push_back(doc2);
1572 llvm::raw_string_ostream ostr(intermediate);
1573 Output yout(ostr);
1574 yout << docList;
1579 Input yin(intermediate);
1580 std::vector<FooBarMap> docList2;
1581 yin >> docList2;
1583 EXPECT_FALSE(yin.error());
1584 EXPECT_EQ(docList2.size(), 2UL);
1585 FooBarMap& map1 = docList2[0];
1586 FooBarMap& map2 = docList2[1];
1587 EXPECT_EQ(map1.foo, 10);
1588 EXPECT_EQ(map1.bar, -3);
1589 EXPECT_EQ(map2.foo, 257);
1590 EXPECT_EQ(map2.bar, 0);
1594 //===----------------------------------------------------------------------===//
1595 // Test document tags
1596 //===----------------------------------------------------------------------===//
1598 struct MyDouble {
1599 MyDouble() : value(0.0) { }
1600 MyDouble(double x) : value(x) { }
1601 double value;
1604 LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(MyDouble)
1607 namespace llvm {
1608 namespace yaml {
1609 template <>
1610 struct MappingTraits<MyDouble> {
1611 static void mapping(IO &io, MyDouble &d) {
1612 if (io.mapTag("!decimal", true)) {
1613 mappingDecimal(io, d);
1614 } else if (io.mapTag("!fraction")) {
1615 mappingFraction(io, d);
1618 static void mappingDecimal(IO &io, MyDouble &d) {
1619 io.mapRequired("value", d.value);
1621 static void mappingFraction(IO &io, MyDouble &d) {
1622 double num, denom;
1623 io.mapRequired("numerator", num);
1624 io.mapRequired("denominator", denom);
1625 // convert fraction to double
1626 d.value = num/denom;
1634 // Test the reading of two different tagged yaml documents.
1636 TEST(YAMLIO, TestTaggedDocuments) {
1637 std::vector<MyDouble> docList;
1638 Input yin("--- !decimal\nvalue: 3.0\n"
1639 "--- !fraction\nnumerator: 9.0\ndenominator: 2\n...\n");
1640 yin >> docList;
1641 EXPECT_FALSE(yin.error());
1642 EXPECT_EQ(docList.size(), 2UL);
1643 EXPECT_EQ(docList[0].value, 3.0);
1644 EXPECT_EQ(docList[1].value, 4.5);
1650 // Test writing then reading back tagged documents
1652 TEST(YAMLIO, TestTaggedDocumentsWriteAndRead) {
1653 std::string intermediate;
1655 MyDouble a(10.25);
1656 MyDouble b(-3.75);
1657 std::vector<MyDouble> docList;
1658 docList.push_back(a);
1659 docList.push_back(b);
1661 llvm::raw_string_ostream ostr(intermediate);
1662 Output yout(ostr);
1663 yout << docList;
1667 Input yin(intermediate);
1668 std::vector<MyDouble> docList2;
1669 yin >> docList2;
1671 EXPECT_FALSE(yin.error());
1672 EXPECT_EQ(docList2.size(), 2UL);
1673 EXPECT_EQ(docList2[0].value, 10.25);
1674 EXPECT_EQ(docList2[1].value, -3.75);
1679 //===----------------------------------------------------------------------===//
1680 // Test mapping validation
1681 //===----------------------------------------------------------------------===//
1683 struct MyValidation {
1684 double value;
1687 LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(MyValidation)
1689 namespace llvm {
1690 namespace yaml {
1691 template <>
1692 struct MappingTraits<MyValidation> {
1693 static void mapping(IO &io, MyValidation &d) {
1694 io.mapRequired("value", d.value);
1696 static StringRef validate(IO &io, MyValidation &d) {
1697 if (d.value < 0)
1698 return "negative value";
1699 return StringRef();
1707 // Test that validate() is called and complains about the negative value.
1709 TEST(YAMLIO, TestValidatingInput) {
1710 std::vector<MyValidation> docList;
1711 Input yin("--- \nvalue: 3.0\n"
1712 "--- \nvalue: -1.0\n...\n",
1713 nullptr, suppressErrorMessages);
1714 yin >> docList;
1715 EXPECT_TRUE(!!yin.error());
1718 //===----------------------------------------------------------------------===//
1719 // Test flow mapping
1720 //===----------------------------------------------------------------------===//
1722 struct FlowFooBar {
1723 int foo;
1724 int bar;
1726 FlowFooBar() : foo(0), bar(0) {}
1727 FlowFooBar(int foo, int bar) : foo(foo), bar(bar) {}
1730 typedef std::vector<FlowFooBar> FlowFooBarSequence;
1732 LLVM_YAML_IS_SEQUENCE_VECTOR(FlowFooBar)
1734 struct FlowFooBarDoc {
1735 FlowFooBar attribute;
1736 FlowFooBarSequence seq;
1739 namespace llvm {
1740 namespace yaml {
1741 template <>
1742 struct MappingTraits<FlowFooBar> {
1743 static void mapping(IO &io, FlowFooBar &fb) {
1744 io.mapRequired("foo", fb.foo);
1745 io.mapRequired("bar", fb.bar);
1748 static const bool flow = true;
1751 template <>
1752 struct MappingTraits<FlowFooBarDoc> {
1753 static void mapping(IO &io, FlowFooBarDoc &fb) {
1754 io.mapRequired("attribute", fb.attribute);
1755 io.mapRequired("seq", fb.seq);
1762 // Test writing then reading back custom mappings
1764 TEST(YAMLIO, TestReadWriteMyFlowMapping) {
1765 std::string intermediate;
1767 FlowFooBarDoc doc;
1768 doc.attribute = FlowFooBar(42, 907);
1769 doc.seq.push_back(FlowFooBar(1, 2));
1770 doc.seq.push_back(FlowFooBar(0, 0));
1771 doc.seq.push_back(FlowFooBar(-1, 1024));
1773 llvm::raw_string_ostream ostr(intermediate);
1774 Output yout(ostr);
1775 yout << doc;
1777 // Verify that mappings were written in flow style
1778 ostr.flush();
1779 llvm::StringRef flowOut(intermediate);
1780 EXPECT_NE(llvm::StringRef::npos, flowOut.find("{ foo: 42, bar: 907 }"));
1781 EXPECT_NE(llvm::StringRef::npos, flowOut.find("- { foo: 1, bar: 2 }"));
1782 EXPECT_NE(llvm::StringRef::npos, flowOut.find("- { foo: 0, bar: 0 }"));
1783 EXPECT_NE(llvm::StringRef::npos, flowOut.find("- { foo: -1, bar: 1024 }"));
1787 Input yin(intermediate);
1788 FlowFooBarDoc doc2;
1789 yin >> doc2;
1791 EXPECT_FALSE(yin.error());
1792 EXPECT_EQ(doc2.attribute.foo, 42);
1793 EXPECT_EQ(doc2.attribute.bar, 907);
1794 EXPECT_EQ(doc2.seq.size(), 3UL);
1795 EXPECT_EQ(doc2.seq[0].foo, 1);
1796 EXPECT_EQ(doc2.seq[0].bar, 2);
1797 EXPECT_EQ(doc2.seq[1].foo, 0);
1798 EXPECT_EQ(doc2.seq[1].bar, 0);
1799 EXPECT_EQ(doc2.seq[2].foo, -1);
1800 EXPECT_EQ(doc2.seq[2].bar, 1024);
1804 //===----------------------------------------------------------------------===//
1805 // Test error handling
1806 //===----------------------------------------------------------------------===//
1809 // Test error handling of unknown enumerated scalar
1811 TEST(YAMLIO, TestColorsReadError) {
1812 ColorMap map;
1813 Input yin("---\n"
1814 "c1: blue\n"
1815 "c2: purple\n"
1816 "c3: green\n"
1817 "...\n",
1818 /*Ctxt=*/nullptr,
1819 suppressErrorMessages);
1820 yin >> map;
1821 EXPECT_TRUE(!!yin.error());
1826 // Test error handling of flow sequence with unknown value
1828 TEST(YAMLIO, TestFlagsReadError) {
1829 FlagsMap map;
1830 Input yin("---\n"
1831 "f1: [ big ]\n"
1832 "f2: [ round, hollow ]\n"
1833 "f3: []\n"
1834 "...\n",
1835 /*Ctxt=*/nullptr,
1836 suppressErrorMessages);
1837 yin >> map;
1839 EXPECT_TRUE(!!yin.error());
1844 // Test error handling reading built-in uint8_t type
1846 TEST(YAMLIO, TestReadBuiltInTypesUint8Error) {
1847 std::vector<uint8_t> seq;
1848 Input yin("---\n"
1849 "- 255\n"
1850 "- 0\n"
1851 "- 257\n"
1852 "...\n",
1853 /*Ctxt=*/nullptr,
1854 suppressErrorMessages);
1855 yin >> seq;
1857 EXPECT_TRUE(!!yin.error());
1862 // Test error handling reading built-in uint16_t type
1864 TEST(YAMLIO, TestReadBuiltInTypesUint16Error) {
1865 std::vector<uint16_t> seq;
1866 Input yin("---\n"
1867 "- 65535\n"
1868 "- 0\n"
1869 "- 66000\n"
1870 "...\n",
1871 /*Ctxt=*/nullptr,
1872 suppressErrorMessages);
1873 yin >> seq;
1875 EXPECT_TRUE(!!yin.error());
1880 // Test error handling reading built-in uint32_t type
1882 TEST(YAMLIO, TestReadBuiltInTypesUint32Error) {
1883 std::vector<uint32_t> seq;
1884 Input yin("---\n"
1885 "- 4000000000\n"
1886 "- 0\n"
1887 "- 5000000000\n"
1888 "...\n",
1889 /*Ctxt=*/nullptr,
1890 suppressErrorMessages);
1891 yin >> seq;
1893 EXPECT_TRUE(!!yin.error());
1898 // Test error handling reading built-in uint64_t type
1900 TEST(YAMLIO, TestReadBuiltInTypesUint64Error) {
1901 std::vector<uint64_t> seq;
1902 Input yin("---\n"
1903 "- 18446744073709551615\n"
1904 "- 0\n"
1905 "- 19446744073709551615\n"
1906 "...\n",
1907 /*Ctxt=*/nullptr,
1908 suppressErrorMessages);
1909 yin >> seq;
1911 EXPECT_TRUE(!!yin.error());
1916 // Test error handling reading built-in int8_t type
1918 TEST(YAMLIO, TestReadBuiltInTypesint8OverError) {
1919 std::vector<int8_t> seq;
1920 Input yin("---\n"
1921 "- -128\n"
1922 "- 0\n"
1923 "- 127\n"
1924 "- 128\n"
1925 "...\n",
1926 /*Ctxt=*/nullptr,
1927 suppressErrorMessages);
1928 yin >> seq;
1930 EXPECT_TRUE(!!yin.error());
1934 // Test error handling reading built-in int8_t type
1936 TEST(YAMLIO, TestReadBuiltInTypesint8UnderError) {
1937 std::vector<int8_t> seq;
1938 Input yin("---\n"
1939 "- -128\n"
1940 "- 0\n"
1941 "- 127\n"
1942 "- -129\n"
1943 "...\n",
1944 /*Ctxt=*/nullptr,
1945 suppressErrorMessages);
1946 yin >> seq;
1948 EXPECT_TRUE(!!yin.error());
1953 // Test error handling reading built-in int16_t type
1955 TEST(YAMLIO, TestReadBuiltInTypesint16UnderError) {
1956 std::vector<int16_t> seq;
1957 Input yin("---\n"
1958 "- 32767\n"
1959 "- 0\n"
1960 "- -32768\n"
1961 "- -32769\n"
1962 "...\n",
1963 /*Ctxt=*/nullptr,
1964 suppressErrorMessages);
1965 yin >> seq;
1967 EXPECT_TRUE(!!yin.error());
1972 // Test error handling reading built-in int16_t type
1974 TEST(YAMLIO, TestReadBuiltInTypesint16OverError) {
1975 std::vector<int16_t> seq;
1976 Input yin("---\n"
1977 "- 32767\n"
1978 "- 0\n"
1979 "- -32768\n"
1980 "- 32768\n"
1981 "...\n",
1982 /*Ctxt=*/nullptr,
1983 suppressErrorMessages);
1984 yin >> seq;
1986 EXPECT_TRUE(!!yin.error());
1991 // Test error handling reading built-in int32_t type
1993 TEST(YAMLIO, TestReadBuiltInTypesint32UnderError) {
1994 std::vector<int32_t> seq;
1995 Input yin("---\n"
1996 "- 2147483647\n"
1997 "- 0\n"
1998 "- -2147483648\n"
1999 "- -2147483649\n"
2000 "...\n",
2001 /*Ctxt=*/nullptr,
2002 suppressErrorMessages);
2003 yin >> seq;
2005 EXPECT_TRUE(!!yin.error());
2009 // Test error handling reading built-in int32_t type
2011 TEST(YAMLIO, TestReadBuiltInTypesint32OverError) {
2012 std::vector<int32_t> seq;
2013 Input yin("---\n"
2014 "- 2147483647\n"
2015 "- 0\n"
2016 "- -2147483648\n"
2017 "- 2147483649\n"
2018 "...\n",
2019 /*Ctxt=*/nullptr,
2020 suppressErrorMessages);
2021 yin >> seq;
2023 EXPECT_TRUE(!!yin.error());
2028 // Test error handling reading built-in int64_t type
2030 TEST(YAMLIO, TestReadBuiltInTypesint64UnderError) {
2031 std::vector<int64_t> seq;
2032 Input yin("---\n"
2033 "- -9223372036854775808\n"
2034 "- 0\n"
2035 "- 9223372036854775807\n"
2036 "- -9223372036854775809\n"
2037 "...\n",
2038 /*Ctxt=*/nullptr,
2039 suppressErrorMessages);
2040 yin >> seq;
2042 EXPECT_TRUE(!!yin.error());
2046 // Test error handling reading built-in int64_t type
2048 TEST(YAMLIO, TestReadBuiltInTypesint64OverError) {
2049 std::vector<int64_t> seq;
2050 Input yin("---\n"
2051 "- -9223372036854775808\n"
2052 "- 0\n"
2053 "- 9223372036854775807\n"
2054 "- 9223372036854775809\n"
2055 "...\n",
2056 /*Ctxt=*/nullptr,
2057 suppressErrorMessages);
2058 yin >> seq;
2060 EXPECT_TRUE(!!yin.error());
2064 // Test error handling reading built-in float type
2066 TEST(YAMLIO, TestReadBuiltInTypesFloatError) {
2067 std::vector<float> seq;
2068 Input yin("---\n"
2069 "- 0.0\n"
2070 "- 1000.1\n"
2071 "- -123.456\n"
2072 "- 1.2.3\n"
2073 "...\n",
2074 /*Ctxt=*/nullptr,
2075 suppressErrorMessages);
2076 yin >> seq;
2078 EXPECT_TRUE(!!yin.error());
2082 // Test error handling reading built-in float type
2084 TEST(YAMLIO, TestReadBuiltInTypesDoubleError) {
2085 std::vector<double> seq;
2086 Input yin("---\n"
2087 "- 0.0\n"
2088 "- 1000.1\n"
2089 "- -123.456\n"
2090 "- 1.2.3\n"
2091 "...\n",
2092 /*Ctxt=*/nullptr,
2093 suppressErrorMessages);
2094 yin >> seq;
2096 EXPECT_TRUE(!!yin.error());
2100 // Test error handling reading built-in Hex8 type
2102 LLVM_YAML_IS_SEQUENCE_VECTOR(Hex8)
2103 TEST(YAMLIO, TestReadBuiltInTypesHex8Error) {
2104 std::vector<Hex8> seq;
2105 Input yin("---\n"
2106 "- 0x12\n"
2107 "- 0xFE\n"
2108 "- 0x123\n"
2109 "...\n",
2110 /*Ctxt=*/nullptr,
2111 suppressErrorMessages);
2112 yin >> seq;
2114 EXPECT_TRUE(!!yin.error());
2119 // Test error handling reading built-in Hex16 type
2121 LLVM_YAML_IS_SEQUENCE_VECTOR(Hex16)
2122 TEST(YAMLIO, TestReadBuiltInTypesHex16Error) {
2123 std::vector<Hex16> seq;
2124 Input yin("---\n"
2125 "- 0x0012\n"
2126 "- 0xFEFF\n"
2127 "- 0x12345\n"
2128 "...\n",
2129 /*Ctxt=*/nullptr,
2130 suppressErrorMessages);
2131 yin >> seq;
2133 EXPECT_TRUE(!!yin.error());
2137 // Test error handling reading built-in Hex32 type
2139 LLVM_YAML_IS_SEQUENCE_VECTOR(Hex32)
2140 TEST(YAMLIO, TestReadBuiltInTypesHex32Error) {
2141 std::vector<Hex32> seq;
2142 Input yin("---\n"
2143 "- 0x0012\n"
2144 "- 0xFEFF0000\n"
2145 "- 0x1234556789\n"
2146 "...\n",
2147 /*Ctxt=*/nullptr,
2148 suppressErrorMessages);
2149 yin >> seq;
2151 EXPECT_TRUE(!!yin.error());
2155 // Test error handling reading built-in Hex64 type
2157 LLVM_YAML_IS_SEQUENCE_VECTOR(Hex64)
2158 TEST(YAMLIO, TestReadBuiltInTypesHex64Error) {
2159 std::vector<Hex64> seq;
2160 Input yin("---\n"
2161 "- 0x0012\n"
2162 "- 0xFFEEDDCCBBAA9988\n"
2163 "- 0x12345567890ABCDEF0\n"
2164 "...\n",
2165 /*Ctxt=*/nullptr,
2166 suppressErrorMessages);
2167 yin >> seq;
2169 EXPECT_TRUE(!!yin.error());
2172 TEST(YAMLIO, TestMalformedMapFailsGracefully) {
2173 FooBar doc;
2175 // We pass the suppressErrorMessages handler to handle the error
2176 // message generated in the constructor of Input.
2177 Input yin("{foo:3, bar: 5}", /*Ctxt=*/nullptr, suppressErrorMessages);
2178 yin >> doc;
2179 EXPECT_TRUE(!!yin.error());
2183 Input yin("---\nfoo:3\nbar: 5\n...\n", /*Ctxt=*/nullptr, suppressErrorMessages);
2184 yin >> doc;
2185 EXPECT_TRUE(!!yin.error());
2189 struct OptionalTest {
2190 std::vector<int> Numbers;
2193 struct OptionalTestSeq {
2194 std::vector<OptionalTest> Tests;
2197 LLVM_YAML_IS_SEQUENCE_VECTOR(OptionalTest)
2198 namespace llvm {
2199 namespace yaml {
2200 template <>
2201 struct MappingTraits<OptionalTest> {
2202 static void mapping(IO& IO, OptionalTest &OT) {
2203 IO.mapOptional("Numbers", OT.Numbers);
2207 template <>
2208 struct MappingTraits<OptionalTestSeq> {
2209 static void mapping(IO &IO, OptionalTestSeq &OTS) {
2210 IO.mapOptional("Tests", OTS.Tests);
2216 TEST(YAMLIO, SequenceElideTest) {
2217 // Test that writing out a purely optional structure with its fields set to
2218 // default followed by other data is properly read back in.
2219 OptionalTestSeq Seq;
2220 OptionalTest One, Two, Three, Four;
2221 int N[] = {1, 2, 3};
2222 Three.Numbers.assign(N, N + 3);
2223 Seq.Tests.push_back(One);
2224 Seq.Tests.push_back(Two);
2225 Seq.Tests.push_back(Three);
2226 Seq.Tests.push_back(Four);
2228 std::string intermediate;
2230 llvm::raw_string_ostream ostr(intermediate);
2231 Output yout(ostr);
2232 yout << Seq;
2235 Input yin(intermediate);
2236 OptionalTestSeq Seq2;
2237 yin >> Seq2;
2239 EXPECT_FALSE(yin.error());
2241 EXPECT_EQ(4UL, Seq2.Tests.size());
2243 EXPECT_TRUE(Seq2.Tests[0].Numbers.empty());
2244 EXPECT_TRUE(Seq2.Tests[1].Numbers.empty());
2246 EXPECT_EQ(1, Seq2.Tests[2].Numbers[0]);
2247 EXPECT_EQ(2, Seq2.Tests[2].Numbers[1]);
2248 EXPECT_EQ(3, Seq2.Tests[2].Numbers[2]);
2250 EXPECT_TRUE(Seq2.Tests[3].Numbers.empty());
2253 TEST(YAMLIO, TestEmptyStringFailsForMapWithRequiredFields) {
2254 FooBar doc;
2255 Input yin("");
2256 yin >> doc;
2257 EXPECT_TRUE(!!yin.error());
2260 TEST(YAMLIO, TestEmptyStringSucceedsForMapWithOptionalFields) {
2261 OptionalTest doc;
2262 Input yin("");
2263 yin >> doc;
2264 EXPECT_FALSE(yin.error());
2267 TEST(YAMLIO, TestEmptyStringSucceedsForSequence) {
2268 std::vector<uint8_t> seq;
2269 Input yin("", /*Ctxt=*/nullptr, suppressErrorMessages);
2270 yin >> seq;
2272 EXPECT_FALSE(yin.error());
2273 EXPECT_TRUE(seq.empty());
2276 struct FlowMap {
2277 llvm::StringRef str1, str2, str3;
2278 FlowMap(llvm::StringRef str1, llvm::StringRef str2, llvm::StringRef str3)
2279 : str1(str1), str2(str2), str3(str3) {}
2282 struct FlowSeq {
2283 llvm::StringRef str;
2284 FlowSeq(llvm::StringRef S) : str(S) {}
2285 FlowSeq() = default;
2288 namespace llvm {
2289 namespace yaml {
2290 template <>
2291 struct MappingTraits<FlowMap> {
2292 static void mapping(IO &io, FlowMap &fm) {
2293 io.mapRequired("str1", fm.str1);
2294 io.mapRequired("str2", fm.str2);
2295 io.mapRequired("str3", fm.str3);
2298 static const bool flow = true;
2301 template <>
2302 struct ScalarTraits<FlowSeq> {
2303 static void output(const FlowSeq &value, void*, llvm::raw_ostream &out) {
2304 out << value.str;
2306 static StringRef input(StringRef scalar, void*, FlowSeq &value) {
2307 value.str = scalar;
2308 return "";
2311 static QuotingType mustQuote(StringRef S) { return QuotingType::None; }
2316 LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(FlowSeq)
2318 TEST(YAMLIO, TestWrapFlow) {
2319 std::string out;
2320 llvm::raw_string_ostream ostr(out);
2321 FlowMap Map("This is str1", "This is str2", "This is str3");
2322 std::vector<FlowSeq> Seq;
2323 Seq.emplace_back("This is str1");
2324 Seq.emplace_back("This is str2");
2325 Seq.emplace_back("This is str3");
2328 // 20 is just bellow the total length of the first mapping field.
2329 // We should wreap at every element.
2330 Output yout(ostr, nullptr, 15);
2332 yout << Map;
2333 ostr.flush();
2334 EXPECT_EQ(out,
2335 "---\n"
2336 "{ str1: This is str1, \n"
2337 " str2: This is str2, \n"
2338 " str3: This is str3 }\n"
2339 "...\n");
2340 out.clear();
2342 yout << Seq;
2343 ostr.flush();
2344 EXPECT_EQ(out,
2345 "---\n"
2346 "[ This is str1, \n"
2347 " This is str2, \n"
2348 " This is str3 ]\n"
2349 "...\n");
2350 out.clear();
2353 // 25 will allow the second field to be output on the first line.
2354 Output yout(ostr, nullptr, 25);
2356 yout << Map;
2357 ostr.flush();
2358 EXPECT_EQ(out,
2359 "---\n"
2360 "{ str1: This is str1, str2: This is str2, \n"
2361 " str3: This is str3 }\n"
2362 "...\n");
2363 out.clear();
2365 yout << Seq;
2366 ostr.flush();
2367 EXPECT_EQ(out,
2368 "---\n"
2369 "[ This is str1, This is str2, \n"
2370 " This is str3 ]\n"
2371 "...\n");
2372 out.clear();
2375 // 0 means no wrapping.
2376 Output yout(ostr, nullptr, 0);
2378 yout << Map;
2379 ostr.flush();
2380 EXPECT_EQ(out,
2381 "---\n"
2382 "{ str1: This is str1, str2: This is str2, str3: This is str3 }\n"
2383 "...\n");
2384 out.clear();
2386 yout << Seq;
2387 ostr.flush();
2388 EXPECT_EQ(out,
2389 "---\n"
2390 "[ This is str1, This is str2, This is str3 ]\n"
2391 "...\n");
2392 out.clear();
2396 struct MappingContext {
2397 int A = 0;
2399 struct SimpleMap {
2400 int B = 0;
2401 int C = 0;
2404 struct NestedMap {
2405 NestedMap(MappingContext &Context) : Context(Context) {}
2406 SimpleMap Simple;
2407 MappingContext &Context;
2410 namespace llvm {
2411 namespace yaml {
2412 template <> struct MappingContextTraits<SimpleMap, MappingContext> {
2413 static void mapping(IO &io, SimpleMap &sm, MappingContext &Context) {
2414 io.mapRequired("B", sm.B);
2415 io.mapRequired("C", sm.C);
2416 ++Context.A;
2417 io.mapRequired("Context", Context.A);
2421 template <> struct MappingTraits<NestedMap> {
2422 static void mapping(IO &io, NestedMap &nm) {
2423 io.mapRequired("Simple", nm.Simple, nm.Context);
2429 TEST(YAMLIO, TestMapWithContext) {
2430 MappingContext Context;
2431 NestedMap Nested(Context);
2432 std::string out;
2433 llvm::raw_string_ostream ostr(out);
2435 Output yout(ostr, nullptr, 15);
2437 yout << Nested;
2438 ostr.flush();
2439 EXPECT_EQ(1, Context.A);
2440 EXPECT_EQ("---\n"
2441 "Simple: \n"
2442 " B: 0\n"
2443 " C: 0\n"
2444 " Context: 1\n"
2445 "...\n",
2446 out);
2448 out.clear();
2450 Nested.Simple.B = 2;
2451 Nested.Simple.C = 3;
2452 yout << Nested;
2453 ostr.flush();
2454 EXPECT_EQ(2, Context.A);
2455 EXPECT_EQ("---\n"
2456 "Simple: \n"
2457 " B: 2\n"
2458 " C: 3\n"
2459 " Context: 2\n"
2460 "...\n",
2461 out);
2462 out.clear();
2465 LLVM_YAML_IS_STRING_MAP(int)
2467 TEST(YAMLIO, TestCustomMapping) {
2468 std::map<std::string, int> x;
2469 x["foo"] = 1;
2470 x["bar"] = 2;
2472 std::string out;
2473 llvm::raw_string_ostream ostr(out);
2474 Output xout(ostr, nullptr, 0);
2476 xout << x;
2477 ostr.flush();
2478 EXPECT_EQ("---\n"
2479 "bar: 2\n"
2480 "foo: 1\n"
2481 "...\n",
2482 out);
2484 Input yin(out);
2485 std::map<std::string, int> y;
2486 yin >> y;
2487 EXPECT_EQ(2ul, y.size());
2488 EXPECT_EQ(1, y["foo"]);
2489 EXPECT_EQ(2, y["bar"]);
2492 LLVM_YAML_IS_STRING_MAP(FooBar)
2494 TEST(YAMLIO, TestCustomMappingStruct) {
2495 std::map<std::string, FooBar> x;
2496 x["foo"].foo = 1;
2497 x["foo"].bar = 2;
2498 x["bar"].foo = 3;
2499 x["bar"].bar = 4;
2501 std::string out;
2502 llvm::raw_string_ostream ostr(out);
2503 Output xout(ostr, nullptr, 0);
2505 xout << x;
2506 ostr.flush();
2507 EXPECT_EQ("---\n"
2508 "bar: \n"
2509 " foo: 3\n"
2510 " bar: 4\n"
2511 "foo: \n"
2512 " foo: 1\n"
2513 " bar: 2\n"
2514 "...\n",
2515 out);
2517 Input yin(out);
2518 std::map<std::string, FooBar> y;
2519 yin >> y;
2520 EXPECT_EQ(2ul, y.size());
2521 EXPECT_EQ(1, y["foo"].foo);
2522 EXPECT_EQ(2, y["foo"].bar);
2523 EXPECT_EQ(3, y["bar"].foo);
2524 EXPECT_EQ(4, y["bar"].bar);
2527 static void TestEscaped(llvm::StringRef Input, llvm::StringRef Expected) {
2528 std::string out;
2529 llvm::raw_string_ostream ostr(out);
2530 Output xout(ostr, nullptr, 0);
2532 llvm::yaml::EmptyContext Ctx;
2533 yamlize(xout, Input, true, Ctx);
2535 ostr.flush();
2537 // Make a separate StringRef so we get nice byte-by-byte output.
2538 llvm::StringRef Got(out);
2539 EXPECT_EQ(Expected, Got);
2542 TEST(YAMLIO, TestEscaped) {
2543 // Single quote
2544 TestEscaped("@abc@", "'@abc@'");
2545 // No quote
2546 TestEscaped("abc", "abc");
2547 // Forward slash quoted
2548 TestEscaped("abc/", "'abc/'");
2549 // Double quote non-printable
2550 TestEscaped("\01@abc@", "\"\\x01@abc@\"");
2551 // Double quote inside single quote
2552 TestEscaped("abc\"fdf", "'abc\"fdf'");
2553 // Double quote inside double quote
2554 TestEscaped("\01bc\"fdf", "\"\\x01bc\\\"fdf\"");
2555 // Single quote inside single quote
2556 TestEscaped("abc'fdf", "'abc''fdf'");
2557 // UTF8
2558 TestEscaped("/*параметр*/", "\"/*параметр*/\"");
2559 // UTF8 with single quote inside double quote
2560 TestEscaped("parameter 'параметр' is unused",
2561 "\"parameter 'параметр' is unused\"");
2563 // String with embedded non-printable multibyte UTF-8 sequence (U+200B
2564 // zero-width space). The thing to test here is that we emit a
2565 // unicode-scalar level escape like \uNNNN (at the YAML level), and don't
2566 // just pass the UTF-8 byte sequence through as with quoted printables.
2568 const unsigned char foobar[10] = {'f', 'o', 'o',
2569 0xE2, 0x80, 0x8B, // UTF-8 of U+200B
2570 'b', 'a', 'r',
2571 0x0};
2572 TestEscaped((char const *)foobar, "\"foo\\u200Bbar\"");
2576 TEST(YAMLIO, Numeric) {
2577 EXPECT_TRUE(isNumeric(".inf"));
2578 EXPECT_TRUE(isNumeric(".INF"));
2579 EXPECT_TRUE(isNumeric(".Inf"));
2580 EXPECT_TRUE(isNumeric("-.inf"));
2581 EXPECT_TRUE(isNumeric("+.inf"));
2583 EXPECT_TRUE(isNumeric(".nan"));
2584 EXPECT_TRUE(isNumeric(".NaN"));
2585 EXPECT_TRUE(isNumeric(".NAN"));
2587 EXPECT_TRUE(isNumeric("0"));
2588 EXPECT_TRUE(isNumeric("0."));
2589 EXPECT_TRUE(isNumeric("0.0"));
2590 EXPECT_TRUE(isNumeric("-0.0"));
2591 EXPECT_TRUE(isNumeric("+0.0"));
2593 EXPECT_TRUE(isNumeric("12345"));
2594 EXPECT_TRUE(isNumeric("012345"));
2595 EXPECT_TRUE(isNumeric("+12.0"));
2596 EXPECT_TRUE(isNumeric(".5"));
2597 EXPECT_TRUE(isNumeric("+.5"));
2598 EXPECT_TRUE(isNumeric("-1.0"));
2600 EXPECT_TRUE(isNumeric("2.3e4"));
2601 EXPECT_TRUE(isNumeric("-2E+05"));
2602 EXPECT_TRUE(isNumeric("+12e03"));
2603 EXPECT_TRUE(isNumeric("6.8523015e+5"));
2605 EXPECT_TRUE(isNumeric("1.e+1"));
2606 EXPECT_TRUE(isNumeric(".0e+1"));
2608 EXPECT_TRUE(isNumeric("0x2aF3"));
2609 EXPECT_TRUE(isNumeric("0o01234567"));
2611 EXPECT_FALSE(isNumeric("not a number"));
2612 EXPECT_FALSE(isNumeric("."));
2613 EXPECT_FALSE(isNumeric(".e+1"));
2614 EXPECT_FALSE(isNumeric(".1e"));
2615 EXPECT_FALSE(isNumeric(".1e+"));
2616 EXPECT_FALSE(isNumeric(".1e++1"));
2618 EXPECT_FALSE(isNumeric("ABCD"));
2619 EXPECT_FALSE(isNumeric("+0x2AF3"));
2620 EXPECT_FALSE(isNumeric("-0x2AF3"));
2621 EXPECT_FALSE(isNumeric("0x2AF3Z"));
2622 EXPECT_FALSE(isNumeric("0o012345678"));
2623 EXPECT_FALSE(isNumeric("0xZ"));
2624 EXPECT_FALSE(isNumeric("-0o012345678"));
2625 EXPECT_FALSE(isNumeric("000003A8229434B839616A25C16B0291F77A438B"));
2627 EXPECT_FALSE(isNumeric(""));
2628 EXPECT_FALSE(isNumeric("."));
2629 EXPECT_FALSE(isNumeric(".e+1"));
2630 EXPECT_FALSE(isNumeric(".e+"));
2631 EXPECT_FALSE(isNumeric(".e"));
2632 EXPECT_FALSE(isNumeric("e1"));
2634 // Deprecated formats: as for YAML 1.2 specification, the following are not
2635 // valid numbers anymore:
2637 // * Sexagecimal numbers
2638 // * Decimal numbers with comma s the delimiter
2639 // * "inf", "nan" without '.' prefix
2640 EXPECT_FALSE(isNumeric("3:25:45"));
2641 EXPECT_FALSE(isNumeric("+12,345"));
2642 EXPECT_FALSE(isNumeric("-inf"));
2643 EXPECT_FALSE(isNumeric("1,230.15"));
2646 //===----------------------------------------------------------------------===//
2647 // Test PolymorphicTraits and TaggedScalarTraits
2648 //===----------------------------------------------------------------------===//
2650 struct Poly {
2651 enum NodeKind {
2652 NK_Scalar,
2653 NK_Seq,
2654 NK_Map,
2655 } Kind;
2657 Poly(NodeKind Kind) : Kind(Kind) {}
2659 virtual ~Poly() = default;
2661 NodeKind getKind() const { return Kind; }
2664 struct Scalar : Poly {
2665 enum ScalarKind {
2666 SK_Unknown,
2667 SK_Double,
2668 SK_Bool,
2669 } SKind;
2671 union {
2672 double DoubleValue;
2673 bool BoolValue;
2676 Scalar() : Poly(NK_Scalar), SKind(SK_Unknown) {}
2677 Scalar(double DoubleValue)
2678 : Poly(NK_Scalar), SKind(SK_Double), DoubleValue(DoubleValue) {}
2679 Scalar(bool BoolValue)
2680 : Poly(NK_Scalar), SKind(SK_Bool), BoolValue(BoolValue) {}
2682 static bool classof(const Poly *N) { return N->getKind() == NK_Scalar; }
2685 struct Seq : Poly, std::vector<std::unique_ptr<Poly>> {
2686 Seq() : Poly(NK_Seq) {}
2688 static bool classof(const Poly *N) { return N->getKind() == NK_Seq; }
2691 struct Map : Poly, llvm::StringMap<std::unique_ptr<Poly>> {
2692 Map() : Poly(NK_Map) {}
2694 static bool classof(const Poly *N) { return N->getKind() == NK_Map; }
2697 namespace llvm {
2698 namespace yaml {
2700 template <> struct PolymorphicTraits<std::unique_ptr<Poly>> {
2701 static NodeKind getKind(const std::unique_ptr<Poly> &N) {
2702 if (isa<Scalar>(*N))
2703 return NodeKind::Scalar;
2704 if (isa<Seq>(*N))
2705 return NodeKind::Sequence;
2706 if (isa<Map>(*N))
2707 return NodeKind::Map;
2708 llvm_unreachable("unsupported node type");
2711 static Scalar &getAsScalar(std::unique_ptr<Poly> &N) {
2712 if (!N || !isa<Scalar>(*N))
2713 N = llvm::make_unique<Scalar>();
2714 return *cast<Scalar>(N.get());
2717 static Seq &getAsSequence(std::unique_ptr<Poly> &N) {
2718 if (!N || !isa<Seq>(*N))
2719 N = llvm::make_unique<Seq>();
2720 return *cast<Seq>(N.get());
2723 static Map &getAsMap(std::unique_ptr<Poly> &N) {
2724 if (!N || !isa<Map>(*N))
2725 N = llvm::make_unique<Map>();
2726 return *cast<Map>(N.get());
2730 template <> struct TaggedScalarTraits<Scalar> {
2731 static void output(const Scalar &S, void *Ctxt, raw_ostream &ScalarOS,
2732 raw_ostream &TagOS) {
2733 switch (S.SKind) {
2734 case Scalar::SK_Unknown:
2735 report_fatal_error("output unknown scalar");
2736 break;
2737 case Scalar::SK_Double:
2738 TagOS << "!double";
2739 ScalarTraits<double>::output(S.DoubleValue, Ctxt, ScalarOS);
2740 break;
2741 case Scalar::SK_Bool:
2742 TagOS << "!bool";
2743 ScalarTraits<bool>::output(S.BoolValue, Ctxt, ScalarOS);
2744 break;
2748 static StringRef input(StringRef ScalarStr, StringRef Tag, void *Ctxt,
2749 Scalar &S) {
2750 S.SKind = StringSwitch<Scalar::ScalarKind>(Tag)
2751 .Case("!double", Scalar::SK_Double)
2752 .Case("!bool", Scalar::SK_Bool)
2753 .Default(Scalar::SK_Unknown);
2754 switch (S.SKind) {
2755 case Scalar::SK_Unknown:
2756 return StringRef("unknown scalar tag");
2757 case Scalar::SK_Double:
2758 return ScalarTraits<double>::input(ScalarStr, Ctxt, S.DoubleValue);
2759 case Scalar::SK_Bool:
2760 return ScalarTraits<bool>::input(ScalarStr, Ctxt, S.BoolValue);
2762 llvm_unreachable("unknown scalar kind");
2765 static QuotingType mustQuote(const Scalar &S, StringRef Str) {
2766 switch (S.SKind) {
2767 case Scalar::SK_Unknown:
2768 report_fatal_error("quote unknown scalar");
2769 case Scalar::SK_Double:
2770 return ScalarTraits<double>::mustQuote(Str);
2771 case Scalar::SK_Bool:
2772 return ScalarTraits<bool>::mustQuote(Str);
2774 llvm_unreachable("unknown scalar kind");
2778 template <> struct CustomMappingTraits<Map> {
2779 static void inputOne(IO &IO, StringRef Key, Map &M) {
2780 IO.mapRequired(Key.str().c_str(), M[Key]);
2783 static void output(IO &IO, Map &M) {
2784 for (auto &N : M)
2785 IO.mapRequired(N.getKey().str().c_str(), N.getValue());
2789 template <> struct SequenceTraits<Seq> {
2790 static size_t size(IO &IO, Seq &A) { return A.size(); }
2792 static std::unique_ptr<Poly> &element(IO &IO, Seq &A, size_t Index) {
2793 if (Index >= A.size())
2794 A.resize(Index + 1);
2795 return A[Index];
2799 } // namespace yaml
2800 } // namespace llvm
2802 TEST(YAMLIO, TestReadWritePolymorphicScalar) {
2803 std::string intermediate;
2804 std::unique_ptr<Poly> node = llvm::make_unique<Scalar>(true);
2806 llvm::raw_string_ostream ostr(intermediate);
2807 Output yout(ostr);
2808 #ifdef GTEST_HAS_DEATH_TEST
2809 #ifndef NDEBUG
2810 EXPECT_DEATH(yout << node, "plain scalar documents are not supported");
2811 #endif
2812 #endif
2815 TEST(YAMLIO, TestReadWritePolymorphicSeq) {
2816 std::string intermediate;
2818 auto seq = llvm::make_unique<Seq>();
2819 seq->push_back(llvm::make_unique<Scalar>(true));
2820 seq->push_back(llvm::make_unique<Scalar>(1.0));
2821 auto node = llvm::unique_dyn_cast<Poly>(seq);
2823 llvm::raw_string_ostream ostr(intermediate);
2824 Output yout(ostr);
2825 yout << node;
2828 Input yin(intermediate);
2829 std::unique_ptr<Poly> node;
2830 yin >> node;
2832 EXPECT_FALSE(yin.error());
2833 auto seq = llvm::dyn_cast<Seq>(node.get());
2834 ASSERT_TRUE(seq);
2835 ASSERT_EQ(seq->size(), 2u);
2836 auto first = llvm::dyn_cast<Scalar>((*seq)[0].get());
2837 ASSERT_TRUE(first);
2838 EXPECT_EQ(first->SKind, Scalar::SK_Bool);
2839 EXPECT_TRUE(first->BoolValue);
2840 auto second = llvm::dyn_cast<Scalar>((*seq)[1].get());
2841 ASSERT_TRUE(second);
2842 EXPECT_EQ(second->SKind, Scalar::SK_Double);
2843 EXPECT_EQ(second->DoubleValue, 1.0);
2847 TEST(YAMLIO, TestReadWritePolymorphicMap) {
2848 std::string intermediate;
2850 auto map = llvm::make_unique<Map>();
2851 (*map)["foo"] = llvm::make_unique<Scalar>(false);
2852 (*map)["bar"] = llvm::make_unique<Scalar>(2.0);
2853 std::unique_ptr<Poly> node = llvm::unique_dyn_cast<Poly>(map);
2855 llvm::raw_string_ostream ostr(intermediate);
2856 Output yout(ostr);
2857 yout << node;
2860 Input yin(intermediate);
2861 std::unique_ptr<Poly> node;
2862 yin >> node;
2864 EXPECT_FALSE(yin.error());
2865 auto map = llvm::dyn_cast<Map>(node.get());
2866 ASSERT_TRUE(map);
2867 auto foo = llvm::dyn_cast<Scalar>((*map)["foo"].get());
2868 ASSERT_TRUE(foo);
2869 EXPECT_EQ(foo->SKind, Scalar::SK_Bool);
2870 EXPECT_FALSE(foo->BoolValue);
2871 auto bar = llvm::dyn_cast<Scalar>((*map)["bar"].get());
2872 ASSERT_TRUE(bar);
2873 EXPECT_EQ(bar->SKind, Scalar::SK_Double);
2874 EXPECT_EQ(bar->DoubleValue, 2.0);