1 //===- llvm/Support/YAMLTraits.h --------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #ifndef LLVM_SUPPORT_YAMLTRAITS_H
10 #define LLVM_SUPPORT_YAMLTRAITS_H
12 #include "llvm/ADT/Optional.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/StringExtras.h"
15 #include "llvm/ADT/StringMap.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/Support/AlignOf.h"
19 #include "llvm/Support/Allocator.h"
20 #include "llvm/Support/Endian.h"
21 #include "llvm/Support/Regex.h"
22 #include "llvm/Support/SourceMgr.h"
23 #include "llvm/Support/YAMLParser.h"
24 #include "llvm/Support/raw_ostream.h"
34 #include <system_error>
35 #include <type_traits>
41 enum class NodeKind
: uint8_t {
47 struct EmptyContext
{};
49 /// This class should be specialized by any type that needs to be converted
50 /// to/from a YAML mapping. For example:
52 /// struct MappingTraits<MyStruct> {
53 /// static void mapping(IO &io, MyStruct &s) {
54 /// io.mapRequired("name", s.name);
55 /// io.mapRequired("size", s.size);
56 /// io.mapOptional("age", s.age);
60 struct MappingTraits
{
62 // static void mapping(IO &io, T &fields);
63 // Optionally may provide:
64 // static StringRef validate(IO &io, T &fields);
66 // The optional flow flag will cause generated YAML to use a flow mapping
67 // (e.g. { a: 0, b: 1 }):
68 // static const bool flow = true;
71 /// This class is similar to MappingTraits<T> but allows you to pass in
72 /// additional context for each map operation. For example:
74 /// struct MappingContextTraits<MyStruct, MyContext> {
75 /// static void mapping(IO &io, MyStruct &s, MyContext &c) {
76 /// io.mapRequired("name", s.name);
77 /// io.mapRequired("size", s.size);
78 /// io.mapOptional("age", s.age);
82 template <class T
, class Context
> struct MappingContextTraits
{
84 // static void mapping(IO &io, T &fields, Context &Ctx);
85 // Optionally may provide:
86 // static StringRef validate(IO &io, T &fields, Context &Ctx);
88 // The optional flow flag will cause generated YAML to use a flow mapping
89 // (e.g. { a: 0, b: 1 }):
90 // static const bool flow = true;
93 /// This class should be specialized by any integral type that converts
94 /// to/from a YAML scalar where there is a one-to-one mapping between
95 /// in-memory values and a string in YAML. For example:
97 /// struct ScalarEnumerationTraits<Colors> {
98 /// static void enumeration(IO &io, Colors &value) {
99 /// io.enumCase(value, "red", cRed);
100 /// io.enumCase(value, "blue", cBlue);
101 /// io.enumCase(value, "green", cGreen);
105 struct ScalarEnumerationTraits
{
107 // static void enumeration(IO &io, T &value);
110 /// This class should be specialized by any integer type that is a union
111 /// of bit values and the YAML representation is a flow sequence of
112 /// strings. For example:
114 /// struct ScalarBitSetTraits<MyFlags> {
115 /// static void bitset(IO &io, MyFlags &value) {
116 /// io.bitSetCase(value, "big", flagBig);
117 /// io.bitSetCase(value, "flat", flagFlat);
118 /// io.bitSetCase(value, "round", flagRound);
122 struct ScalarBitSetTraits
{
124 // static void bitset(IO &io, T &value);
127 /// Describe which type of quotes should be used when quoting is necessary.
128 /// Some non-printable characters need to be double-quoted, while some others
129 /// are fine with simple-quoting, and some don't need any quoting.
130 enum class QuotingType
{ None
, Single
, Double
};
132 /// This class should be specialized by type that requires custom conversion
133 /// to/from a yaml scalar. For example:
136 /// struct ScalarTraits<MyType> {
137 /// static void output(const MyType &val, void*, llvm::raw_ostream &out) {
138 /// // stream out custom formatting
139 /// out << llvm::format("%x", val);
141 /// static StringRef input(StringRef scalar, void*, MyType &value) {
142 /// // parse scalar and set `value`
143 /// // return empty string on success, or error string
144 /// return StringRef();
146 /// static QuotingType mustQuote(StringRef) { return QuotingType::Single; }
149 struct ScalarTraits
{
152 // Function to write the value as a string:
153 // static void output(const T &value, void *ctxt, llvm::raw_ostream &out);
155 // Function to convert a string to a value. Returns the empty
156 // StringRef on success or an error string if string is malformed:
157 // static StringRef input(StringRef scalar, void *ctxt, T &value);
159 // Function to determine if the value should be quoted.
160 // static QuotingType mustQuote(StringRef);
163 /// This class should be specialized by type that requires custom conversion
164 /// to/from a YAML literal block scalar. For example:
167 /// struct BlockScalarTraits<MyType> {
168 /// static void output(const MyType &Value, void*, llvm::raw_ostream &Out)
170 /// // stream out custom formatting
173 /// static StringRef input(StringRef Scalar, void*, MyType &Value) {
174 /// // parse scalar and set `value`
175 /// // return empty string on success, or error string
176 /// return StringRef();
179 template <typename T
>
180 struct BlockScalarTraits
{
183 // Function to write the value as a string:
184 // static void output(const T &Value, void *ctx, llvm::raw_ostream &Out);
186 // Function to convert a string to a value. Returns the empty
187 // StringRef on success or an error string if string is malformed:
188 // static StringRef input(StringRef Scalar, void *ctxt, T &Value);
191 // static StringRef inputTag(T &Val, std::string Tag)
192 // static void outputTag(const T &Val, raw_ostream &Out)
195 /// This class should be specialized by type that requires custom conversion
196 /// to/from a YAML scalar with optional tags. For example:
199 /// struct TaggedScalarTraits<MyType> {
200 /// static void output(const MyType &Value, void*, llvm::raw_ostream
201 /// &ScalarOut, llvm::raw_ostream &TagOut)
203 /// // stream out custom formatting including optional Tag
206 /// static StringRef input(StringRef Scalar, StringRef Tag, void*, MyType
208 /// // parse scalar and set `value`
209 /// // return empty string on success, or error string
210 /// return StringRef();
212 /// static QuotingType mustQuote(const MyType &Value, StringRef) {
213 /// return QuotingType::Single;
216 template <typename T
> struct TaggedScalarTraits
{
219 // Function to write the value and tag as strings:
220 // static void output(const T &Value, void *ctx, llvm::raw_ostream &ScalarOut,
221 // llvm::raw_ostream &TagOut);
223 // Function to convert a string to a value. Returns the empty
224 // StringRef on success or an error string if string is malformed:
225 // static StringRef input(StringRef Scalar, StringRef Tag, void *ctxt, T
228 // Function to determine if the value should be quoted.
229 // static QuotingType mustQuote(const T &Value, StringRef Scalar);
232 /// This class should be specialized by any type that needs to be converted
233 /// to/from a YAML sequence. For example:
236 /// struct SequenceTraits<MyContainer> {
237 /// static size_t size(IO &io, MyContainer &seq) {
238 /// return seq.size();
240 /// static MyType& element(IO &, MyContainer &seq, size_t index) {
241 /// if ( index >= seq.size() )
242 /// seq.resize(index+1);
243 /// return seq[index];
246 template<typename T
, typename EnableIf
= void>
247 struct SequenceTraits
{
249 // static size_t size(IO &io, T &seq);
250 // static T::value_type& element(IO &io, T &seq, size_t index);
252 // The following is option and will cause generated YAML to use
253 // a flow sequence (e.g. [a,b,c]).
254 // static const bool flow = true;
257 /// This class should be specialized by any type for which vectors of that
258 /// type need to be converted to/from a YAML sequence.
259 template<typename T
, typename EnableIf
= void>
260 struct SequenceElementTraits
{
262 // static const bool flow;
265 /// This class should be specialized by any type that needs to be converted
266 /// to/from a list of YAML documents.
268 struct DocumentListTraits
{
270 // static size_t size(IO &io, T &seq);
271 // static T::value_type& element(IO &io, T &seq, size_t index);
274 /// This class should be specialized by any type that needs to be converted
275 /// to/from a YAML mapping in the case where the names of the keys are not known
276 /// in advance, e.g. a string map.
277 template <typename T
>
278 struct CustomMappingTraits
{
279 // static void inputOne(IO &io, StringRef key, T &elem);
280 // static void output(IO &io, T &elem);
283 /// This class should be specialized by any type that can be represented as
284 /// a scalar, map, or sequence, decided dynamically. For example:
286 /// typedef std::unique_ptr<MyBase> MyPoly;
289 /// struct PolymorphicTraits<MyPoly> {
290 /// static NodeKind getKind(const MyPoly &poly) {
291 /// return poly->getKind();
293 /// static MyScalar& getAsScalar(MyPoly &poly) {
294 /// if (!poly || !isa<MyScalar>(poly))
295 /// poly.reset(new MyScalar());
296 /// return *cast<MyScalar>(poly.get());
300 template <typename T
> struct PolymorphicTraits
{
302 // static NodeKind getKind(const T &poly);
303 // static scalar_type &getAsScalar(T &poly);
304 // static map_type &getAsMap(T &poly);
305 // static sequence_type &getAsSequence(T &poly);
308 // Only used for better diagnostics of missing traits
309 template <typename T
>
312 // Test if ScalarEnumerationTraits<T> is defined on type T.
314 struct has_ScalarEnumerationTraits
316 using Signature_enumeration
= void (*)(class IO
&, T
&);
318 template <typename U
>
319 static char test(SameType
<Signature_enumeration
, &U::enumeration
>*);
321 template <typename U
>
322 static double test(...);
324 static bool const value
=
325 (sizeof(test
<ScalarEnumerationTraits
<T
>>(nullptr)) == 1);
328 // Test if ScalarBitSetTraits<T> is defined on type T.
330 struct has_ScalarBitSetTraits
332 using Signature_bitset
= void (*)(class IO
&, T
&);
334 template <typename U
>
335 static char test(SameType
<Signature_bitset
, &U::bitset
>*);
337 template <typename U
>
338 static double test(...);
340 static bool const value
= (sizeof(test
<ScalarBitSetTraits
<T
>>(nullptr)) == 1);
343 // Test if ScalarTraits<T> is defined on type T.
345 struct has_ScalarTraits
347 using Signature_input
= StringRef (*)(StringRef
, void*, T
&);
348 using Signature_output
= void (*)(const T
&, void*, raw_ostream
&);
349 using Signature_mustQuote
= QuotingType (*)(StringRef
);
351 template <typename U
>
352 static char test(SameType
<Signature_input
, &U::input
> *,
353 SameType
<Signature_output
, &U::output
> *,
354 SameType
<Signature_mustQuote
, &U::mustQuote
> *);
356 template <typename U
>
357 static double test(...);
359 static bool const value
=
360 (sizeof(test
<ScalarTraits
<T
>>(nullptr, nullptr, nullptr)) == 1);
363 // Test if BlockScalarTraits<T> is defined on type T.
365 struct has_BlockScalarTraits
367 using Signature_input
= StringRef (*)(StringRef
, void *, T
&);
368 using Signature_output
= void (*)(const T
&, void *, raw_ostream
&);
370 template <typename U
>
371 static char test(SameType
<Signature_input
, &U::input
> *,
372 SameType
<Signature_output
, &U::output
> *);
374 template <typename U
>
375 static double test(...);
377 static bool const value
=
378 (sizeof(test
<BlockScalarTraits
<T
>>(nullptr, nullptr)) == 1);
381 // Test if TaggedScalarTraits<T> is defined on type T.
382 template <class T
> struct has_TaggedScalarTraits
{
383 using Signature_input
= StringRef (*)(StringRef
, StringRef
, void *, T
&);
384 using Signature_output
= void (*)(const T
&, void *, raw_ostream
&,
386 using Signature_mustQuote
= QuotingType (*)(const T
&, StringRef
);
388 template <typename U
>
389 static char test(SameType
<Signature_input
, &U::input
> *,
390 SameType
<Signature_output
, &U::output
> *,
391 SameType
<Signature_mustQuote
, &U::mustQuote
> *);
393 template <typename U
> static double test(...);
395 static bool const value
=
396 (sizeof(test
<TaggedScalarTraits
<T
>>(nullptr, nullptr, nullptr)) == 1);
399 // Test if MappingContextTraits<T> is defined on type T.
400 template <class T
, class Context
> struct has_MappingTraits
{
401 using Signature_mapping
= void (*)(class IO
&, T
&, Context
&);
403 template <typename U
>
404 static char test(SameType
<Signature_mapping
, &U::mapping
>*);
406 template <typename U
>
407 static double test(...);
409 static bool const value
=
410 (sizeof(test
<MappingContextTraits
<T
, Context
>>(nullptr)) == 1);
413 // Test if MappingTraits<T> is defined on type T.
414 template <class T
> struct has_MappingTraits
<T
, EmptyContext
> {
415 using Signature_mapping
= void (*)(class IO
&, T
&);
417 template <typename U
>
418 static char test(SameType
<Signature_mapping
, &U::mapping
> *);
420 template <typename U
> static double test(...);
422 static bool const value
= (sizeof(test
<MappingTraits
<T
>>(nullptr)) == 1);
425 // Test if MappingContextTraits<T>::validate() is defined on type T.
426 template <class T
, class Context
> struct has_MappingValidateTraits
{
427 using Signature_validate
= StringRef (*)(class IO
&, T
&, Context
&);
429 template <typename U
>
430 static char test(SameType
<Signature_validate
, &U::validate
>*);
432 template <typename U
>
433 static double test(...);
435 static bool const value
=
436 (sizeof(test
<MappingContextTraits
<T
, Context
>>(nullptr)) == 1);
439 // Test if MappingTraits<T>::validate() is defined on type T.
440 template <class T
> struct has_MappingValidateTraits
<T
, EmptyContext
> {
441 using Signature_validate
= StringRef (*)(class IO
&, T
&);
443 template <typename U
>
444 static char test(SameType
<Signature_validate
, &U::validate
> *);
446 template <typename U
> static double test(...);
448 static bool const value
= (sizeof(test
<MappingTraits
<T
>>(nullptr)) == 1);
451 // Test if SequenceTraits<T> is defined on type T.
453 struct has_SequenceMethodTraits
455 using Signature_size
= size_t (*)(class IO
&, T
&);
457 template <typename U
>
458 static char test(SameType
<Signature_size
, &U::size
>*);
460 template <typename U
>
461 static double test(...);
463 static bool const value
= (sizeof(test
<SequenceTraits
<T
>>(nullptr)) == 1);
466 // Test if CustomMappingTraits<T> is defined on type T.
468 struct has_CustomMappingTraits
470 using Signature_input
= void (*)(IO
&io
, StringRef key
, T
&v
);
472 template <typename U
>
473 static char test(SameType
<Signature_input
, &U::inputOne
>*);
475 template <typename U
>
476 static double test(...);
478 static bool const value
=
479 (sizeof(test
<CustomMappingTraits
<T
>>(nullptr)) == 1);
482 // has_FlowTraits<int> will cause an error with some compilers because
483 // it subclasses int. Using this wrapper only instantiates the
484 // real has_FlowTraits only if the template type is a class.
485 template <typename T
, bool Enabled
= std::is_class
<T
>::value
>
489 static const bool value
= false;
492 // Some older gcc compilers don't support straight forward tests
493 // for members, so test for ambiguity cause by the base and derived
494 // classes both defining the member.
496 struct has_FlowTraits
<T
, true>
498 struct Fallback
{ bool flow
; };
499 struct Derived
: T
, Fallback
{ };
502 static char (&f(SameType
<bool Fallback::*, &C::flow
>*))[1];
505 static char (&f(...))[2];
507 static bool const value
= sizeof(f
<Derived
>(nullptr)) == 2;
510 // Test if SequenceTraits<T> is defined on type T
512 struct has_SequenceTraits
: public std::integral_constant
<bool,
513 has_SequenceMethodTraits
<T
>::value
> { };
515 // Test if DocumentListTraits<T> is defined on type T
517 struct has_DocumentListTraits
519 using Signature_size
= size_t (*)(class IO
&, T
&);
521 template <typename U
>
522 static char test(SameType
<Signature_size
, &U::size
>*);
524 template <typename U
>
525 static double test(...);
527 static bool const value
= (sizeof(test
<DocumentListTraits
<T
>>(nullptr))==1);
530 template <class T
> struct has_PolymorphicTraits
{
531 using Signature_getKind
= NodeKind (*)(const T
&);
533 template <typename U
>
534 static char test(SameType
<Signature_getKind
, &U::getKind
> *);
536 template <typename U
> static double test(...);
538 static bool const value
= (sizeof(test
<PolymorphicTraits
<T
>>(nullptr)) == 1);
541 inline bool isNumeric(StringRef S
) {
542 const static auto skipDigits
= [](StringRef Input
) {
543 return Input
.drop_front(
544 std::min(Input
.find_first_not_of("0123456789"), Input
.size()));
547 // Make S.front() and S.drop_front().front() (if S.front() is [+-]) calls
549 if (S
.empty() || S
.equals("+") || S
.equals("-"))
552 if (S
.equals(".nan") || S
.equals(".NaN") || S
.equals(".NAN"))
555 // Infinity and decimal numbers can be prefixed with sign.
556 StringRef Tail
= (S
.front() == '-' || S
.front() == '+') ? S
.drop_front() : S
;
558 // Check for infinity first, because checking for hex and oct numbers is more
560 if (Tail
.equals(".inf") || Tail
.equals(".Inf") || Tail
.equals(".INF"))
563 // Section 10.3.2 Tag Resolution
564 // YAML 1.2 Specification prohibits Base 8 and Base 16 numbers prefixed with
565 // [-+], so S should be used instead of Tail.
566 if (S
.startswith("0o"))
567 return S
.size() > 2 &&
568 S
.drop_front(2).find_first_not_of("01234567") == StringRef::npos
;
570 if (S
.startswith("0x"))
571 return S
.size() > 2 && S
.drop_front(2).find_first_not_of(
572 "0123456789abcdefABCDEF") == StringRef::npos
;
574 // Parse float: [-+]? (\. [0-9]+ | [0-9]+ (\. [0-9]* )?) ([eE] [-+]? [0-9]+)?
577 // Handle cases when the number starts with '.' and hence needs at least one
578 // digit after dot (as opposed by number which has digits before the dot), but
580 if (S
.startswith(".") &&
582 (S
.size() > 1 && std::strchr("0123456789", S
[1]) == nullptr)))
585 if (S
.startswith("E") || S
.startswith("e"))
593 ParseState State
= Default
;
597 // Accept decimal integer.
601 if (S
.front() == '.') {
604 } else if (S
.front() == 'e' || S
.front() == 'E') {
605 State
= FoundExponent
;
611 if (State
== FoundDot
) {
616 if (S
.front() == 'e' || S
.front() == 'E') {
617 State
= FoundExponent
;
624 assert(State
== FoundExponent
&& "Should have found exponent at this point.");
628 if (S
.front() == '+' || S
.front() == '-') {
634 return skipDigits(S
).empty();
637 inline bool isNull(StringRef S
) {
638 return S
.equals("null") || S
.equals("Null") || S
.equals("NULL") ||
642 inline bool isBool(StringRef S
) {
643 return S
.equals("true") || S
.equals("True") || S
.equals("TRUE") ||
644 S
.equals("false") || S
.equals("False") || S
.equals("FALSE");
647 // 5.1. Character Set
648 // The allowed character range explicitly excludes the C0 control block #x0-#x1F
649 // (except for TAB #x9, LF #xA, and CR #xD which are allowed), DEL #x7F, the C1
650 // control block #x80-#x9F (except for NEL #x85 which is allowed), the surrogate
651 // block #xD800-#xDFFF, #xFFFE, and #xFFFF.
652 inline QuotingType
needsQuotes(StringRef S
) {
654 return QuotingType::Single
;
655 if (isspace(S
.front()) || isspace(S
.back()))
656 return QuotingType::Single
;
658 return QuotingType::Single
;
660 return QuotingType::Single
;
662 return QuotingType::Single
;
665 // Plain scalars must not begin with most indicators, as this would cause
666 // ambiguity with other YAML constructs.
667 static constexpr char Indicators
[] = R
"(-?:\,[]{}#&*!|>'"%@`
)";
668 if (S.find_first_of(Indicators) == 0)
669 return QuotingType::Single;
671 QuotingType MaxQuotingNeeded = QuotingType::None;
672 for (unsigned char C : S) {
678 // Safe scalar characters.
685 // TAB (0x9) is allowed in unquoted strings.
688 // LF(0xA) and CR(0xD) may delimit values and so require at least single
692 MaxQuotingNeeded = QuotingType::Single;
694 // DEL (0x7F) are excluded from the allowed character range.
696 return QuotingType::Double;
697 // Forward slash is allowed to be unquoted, but we quote it anyway. We have
698 // many tests that use FileCheck against YAML output, and this output often
699 // contains paths. If we quote backslashes but not forward slashes then
700 // paths will come out either quoted or unquoted depending on which platform
701 // the test is run on, making FileCheck comparisons difficult.
704 // C0 control block (0x0 - 0x1F) is excluded from the allowed character
707 return QuotingType::Double;
709 // Always double quote UTF-8.
711 return QuotingType::Double;
713 // The character is not safe, at least simple quoting needed.
714 MaxQuotingNeeded = QuotingType::Single;
719 return MaxQuotingNeeded;
722 template <typename T, typename Context>
724 : public std::integral_constant<bool,
725 !has_ScalarEnumerationTraits<T>::value &&
726 !has_ScalarBitSetTraits<T>::value &&
727 !has_ScalarTraits<T>::value &&
728 !has_BlockScalarTraits<T>::value &&
729 !has_TaggedScalarTraits<T>::value &&
730 !has_MappingTraits<T, Context>::value &&
731 !has_SequenceTraits<T>::value &&
732 !has_CustomMappingTraits<T>::value &&
733 !has_DocumentListTraits<T>::value &&
734 !has_PolymorphicTraits<T>::value> {};
736 template <typename T, typename Context>
737 struct validatedMappingTraits
738 : public std::integral_constant<
739 bool, has_MappingTraits<T, Context>::value &&
740 has_MappingValidateTraits<T, Context>::value> {};
742 template <typename T, typename Context>
743 struct unvalidatedMappingTraits
744 : public std::integral_constant<
745 bool, has_MappingTraits<T, Context>::value &&
746 !has_MappingValidateTraits<T, Context>::value> {};
748 // Base class for Input and Output.
751 IO(void *Ctxt = nullptr);
754 virtual bool outputting() = 0;
756 virtual unsigned beginSequence() = 0;
757 virtual bool preflightElement(unsigned, void *&) = 0;
758 virtual void postflightElement(void*) = 0;
759 virtual void endSequence() = 0;
760 virtual bool canElideEmptySequence() = 0;
762 virtual unsigned beginFlowSequence() = 0;
763 virtual bool preflightFlowElement(unsigned, void *&) = 0;
764 virtual void postflightFlowElement(void*) = 0;
765 virtual void endFlowSequence() = 0;
767 virtual bool mapTag(StringRef Tag, bool Default=false) = 0;
768 virtual void beginMapping() = 0;
769 virtual void endMapping() = 0;
770 virtual bool preflightKey(const char*, bool, bool, bool &, void *&) = 0;
771 virtual void postflightKey(void*) = 0;
772 virtual std::vector<StringRef> keys() = 0;
774 virtual void beginFlowMapping() = 0;
775 virtual void endFlowMapping() = 0;
777 virtual void beginEnumScalar() = 0;
778 virtual bool matchEnumScalar(const char*, bool) = 0;
779 virtual bool matchEnumFallback() = 0;
780 virtual void endEnumScalar() = 0;
782 virtual bool beginBitSetScalar(bool &) = 0;
783 virtual bool bitSetMatch(const char*, bool) = 0;
784 virtual void endBitSetScalar() = 0;
786 virtual void scalarString(StringRef &, QuotingType) = 0;
787 virtual void blockScalarString(StringRef &) = 0;
788 virtual void scalarTag(std::string &) = 0;
790 virtual NodeKind getNodeKind() = 0;
792 virtual void setError(const Twine &) = 0;
794 template <typename T>
795 void enumCase(T &Val, const char* Str, const T ConstVal) {
796 if ( matchEnumScalar(Str, outputting() && Val == ConstVal) ) {
801 // allow anonymous enum values to be used with LLVM_YAML_STRONG_TYPEDEF
802 template <typename T>
803 void enumCase(T &Val, const char* Str, const uint32_t ConstVal) {
804 if ( matchEnumScalar(Str, outputting() && Val == static_cast<T>(ConstVal)) ) {
809 template <typename FBT, typename T>
810 void enumFallback(T &Val) {
811 if (matchEnumFallback()) {
812 EmptyContext Context;
813 // FIXME: Force integral conversion to allow strong typedefs to convert.
814 FBT Res = static_cast<typename FBT::BaseType>(Val);
815 yamlize(*this, Res, true, Context);
816 Val = static_cast<T>(static_cast<typename FBT::BaseType>(Res));
820 template <typename T>
821 void bitSetCase(T &Val, const char* Str, const T ConstVal) {
822 if ( bitSetMatch(Str, outputting() && (Val & ConstVal) == ConstVal) ) {
823 Val = static_cast<T>(Val | ConstVal);
827 // allow anonymous enum values to be used with LLVM_YAML_STRONG_TYPEDEF
828 template <typename T>
829 void bitSetCase(T &Val, const char* Str, const uint32_t ConstVal) {
830 if ( bitSetMatch(Str, outputting() && (Val & ConstVal) == ConstVal) ) {
831 Val = static_cast<T>(Val | ConstVal);
835 template <typename T>
836 void maskedBitSetCase(T &Val, const char *Str, T ConstVal, T Mask) {
837 if (bitSetMatch(Str, outputting() && (Val & Mask) == ConstVal))
838 Val = Val | ConstVal;
841 template <typename T>
842 void maskedBitSetCase(T &Val, const char *Str, uint32_t ConstVal,
844 if (bitSetMatch(Str, outputting() && (Val & Mask) == ConstVal))
845 Val = Val | ConstVal;
849 void setContext(void *);
851 template <typename T> void mapRequired(const char *Key, T &Val) {
853 this->processKey(Key, Val, true, Ctx);
856 template <typename T, typename Context>
857 void mapRequired(const char *Key, T &Val, Context &Ctx) {
858 this->processKey(Key, Val, true, Ctx);
861 template <typename T> void mapOptional(const char *Key, T &Val) {
863 mapOptionalWithContext(Key, Val, Ctx);
866 template <typename T>
867 void mapOptional(const char *Key, T &Val, const T &Default) {
869 mapOptionalWithContext(Key, Val, Default, Ctx);
872 template <typename T, typename Context>
873 typename std::enable_if<has_SequenceTraits<T>::value, void>::type
874 mapOptionalWithContext(const char *Key, T &Val, Context &Ctx) {
875 // omit key/value instead of outputting empty sequence
876 if (this->canElideEmptySequence() && !(Val.begin() != Val.end()))
878 this->processKey(Key, Val, false, Ctx);
881 template <typename T, typename Context>
882 void mapOptionalWithContext(const char *Key, Optional<T> &Val, Context &Ctx) {
883 this->processKeyWithDefault(Key, Val, Optional<T>(), /*Required=*/false,
887 template <typename T, typename Context>
888 typename std::enable_if<!has_SequenceTraits<T>::value, void>::type
889 mapOptionalWithContext(const char *Key, T &Val, Context &Ctx) {
890 this->processKey(Key, Val, false, Ctx);
893 template <typename T, typename Context>
894 void mapOptionalWithContext(const char *Key, T &Val, const T &Default,
896 this->processKeyWithDefault(Key, Val, Default, false, Ctx);
900 template <typename T, typename Context>
901 void processKeyWithDefault(const char *Key, Optional<T> &Val,
902 const Optional<T> &DefaultValue, bool Required,
904 assert(DefaultValue.hasValue() == false &&
905 "Optional
<T
> shouldn
't have a value!");
907 bool UseDefault = true;
908 const bool sameAsDefault = outputting() && !Val.hasValue();
909 if (!outputting() && !Val.hasValue())
911 if (Val.hasValue() &&
912 this->preflightKey(Key, Required, sameAsDefault, UseDefault,
914 yamlize(*this, Val.getValue(), Required, Ctx);
915 this->postflightKey(SaveInfo);
922 template <typename T, typename Context>
923 void processKeyWithDefault(const char *Key, T &Val, const T &DefaultValue,
924 bool Required, Context &Ctx) {
927 const bool sameAsDefault = outputting() && Val == DefaultValue;
928 if ( this->preflightKey(Key, Required, sameAsDefault, UseDefault,
930 yamlize(*this, Val, Required, Ctx);
931 this->postflightKey(SaveInfo);
939 template <typename T, typename Context>
940 void processKey(const char *Key, T &Val, bool Required, Context &Ctx) {
943 if ( this->preflightKey(Key, Required, false, UseDefault, SaveInfo) ) {
944 yamlize(*this, Val, Required, Ctx);
945 this->postflightKey(SaveInfo);
955 template <typename T, typename Context>
956 void doMapping(IO &io, T &Val, Context &Ctx) {
957 MappingContextTraits<T, Context>::mapping(io, Val, Ctx);
960 template <typename T> void doMapping(IO &io, T &Val, EmptyContext &Ctx) {
961 MappingTraits<T>::mapping(io, Val);
964 } // end namespace detail
966 template <typename T>
967 typename std::enable_if<has_ScalarEnumerationTraits<T>::value, void>::type
968 yamlize(IO &io, T &Val, bool, EmptyContext &Ctx) {
969 io.beginEnumScalar();
970 ScalarEnumerationTraits<T>::enumeration(io, Val);
974 template <typename T>
975 typename std::enable_if<has_ScalarBitSetTraits<T>::value, void>::type
976 yamlize(IO &io, T &Val, bool, EmptyContext &Ctx) {
978 if ( io.beginBitSetScalar(DoClear) ) {
980 Val = static_cast<T>(0);
981 ScalarBitSetTraits<T>::bitset(io, Val);
982 io.endBitSetScalar();
986 template <typename T>
987 typename std::enable_if<has_ScalarTraits<T>::value, void>::type
988 yamlize(IO &io, T &Val, bool, EmptyContext &Ctx) {
989 if ( io.outputting() ) {
991 raw_string_ostream Buffer(Storage);
992 ScalarTraits<T>::output(Val, io.getContext(), Buffer);
993 StringRef Str = Buffer.str();
994 io.scalarString(Str, ScalarTraits<T>::mustQuote(Str));
998 io.scalarString(Str, ScalarTraits<T>::mustQuote(Str));
999 StringRef Result = ScalarTraits<T>::input(Str, io.getContext(), Val);
1000 if ( !Result.empty() ) {
1001 io.setError(Twine(Result));
1006 template <typename T>
1007 typename std::enable_if<has_BlockScalarTraits<T>::value, void>::type
1008 yamlize(IO &YamlIO, T &Val, bool, EmptyContext &Ctx) {
1009 if (YamlIO.outputting()) {
1010 std::string Storage;
1011 raw_string_ostream Buffer(Storage);
1012 BlockScalarTraits<T>::output(Val, YamlIO.getContext(), Buffer);
1013 StringRef Str = Buffer.str();
1014 YamlIO.blockScalarString(Str);
1017 YamlIO.blockScalarString(Str);
1019 BlockScalarTraits<T>::input(Str, YamlIO.getContext(), Val);
1020 if (!Result.empty())
1021 YamlIO.setError(Twine(Result));
1025 template <typename T>
1026 typename std::enable_if<has_TaggedScalarTraits<T>::value, void>::type
1027 yamlize(IO &io, T &Val, bool, EmptyContext &Ctx) {
1028 if (io.outputting()) {
1029 std::string ScalarStorage, TagStorage;
1030 raw_string_ostream ScalarBuffer(ScalarStorage), TagBuffer(TagStorage);
1031 TaggedScalarTraits<T>::output(Val, io.getContext(), ScalarBuffer,
1033 io.scalarTag(TagBuffer.str());
1034 StringRef ScalarStr = ScalarBuffer.str();
1035 io.scalarString(ScalarStr,
1036 TaggedScalarTraits<T>::mustQuote(Val, ScalarStr));
1041 io.scalarString(Str, QuotingType::None);
1043 TaggedScalarTraits<T>::input(Str, Tag, io.getContext(), Val);
1044 if (!Result.empty()) {
1045 io.setError(Twine(Result));
1050 template <typename T, typename Context>
1051 typename std::enable_if<validatedMappingTraits<T, Context>::value, void>::type
1052 yamlize(IO &io, T &Val, bool, Context &Ctx) {
1053 if (has_FlowTraits<MappingTraits<T>>::value)
1054 io.beginFlowMapping();
1057 if (io.outputting()) {
1058 StringRef Err = MappingTraits<T>::validate(io, Val);
1060 errs() << Err << "\n";
1061 assert(Err.empty() && "invalid struct trying to be written as yaml");
1064 detail::doMapping(io, Val, Ctx);
1065 if (!io.outputting()) {
1066 StringRef Err = MappingTraits<T>::validate(io, Val);
1070 if (has_FlowTraits<MappingTraits<T>>::value)
1071 io.endFlowMapping();
1076 template <typename T, typename Context>
1077 typename std::enable_if<unvalidatedMappingTraits<T, Context>::value, void>::type
1078 yamlize(IO &io, T &Val, bool, Context &Ctx) {
1079 if (has_FlowTraits<MappingTraits<T>>::value) {
1080 io.beginFlowMapping();
1081 detail::doMapping(io, Val, Ctx);
1082 io.endFlowMapping();
1085 detail::doMapping(io, Val, Ctx);
1090 template <typename T>
1091 typename std::enable_if<has_CustomMappingTraits<T>::value, void>::type
1092 yamlize(IO &io, T &Val, bool, EmptyContext &Ctx) {
1093 if ( io.outputting() ) {
1095 CustomMappingTraits<T>::output(io, Val);
1099 for (StringRef key : io.keys())
1100 CustomMappingTraits<T>::inputOne(io, key, Val);
1105 template <typename T>
1106 typename std::enable_if<has_PolymorphicTraits<T>::value, void>::type
1107 yamlize(IO &io, T &Val, bool, EmptyContext &Ctx) {
1108 switch (io.outputting() ? PolymorphicTraits<T>::getKind(Val)
1109 : io.getNodeKind()) {
1110 case NodeKind::Scalar:
1111 return yamlize(io, PolymorphicTraits<T>::getAsScalar(Val), true, Ctx);
1113 return yamlize(io, PolymorphicTraits<T>::getAsMap(Val), true, Ctx);
1114 case NodeKind::Sequence:
1115 return yamlize(io, PolymorphicTraits<T>::getAsSequence(Val), true, Ctx);
1119 template <typename T>
1120 typename std::enable_if<missingTraits<T, EmptyContext>::value, void>::type
1121 yamlize(IO &io, T &Val, bool, EmptyContext &Ctx) {
1122 char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
1125 template <typename T, typename Context>
1126 typename std::enable_if<has_SequenceTraits<T>::value, void>::type
1127 yamlize(IO &io, T &Seq, bool, Context &Ctx) {
1128 if ( has_FlowTraits< SequenceTraits<T>>::value ) {
1129 unsigned incnt = io.beginFlowSequence();
1130 unsigned count = io.outputting() ? SequenceTraits<T>::size(io, Seq) : incnt;
1131 for(unsigned i=0; i < count; ++i) {
1133 if ( io.preflightFlowElement(i, SaveInfo) ) {
1134 yamlize(io, SequenceTraits<T>::element(io, Seq, i), true, Ctx);
1135 io.postflightFlowElement(SaveInfo);
1138 io.endFlowSequence();
1141 unsigned incnt = io.beginSequence();
1142 unsigned count = io.outputting() ? SequenceTraits<T>::size(io, Seq) : incnt;
1143 for(unsigned i=0; i < count; ++i) {
1145 if ( io.preflightElement(i, SaveInfo) ) {
1146 yamlize(io, SequenceTraits<T>::element(io, Seq, i), true, Ctx);
1147 io.postflightElement(SaveInfo);
1155 struct ScalarTraits<bool> {
1156 static void output(const bool &, void* , raw_ostream &);
1157 static StringRef input(StringRef, void *, bool &);
1158 static QuotingType mustQuote(StringRef) { return QuotingType::None; }
1162 struct ScalarTraits<StringRef> {
1163 static void output(const StringRef &, void *, raw_ostream &);
1164 static StringRef input(StringRef, void *, StringRef &);
1165 static QuotingType mustQuote(StringRef S) { return needsQuotes(S); }
1169 struct ScalarTraits<std::string> {
1170 static void output(const std::string &, void *, raw_ostream &);
1171 static StringRef input(StringRef, void *, std::string &);
1172 static QuotingType mustQuote(StringRef S) { return needsQuotes(S); }
1176 struct ScalarTraits<uint8_t> {
1177 static void output(const uint8_t &, void *, raw_ostream &);
1178 static StringRef input(StringRef, void *, uint8_t &);
1179 static QuotingType mustQuote(StringRef) { return QuotingType::None; }
1183 struct ScalarTraits<uint16_t> {
1184 static void output(const uint16_t &, void *, raw_ostream &);
1185 static StringRef input(StringRef, void *, uint16_t &);
1186 static QuotingType mustQuote(StringRef) { return QuotingType::None; }
1190 struct ScalarTraits<uint32_t> {
1191 static void output(const uint32_t &, void *, raw_ostream &);
1192 static StringRef input(StringRef, void *, uint32_t &);
1193 static QuotingType mustQuote(StringRef) { return QuotingType::None; }
1197 struct ScalarTraits<uint64_t> {
1198 static void output(const uint64_t &, void *, raw_ostream &);
1199 static StringRef input(StringRef, void *, uint64_t &);
1200 static QuotingType mustQuote(StringRef) { return QuotingType::None; }
1204 struct ScalarTraits<int8_t> {
1205 static void output(const int8_t &, void *, raw_ostream &);
1206 static StringRef input(StringRef, void *, int8_t &);
1207 static QuotingType mustQuote(StringRef) { return QuotingType::None; }
1211 struct ScalarTraits<int16_t> {
1212 static void output(const int16_t &, void *, raw_ostream &);
1213 static StringRef input(StringRef, void *, int16_t &);
1214 static QuotingType mustQuote(StringRef) { return QuotingType::None; }
1218 struct ScalarTraits<int32_t> {
1219 static void output(const int32_t &, void *, raw_ostream &);
1220 static StringRef input(StringRef, void *, int32_t &);
1221 static QuotingType mustQuote(StringRef) { return QuotingType::None; }
1225 struct ScalarTraits<int64_t> {
1226 static void output(const int64_t &, void *, raw_ostream &);
1227 static StringRef input(StringRef, void *, int64_t &);
1228 static QuotingType mustQuote(StringRef) { return QuotingType::None; }
1232 struct ScalarTraits<float> {
1233 static void output(const float &, void *, raw_ostream &);
1234 static StringRef input(StringRef, void *, float &);
1235 static QuotingType mustQuote(StringRef) { return QuotingType::None; }
1239 struct ScalarTraits<double> {
1240 static void output(const double &, void *, raw_ostream &);
1241 static StringRef input(StringRef, void *, double &);
1242 static QuotingType mustQuote(StringRef) { return QuotingType::None; }
1245 // For endian types, we just use the existing ScalarTraits for the underlying
1246 // type. This way endian aware types are supported whenever a ScalarTraits
1247 // is defined for the underlying type.
1248 template <typename value_type, support::endianness endian, size_t alignment>
1249 struct ScalarTraits<support::detail::packed_endian_specific_integral<
1250 value_type, endian, alignment>> {
1252 support::detail::packed_endian_specific_integral<value_type, endian,
1255 static void output(const endian_type &E, void *Ctx, raw_ostream &Stream) {
1256 ScalarTraits<value_type>::output(static_cast<value_type>(E), Ctx, Stream);
1259 static StringRef input(StringRef Str, void *Ctx, endian_type &E) {
1261 auto R = ScalarTraits<value_type>::input(Str, Ctx, V);
1262 E = static_cast<endian_type>(V);
1266 static QuotingType mustQuote(StringRef Str) {
1267 return ScalarTraits<value_type>::mustQuote(Str);
1271 // Utility for use within MappingTraits<>::mapping() method
1272 // to [de]normalize an object for use with YAML conversion.
1273 template <typename TNorm, typename TFinal>
1274 struct MappingNormalization {
1275 MappingNormalization(IO &i_o, TFinal &Obj)
1276 : io(i_o), BufPtr(nullptr), Result(Obj) {
1277 if ( io.outputting() ) {
1278 BufPtr = new (&Buffer) TNorm(io, Obj);
1281 BufPtr = new (&Buffer) TNorm(io);
1285 ~MappingNormalization() {
1286 if ( ! io.outputting() ) {
1287 Result = BufPtr->denormalize(io);
1292 TNorm* operator->() { return BufPtr; }
1295 using Storage = AlignedCharArrayUnion<TNorm>;
1303 // Utility for use within MappingTraits<>::mapping() method
1304 // to [de]normalize an object for use with YAML conversion.
1305 template <typename TNorm, typename TFinal>
1306 struct MappingNormalizationHeap {
1307 MappingNormalizationHeap(IO &i_o, TFinal &Obj, BumpPtrAllocator *allocator)
1308 : io(i_o), Result(Obj) {
1309 if ( io.outputting() ) {
1310 BufPtr = new (&Buffer) TNorm(io, Obj);
1312 else if (allocator) {
1313 BufPtr = allocator->Allocate<TNorm>();
1314 new (BufPtr) TNorm(io);
1316 BufPtr = new TNorm(io);
1320 ~MappingNormalizationHeap() {
1321 if ( io.outputting() ) {
1325 Result = BufPtr->denormalize(io);
1329 TNorm* operator->() { return BufPtr; }
1332 using Storage = AlignedCharArrayUnion<TNorm>;
1336 TNorm *BufPtr = nullptr;
1341 /// The Input class is used to parse a yaml document into in-memory structs
1344 /// It works by using YAMLParser to do a syntax parse of the entire yaml
1345 /// document, then the Input class builds a graph of HNodes which wraps
1346 /// each yaml Node. The extra layer is buffering. The low level yaml
1347 /// parser only lets you look at each node once. The buffering layer lets
1348 /// you search and interate multiple times. This is necessary because
1349 /// the mapRequired() method calls may not be in the same order
1350 /// as the keys in the document.
1352 class Input : public IO {
1354 // Construct a yaml Input object from a StringRef and optional
1355 // user-data. The DiagHandler can be specified to provide
1356 // alternative error reporting.
1357 Input(StringRef InputContent,
1358 void *Ctxt = nullptr,
1359 SourceMgr::DiagHandlerTy DiagHandler = nullptr,
1360 void *DiagHandlerCtxt = nullptr);
1361 Input(MemoryBufferRef Input,
1362 void *Ctxt = nullptr,
1363 SourceMgr::DiagHandlerTy DiagHandler = nullptr,
1364 void *DiagHandlerCtxt = nullptr);
1367 // Check if there was an syntax or semantic error during parsing.
1368 std::error_code error();
1371 bool outputting() override;
1372 bool mapTag(StringRef, bool) override;
1373 void beginMapping() override;
1374 void endMapping() override;
1375 bool preflightKey(const char *, bool, bool, bool &, void *&) override;
1376 void postflightKey(void *) override;
1377 std::vector<StringRef> keys() override;
1378 void beginFlowMapping() override;
1379 void endFlowMapping() override;
1380 unsigned beginSequence() override;
1381 void endSequence() override;
1382 bool preflightElement(unsigned index, void *&) override;
1383 void postflightElement(void *) override;
1384 unsigned beginFlowSequence() override;
1385 bool preflightFlowElement(unsigned , void *&) override;
1386 void postflightFlowElement(void *) override;
1387 void endFlowSequence() override;
1388 void beginEnumScalar() override;
1389 bool matchEnumScalar(const char*, bool) override;
1390 bool matchEnumFallback() override;
1391 void endEnumScalar() override;
1392 bool beginBitSetScalar(bool &) override;
1393 bool bitSetMatch(const char *, bool ) override;
1394 void endBitSetScalar() override;
1395 void scalarString(StringRef &, QuotingType) override;
1396 void blockScalarString(StringRef &) override;
1397 void scalarTag(std::string &) override;
1398 NodeKind getNodeKind() override;
1399 void setError(const Twine &message) override;
1400 bool canElideEmptySequence() override;
1403 virtual void anchor();
1406 HNode(Node *n) : _node(n) { }
1407 virtual ~HNode() = default;
1409 static bool classof(const HNode *) { return true; }
1414 class EmptyHNode : public HNode {
1415 void anchor() override;
1418 EmptyHNode(Node *n) : HNode(n) { }
1420 static bool classof(const HNode *n) { return NullNode::classof(n->_node); }
1422 static bool classof(const EmptyHNode *) { return true; }
1425 class ScalarHNode : public HNode {
1426 void anchor() override;
1429 ScalarHNode(Node *n, StringRef s) : HNode(n), _value(s) { }
1431 StringRef value() const { return _value; }
1433 static bool classof(const HNode *n) {
1434 return ScalarNode::classof(n->_node) ||
1435 BlockScalarNode::classof(n->_node);
1438 static bool classof(const ScalarHNode *) { return true; }
1444 class MapHNode : public HNode {
1445 void anchor() override;
1448 MapHNode(Node *n) : HNode(n) { }
1450 static bool classof(const HNode *n) {
1451 return MappingNode::classof(n->_node);
1454 static bool classof(const MapHNode *) { return true; }
1456 using NameToNode = StringMap<std::unique_ptr<HNode>>;
1459 SmallVector<std::string, 6> ValidKeys;
1462 class SequenceHNode : public HNode {
1463 void anchor() override;
1466 SequenceHNode(Node *n) : HNode(n) { }
1468 static bool classof(const HNode *n) {
1469 return SequenceNode::classof(n->_node);
1472 static bool classof(const SequenceHNode *) { return true; }
1474 std::vector<std::unique_ptr<HNode>> Entries;
1477 std::unique_ptr<Input::HNode> createHNodes(Node *node);
1478 void setError(HNode *hnode, const Twine &message);
1479 void setError(Node *node, const Twine &message);
1482 // These are only used by operator>>. They could be private
1483 // if those templated things could be made friends.
1484 bool setCurrentDocument();
1485 bool nextDocument();
1487 /// Returns the current node that's being parsed by the YAML Parser
.
1488 const Node
*getCurrentNode() const;
1491 SourceMgr SrcMgr
; // must be before Strm
1492 std::unique_ptr
<llvm::yaml::Stream
> Strm
;
1493 std::unique_ptr
<HNode
> TopNode
;
1495 BumpPtrAllocator StringAllocator
;
1496 document_iterator DocIterator
;
1497 std::vector
<bool> BitValuesUsed
;
1498 HNode
*CurrentNode
= nullptr;
1499 bool ScalarMatchFound
;
1503 /// The Output class is used to generate a yaml document from in-memory structs
1506 class Output
: public IO
{
1508 Output(raw_ostream
&, void *Ctxt
= nullptr, int WrapColumn
= 70);
1511 /// Set whether or not to output optional values which are equal
1512 /// to the default value. By default, when outputting if you attempt
1513 /// to write a value that is equal to the default, the value gets ignored.
1514 /// Sometimes, it is useful to be able to see these in the resulting YAML
1516 void setWriteDefaultValues(bool Write
) { WriteDefaultValues
= Write
; }
1518 bool outputting() override
;
1519 bool mapTag(StringRef
, bool) override
;
1520 void beginMapping() override
;
1521 void endMapping() override
;
1522 bool preflightKey(const char *key
, bool, bool, bool &, void *&) override
;
1523 void postflightKey(void *) override
;
1524 std::vector
<StringRef
> keys() override
;
1525 void beginFlowMapping() override
;
1526 void endFlowMapping() override
;
1527 unsigned beginSequence() override
;
1528 void endSequence() override
;
1529 bool preflightElement(unsigned, void *&) override
;
1530 void postflightElement(void *) override
;
1531 unsigned beginFlowSequence() override
;
1532 bool preflightFlowElement(unsigned, void *&) override
;
1533 void postflightFlowElement(void *) override
;
1534 void endFlowSequence() override
;
1535 void beginEnumScalar() override
;
1536 bool matchEnumScalar(const char*, bool) override
;
1537 bool matchEnumFallback() override
;
1538 void endEnumScalar() override
;
1539 bool beginBitSetScalar(bool &) override
;
1540 bool bitSetMatch(const char *, bool ) override
;
1541 void endBitSetScalar() override
;
1542 void scalarString(StringRef
&, QuotingType
) override
;
1543 void blockScalarString(StringRef
&) override
;
1544 void scalarTag(std::string
&) override
;
1545 NodeKind
getNodeKind() override
;
1546 void setError(const Twine
&message
) override
;
1547 bool canElideEmptySequence() override
;
1549 // These are only used by operator<<. They could be private
1550 // if that templated operator could be made a friend.
1551 void beginDocuments();
1552 bool preflightDocument(unsigned);
1553 void postflightDocument();
1554 void endDocuments();
1557 void output(StringRef s
);
1558 void outputUpToEndOfLine(StringRef s
);
1559 void newLineCheck();
1560 void outputNewLine();
1561 void paddedKey(StringRef key
);
1562 void flowKey(StringRef Key
);
1567 inFlowSeqFirstElement
,
1568 inFlowSeqOtherElement
,
1575 static bool inSeqAnyElement(InState State
);
1576 static bool inFlowSeqAnyElement(InState State
);
1577 static bool inMapAnyKey(InState State
);
1578 static bool inFlowMapAnyKey(InState State
);
1582 SmallVector
<InState
, 8> StateStack
;
1584 int ColumnAtFlowStart
= 0;
1585 int ColumnAtMapFlowStart
= 0;
1586 bool NeedBitValueComma
= false;
1587 bool NeedFlowSequenceComma
= false;
1588 bool EnumerationMatchFound
= false;
1589 bool NeedsNewLine
= false;
1590 bool WriteDefaultValues
= false;
1593 /// YAML I/O does conversion based on types. But often native data types
1594 /// are just a typedef of built in intergral types (e.g. int). But the C++
1595 /// type matching system sees through the typedef and all the typedefed types
1596 /// look like a built in type. This will cause the generic YAML I/O conversion
1597 /// to be used. To provide better control over the YAML conversion, you can
1598 /// use this macro instead of typedef. It will create a class with one field
1599 /// and automatic conversion operators to and from the base type.
1600 /// Based on BOOST_STRONG_TYPEDEF
1601 #define LLVM_YAML_STRONG_TYPEDEF(_base, _type) \
1603 _type() = default; \
1604 _type(const _base v) : value(v) {} \
1605 _type(const _type &v) = default; \
1606 _type &operator=(const _type &rhs) = default; \
1607 _type &operator=(const _base &rhs) { value = rhs; return *this; } \
1608 operator const _base & () const { return value; } \
1609 bool operator==(const _type &rhs) const { return value == rhs.value; } \
1610 bool operator==(const _base &rhs) const { return value == rhs; } \
1611 bool operator<(const _type &rhs) const { return value < rhs.value; } \
1613 using BaseType = _base; \
1617 /// Use these types instead of uintXX_t in any mapping to have
1618 /// its yaml output formatted as hexadecimal.
1620 LLVM_YAML_STRONG_TYPEDEF(uint8_t, Hex8
)
1621 LLVM_YAML_STRONG_TYPEDEF(uint16_t, Hex16
)
1622 LLVM_YAML_STRONG_TYPEDEF(uint32_t, Hex32
)
1623 LLVM_YAML_STRONG_TYPEDEF(uint64_t, Hex64
)
1626 struct ScalarTraits
<Hex8
> {
1627 static void output(const Hex8
&, void *, raw_ostream
&);
1628 static StringRef
input(StringRef
, void *, Hex8
&);
1629 static QuotingType
mustQuote(StringRef
) { return QuotingType::None
; }
1633 struct ScalarTraits
<Hex16
> {
1634 static void output(const Hex16
&, void *, raw_ostream
&);
1635 static StringRef
input(StringRef
, void *, Hex16
&);
1636 static QuotingType
mustQuote(StringRef
) { return QuotingType::None
; }
1640 struct ScalarTraits
<Hex32
> {
1641 static void output(const Hex32
&, void *, raw_ostream
&);
1642 static StringRef
input(StringRef
, void *, Hex32
&);
1643 static QuotingType
mustQuote(StringRef
) { return QuotingType::None
; }
1647 struct ScalarTraits
<Hex64
> {
1648 static void output(const Hex64
&, void *, raw_ostream
&);
1649 static StringRef
input(StringRef
, void *, Hex64
&);
1650 static QuotingType
mustQuote(StringRef
) { return QuotingType::None
; }
1653 // Define non-member operator>> so that Input can stream in a document list.
1654 template <typename T
>
1656 typename
std::enable_if
<has_DocumentListTraits
<T
>::value
, Input
&>::type
1657 operator>>(Input
&yin
, T
&docList
) {
1660 while ( yin
.setCurrentDocument() ) {
1661 yamlize(yin
, DocumentListTraits
<T
>::element(yin
, docList
, i
), true, Ctx
);
1670 // Define non-member operator>> so that Input can stream in a map as a document.
1671 template <typename T
>
1672 inline typename
std::enable_if
<has_MappingTraits
<T
, EmptyContext
>::value
,
1674 operator>>(Input
&yin
, T
&docMap
) {
1676 yin
.setCurrentDocument();
1677 yamlize(yin
, docMap
, true, Ctx
);
1681 // Define non-member operator>> so that Input can stream in a sequence as
1683 template <typename T
>
1685 typename
std::enable_if
<has_SequenceTraits
<T
>::value
, Input
&>::type
1686 operator>>(Input
&yin
, T
&docSeq
) {
1688 if (yin
.setCurrentDocument())
1689 yamlize(yin
, docSeq
, true, Ctx
);
1693 // Define non-member operator>> so that Input can stream in a block scalar.
1694 template <typename T
>
1696 typename
std::enable_if
<has_BlockScalarTraits
<T
>::value
, Input
&>::type
1697 operator>>(Input
&In
, T
&Val
) {
1699 if (In
.setCurrentDocument())
1700 yamlize(In
, Val
, true, Ctx
);
1704 // Define non-member operator>> so that Input can stream in a string map.
1705 template <typename T
>
1707 typename
std::enable_if
<has_CustomMappingTraits
<T
>::value
, Input
&>::type
1708 operator>>(Input
&In
, T
&Val
) {
1710 if (In
.setCurrentDocument())
1711 yamlize(In
, Val
, true, Ctx
);
1715 // Define non-member operator>> so that Input can stream in a polymorphic type.
1716 template <typename T
>
1717 inline typename
std::enable_if
<has_PolymorphicTraits
<T
>::value
, Input
&>::type
1718 operator>>(Input
&In
, T
&Val
) {
1720 if (In
.setCurrentDocument())
1721 yamlize(In
, Val
, true, Ctx
);
1725 // Provide better error message about types missing a trait specialization
1726 template <typename T
>
1727 inline typename
std::enable_if
<missingTraits
<T
, EmptyContext
>::value
,
1729 operator>>(Input
&yin
, T
&docSeq
) {
1730 char missing_yaml_trait_for_type
[sizeof(MissingTrait
<T
>)];
1734 // Define non-member operator<< so that Output can stream out document list.
1735 template <typename T
>
1737 typename
std::enable_if
<has_DocumentListTraits
<T
>::value
, Output
&>::type
1738 operator<<(Output
&yout
, T
&docList
) {
1740 yout
.beginDocuments();
1741 const size_t count
= DocumentListTraits
<T
>::size(yout
, docList
);
1742 for(size_t i
=0; i
< count
; ++i
) {
1743 if ( yout
.preflightDocument(i
) ) {
1744 yamlize(yout
, DocumentListTraits
<T
>::element(yout
, docList
, i
), true,
1746 yout
.postflightDocument();
1749 yout
.endDocuments();
1753 // Define non-member operator<< so that Output can stream out a map.
1754 template <typename T
>
1755 inline typename
std::enable_if
<has_MappingTraits
<T
, EmptyContext
>::value
,
1757 operator<<(Output
&yout
, T
&map
) {
1759 yout
.beginDocuments();
1760 if ( yout
.preflightDocument(0) ) {
1761 yamlize(yout
, map
, true, Ctx
);
1762 yout
.postflightDocument();
1764 yout
.endDocuments();
1768 // Define non-member operator<< so that Output can stream out a sequence.
1769 template <typename T
>
1771 typename
std::enable_if
<has_SequenceTraits
<T
>::value
, Output
&>::type
1772 operator<<(Output
&yout
, T
&seq
) {
1774 yout
.beginDocuments();
1775 if ( yout
.preflightDocument(0) ) {
1776 yamlize(yout
, seq
, true, Ctx
);
1777 yout
.postflightDocument();
1779 yout
.endDocuments();
1783 // Define non-member operator<< so that Output can stream out a block scalar.
1784 template <typename T
>
1786 typename
std::enable_if
<has_BlockScalarTraits
<T
>::value
, Output
&>::type
1787 operator<<(Output
&Out
, T
&Val
) {
1789 Out
.beginDocuments();
1790 if (Out
.preflightDocument(0)) {
1791 yamlize(Out
, Val
, true, Ctx
);
1792 Out
.postflightDocument();
1798 // Define non-member operator<< so that Output can stream out a string map.
1799 template <typename T
>
1801 typename
std::enable_if
<has_CustomMappingTraits
<T
>::value
, Output
&>::type
1802 operator<<(Output
&Out
, T
&Val
) {
1804 Out
.beginDocuments();
1805 if (Out
.preflightDocument(0)) {
1806 yamlize(Out
, Val
, true, Ctx
);
1807 Out
.postflightDocument();
1813 // Define non-member operator<< so that Output can stream out a polymorphic
1815 template <typename T
>
1816 inline typename
std::enable_if
<has_PolymorphicTraits
<T
>::value
, Output
&>::type
1817 operator<<(Output
&Out
, T
&Val
) {
1819 Out
.beginDocuments();
1820 if (Out
.preflightDocument(0)) {
1821 // FIXME: The parser does not support explicit documents terminated with a
1822 // plain scalar; the end-marker is included as part of the scalar token.
1823 assert(PolymorphicTraits
<T
>::getKind(Val
) != NodeKind::Scalar
&& "plain scalar documents are not supported");
1824 yamlize(Out
, Val
, true, Ctx
);
1825 Out
.postflightDocument();
1831 // Provide better error message about types missing a trait specialization
1832 template <typename T
>
1833 inline typename
std::enable_if
<missingTraits
<T
, EmptyContext
>::value
,
1835 operator<<(Output
&yout
, T
&seq
) {
1836 char missing_yaml_trait_for_type
[sizeof(MissingTrait
<T
>)];
1840 template <bool B
> struct IsFlowSequenceBase
{};
1841 template <> struct IsFlowSequenceBase
<true> { static const bool flow
= true; };
1843 template <typename T
, bool Flow
>
1844 struct SequenceTraitsImpl
: IsFlowSequenceBase
<Flow
> {
1846 using type
= typename
T::value_type
;
1849 static size_t size(IO
&io
, T
&seq
) { return seq
.size(); }
1851 static type
&element(IO
&io
, T
&seq
, size_t index
) {
1852 if (index
>= seq
.size())
1853 seq
.resize(index
+ 1);
1858 // Simple helper to check an expression can be used as a bool-valued template
1860 template <bool> struct CheckIsBool
{ static const bool value
= true; };
1862 // If T has SequenceElementTraits, then vector<T> and SmallVector<T, N> have
1863 // SequenceTraits that do the obvious thing.
1864 template <typename T
>
1865 struct SequenceTraits
<std::vector
<T
>,
1866 typename
std::enable_if
<CheckIsBool
<
1867 SequenceElementTraits
<T
>::flow
>::value
>::type
>
1868 : SequenceTraitsImpl
<std::vector
<T
>, SequenceElementTraits
<T
>::flow
> {};
1869 template <typename T
, unsigned N
>
1870 struct SequenceTraits
<SmallVector
<T
, N
>,
1871 typename
std::enable_if
<CheckIsBool
<
1872 SequenceElementTraits
<T
>::flow
>::value
>::type
>
1873 : SequenceTraitsImpl
<SmallVector
<T
, N
>, SequenceElementTraits
<T
>::flow
> {};
1875 // Sequences of fundamental types use flow formatting.
1876 template <typename T
>
1877 struct SequenceElementTraits
<
1878 T
, typename
std::enable_if
<std::is_fundamental
<T
>::value
>::type
> {
1879 static const bool flow
= true;
1882 // Sequences of strings use block formatting.
1883 template<> struct SequenceElementTraits
<std::string
> {
1884 static const bool flow
= false;
1886 template<> struct SequenceElementTraits
<StringRef
> {
1887 static const bool flow
= false;
1889 template<> struct SequenceElementTraits
<std::pair
<std::string
, std::string
>> {
1890 static const bool flow
= false;
1893 /// Implementation of CustomMappingTraits for std::map<std::string, T>.
1894 template <typename T
> struct StdMapStringCustomMappingTraitsImpl
{
1895 using map_type
= std::map
<std::string
, T
>;
1897 static void inputOne(IO
&io
, StringRef key
, map_type
&v
) {
1898 io
.mapRequired(key
.str().c_str(), v
[key
]);
1901 static void output(IO
&io
, map_type
&v
) {
1903 io
.mapRequired(p
.first
.c_str(), p
.second
);
1907 } // end namespace yaml
1908 } // end namespace llvm
1910 #define LLVM_YAML_IS_SEQUENCE_VECTOR_IMPL(TYPE, FLOW) \
1914 !std::is_fundamental<TYPE>::value && \
1915 !std::is_same<TYPE, std::string>::value && \
1916 !std::is_same<TYPE, llvm::StringRef>::value, \
1917 "only use LLVM_YAML_IS_SEQUENCE_VECTOR for types you control"); \
1918 template <> struct SequenceElementTraits<TYPE> { \
1919 static const bool flow = FLOW; \
1924 /// Utility for declaring that a std::vector of a particular type
1925 /// should be considered a YAML sequence.
1926 #define LLVM_YAML_IS_SEQUENCE_VECTOR(type) \
1927 LLVM_YAML_IS_SEQUENCE_VECTOR_IMPL(type, false)
1929 /// Utility for declaring that a std::vector of a particular type
1930 /// should be considered a YAML flow sequence.
1931 #define LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(type) \
1932 LLVM_YAML_IS_SEQUENCE_VECTOR_IMPL(type, true)
1934 #define LLVM_YAML_DECLARE_MAPPING_TRAITS(Type) \
1937 template <> struct MappingTraits<Type> { \
1938 static void mapping(IO &IO, Type &Obj); \
1943 #define LLVM_YAML_DECLARE_ENUM_TRAITS(Type) \
1946 template <> struct ScalarEnumerationTraits<Type> { \
1947 static void enumeration(IO &io, Type &Value); \
1952 #define LLVM_YAML_DECLARE_BITSET_TRAITS(Type) \
1955 template <> struct ScalarBitSetTraits<Type> { \
1956 static void bitset(IO &IO, Type &Options); \
1961 #define LLVM_YAML_DECLARE_SCALAR_TRAITS(Type, MustQuote) \
1964 template <> struct ScalarTraits<Type> { \
1965 static void output(const Type &Value, void *ctx, raw_ostream &Out); \
1966 static StringRef input(StringRef Scalar, void *ctxt, Type &Value); \
1967 static QuotingType mustQuote(StringRef) { return MustQuote; } \
1972 /// Utility for declaring that a std::vector of a particular type
1973 /// should be considered a YAML document list.
1974 #define LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(_type) \
1977 template <unsigned N> \
1978 struct DocumentListTraits<SmallVector<_type, N>> \
1979 : public SequenceTraitsImpl<SmallVector<_type, N>, false> {}; \
1981 struct DocumentListTraits<std::vector<_type>> \
1982 : public SequenceTraitsImpl<std::vector<_type>, false> {}; \
1986 /// Utility for declaring that std::map<std::string, _type> should be considered
1988 #define LLVM_YAML_IS_STRING_MAP(_type) \
1992 struct CustomMappingTraits<std::map<std::string, _type>> \
1993 : public StdMapStringCustomMappingTraitsImpl<_type> {}; \
1997 #endif // LLVM_SUPPORT_YAMLTRAITS_H