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);
104 template <typename T
, typename Enable
= void> struct ScalarEnumerationTraits
{
106 // static void enumeration(IO &io, T &value);
109 /// This class should be specialized by any integer type that is a union
110 /// of bit values and the YAML representation is a flow sequence of
111 /// strings. For example:
113 /// struct ScalarBitSetTraits<MyFlags> {
114 /// static void bitset(IO &io, MyFlags &value) {
115 /// io.bitSetCase(value, "big", flagBig);
116 /// io.bitSetCase(value, "flat", flagFlat);
117 /// io.bitSetCase(value, "round", flagRound);
120 template <typename T
, typename Enable
= void> struct ScalarBitSetTraits
{
122 // static void bitset(IO &io, T &value);
125 /// Describe which type of quotes should be used when quoting is necessary.
126 /// Some non-printable characters need to be double-quoted, while some others
127 /// are fine with simple-quoting, and some don't need any quoting.
128 enum class QuotingType
{ None
, Single
, Double
};
130 /// This class should be specialized by type that requires custom conversion
131 /// to/from a yaml scalar. For example:
134 /// struct ScalarTraits<MyType> {
135 /// static void output(const MyType &val, void*, llvm::raw_ostream &out) {
136 /// // stream out custom formatting
137 /// out << llvm::format("%x", val);
139 /// static StringRef input(StringRef scalar, void*, MyType &value) {
140 /// // parse scalar and set `value`
141 /// // return empty string on success, or error string
142 /// return StringRef();
144 /// static QuotingType mustQuote(StringRef) { return QuotingType::Single; }
146 template <typename T
, typename Enable
= void> struct ScalarTraits
{
149 // Function to write the value as a string:
150 // static void output(const T &value, void *ctxt, llvm::raw_ostream &out);
152 // Function to convert a string to a value. Returns the empty
153 // StringRef on success or an error string if string is malformed:
154 // static StringRef input(StringRef scalar, void *ctxt, T &value);
156 // Function to determine if the value should be quoted.
157 // static QuotingType mustQuote(StringRef);
160 /// This class should be specialized by type that requires custom conversion
161 /// to/from a YAML literal block scalar. For example:
164 /// struct BlockScalarTraits<MyType> {
165 /// static void output(const MyType &Value, void*, llvm::raw_ostream &Out)
167 /// // stream out custom formatting
170 /// static StringRef input(StringRef Scalar, void*, MyType &Value) {
171 /// // parse scalar and set `value`
172 /// // return empty string on success, or error string
173 /// return StringRef();
176 template <typename T
>
177 struct BlockScalarTraits
{
180 // Function to write the value as a string:
181 // static void output(const T &Value, void *ctx, llvm::raw_ostream &Out);
183 // Function to convert a string to a value. Returns the empty
184 // StringRef on success or an error string if string is malformed:
185 // static StringRef input(StringRef Scalar, void *ctxt, T &Value);
188 // static StringRef inputTag(T &Val, std::string Tag)
189 // static void outputTag(const T &Val, raw_ostream &Out)
192 /// This class should be specialized by type that requires custom conversion
193 /// to/from a YAML scalar with optional tags. For example:
196 /// struct TaggedScalarTraits<MyType> {
197 /// static void output(const MyType &Value, void*, llvm::raw_ostream
198 /// &ScalarOut, llvm::raw_ostream &TagOut)
200 /// // stream out custom formatting including optional Tag
203 /// static StringRef input(StringRef Scalar, StringRef Tag, void*, MyType
205 /// // parse scalar and set `value`
206 /// // return empty string on success, or error string
207 /// return StringRef();
209 /// static QuotingType mustQuote(const MyType &Value, StringRef) {
210 /// return QuotingType::Single;
213 template <typename T
> struct TaggedScalarTraits
{
216 // Function to write the value and tag as strings:
217 // static void output(const T &Value, void *ctx, llvm::raw_ostream &ScalarOut,
218 // llvm::raw_ostream &TagOut);
220 // Function to convert a string to a value. Returns the empty
221 // StringRef on success or an error string if string is malformed:
222 // static StringRef input(StringRef Scalar, StringRef Tag, void *ctxt, T
225 // Function to determine if the value should be quoted.
226 // static QuotingType mustQuote(const T &Value, StringRef Scalar);
229 /// This class should be specialized by any type that needs to be converted
230 /// to/from a YAML sequence. For example:
233 /// struct SequenceTraits<MyContainer> {
234 /// static size_t size(IO &io, MyContainer &seq) {
235 /// return seq.size();
237 /// static MyType& element(IO &, MyContainer &seq, size_t index) {
238 /// if ( index >= seq.size() )
239 /// seq.resize(index+1);
240 /// return seq[index];
243 template<typename T
, typename EnableIf
= void>
244 struct SequenceTraits
{
246 // static size_t size(IO &io, T &seq);
247 // static T::value_type& element(IO &io, T &seq, size_t index);
249 // The following is option and will cause generated YAML to use
250 // a flow sequence (e.g. [a,b,c]).
251 // static const bool flow = true;
254 /// This class should be specialized by any type for which vectors of that
255 /// type need to be converted to/from a YAML sequence.
256 template<typename T
, typename EnableIf
= void>
257 struct SequenceElementTraits
{
259 // static const bool flow;
262 /// This class should be specialized by any type that needs to be converted
263 /// to/from a list of YAML documents.
265 struct DocumentListTraits
{
267 // static size_t size(IO &io, T &seq);
268 // static T::value_type& element(IO &io, T &seq, size_t index);
271 /// This class should be specialized by any type that needs to be converted
272 /// to/from a YAML mapping in the case where the names of the keys are not known
273 /// in advance, e.g. a string map.
274 template <typename T
>
275 struct CustomMappingTraits
{
276 // static void inputOne(IO &io, StringRef key, T &elem);
277 // static void output(IO &io, T &elem);
280 /// This class should be specialized by any type that can be represented as
281 /// a scalar, map, or sequence, decided dynamically. For example:
283 /// typedef std::unique_ptr<MyBase> MyPoly;
286 /// struct PolymorphicTraits<MyPoly> {
287 /// static NodeKind getKind(const MyPoly &poly) {
288 /// return poly->getKind();
290 /// static MyScalar& getAsScalar(MyPoly &poly) {
291 /// if (!poly || !isa<MyScalar>(poly))
292 /// poly.reset(new MyScalar());
293 /// return *cast<MyScalar>(poly.get());
297 template <typename T
> struct PolymorphicTraits
{
299 // static NodeKind getKind(const T &poly);
300 // static scalar_type &getAsScalar(T &poly);
301 // static map_type &getAsMap(T &poly);
302 // static sequence_type &getAsSequence(T &poly);
305 // Only used for better diagnostics of missing traits
306 template <typename T
>
309 // Test if ScalarEnumerationTraits<T> is defined on type T.
311 struct has_ScalarEnumerationTraits
313 using Signature_enumeration
= void (*)(class IO
&, T
&);
315 template <typename U
>
316 static char test(SameType
<Signature_enumeration
, &U::enumeration
>*);
318 template <typename U
>
319 static double test(...);
321 static bool const value
=
322 (sizeof(test
<ScalarEnumerationTraits
<T
>>(nullptr)) == 1);
325 // Test if ScalarBitSetTraits<T> is defined on type T.
327 struct has_ScalarBitSetTraits
329 using Signature_bitset
= void (*)(class IO
&, T
&);
331 template <typename U
>
332 static char test(SameType
<Signature_bitset
, &U::bitset
>*);
334 template <typename U
>
335 static double test(...);
337 static bool const value
= (sizeof(test
<ScalarBitSetTraits
<T
>>(nullptr)) == 1);
340 // Test if ScalarTraits<T> is defined on type T.
342 struct has_ScalarTraits
344 using Signature_input
= StringRef (*)(StringRef
, void*, T
&);
345 using Signature_output
= void (*)(const T
&, void*, raw_ostream
&);
346 using Signature_mustQuote
= QuotingType (*)(StringRef
);
348 template <typename U
>
349 static char test(SameType
<Signature_input
, &U::input
> *,
350 SameType
<Signature_output
, &U::output
> *,
351 SameType
<Signature_mustQuote
, &U::mustQuote
> *);
353 template <typename U
>
354 static double test(...);
356 static bool const value
=
357 (sizeof(test
<ScalarTraits
<T
>>(nullptr, nullptr, nullptr)) == 1);
360 // Test if BlockScalarTraits<T> is defined on type T.
362 struct has_BlockScalarTraits
364 using Signature_input
= StringRef (*)(StringRef
, void *, T
&);
365 using Signature_output
= void (*)(const T
&, void *, raw_ostream
&);
367 template <typename U
>
368 static char test(SameType
<Signature_input
, &U::input
> *,
369 SameType
<Signature_output
, &U::output
> *);
371 template <typename U
>
372 static double test(...);
374 static bool const value
=
375 (sizeof(test
<BlockScalarTraits
<T
>>(nullptr, nullptr)) == 1);
378 // Test if TaggedScalarTraits<T> is defined on type T.
379 template <class T
> struct has_TaggedScalarTraits
{
380 using Signature_input
= StringRef (*)(StringRef
, StringRef
, void *, T
&);
381 using Signature_output
= void (*)(const T
&, void *, raw_ostream
&,
383 using Signature_mustQuote
= QuotingType (*)(const T
&, StringRef
);
385 template <typename U
>
386 static char test(SameType
<Signature_input
, &U::input
> *,
387 SameType
<Signature_output
, &U::output
> *,
388 SameType
<Signature_mustQuote
, &U::mustQuote
> *);
390 template <typename U
> static double test(...);
392 static bool const value
=
393 (sizeof(test
<TaggedScalarTraits
<T
>>(nullptr, nullptr, nullptr)) == 1);
396 // Test if MappingContextTraits<T> is defined on type T.
397 template <class T
, class Context
> struct has_MappingTraits
{
398 using Signature_mapping
= void (*)(class IO
&, T
&, Context
&);
400 template <typename U
>
401 static char test(SameType
<Signature_mapping
, &U::mapping
>*);
403 template <typename U
>
404 static double test(...);
406 static bool const value
=
407 (sizeof(test
<MappingContextTraits
<T
, Context
>>(nullptr)) == 1);
410 // Test if MappingTraits<T> is defined on type T.
411 template <class T
> struct has_MappingTraits
<T
, EmptyContext
> {
412 using Signature_mapping
= void (*)(class IO
&, T
&);
414 template <typename U
>
415 static char test(SameType
<Signature_mapping
, &U::mapping
> *);
417 template <typename U
> static double test(...);
419 static bool const value
= (sizeof(test
<MappingTraits
<T
>>(nullptr)) == 1);
422 // Test if MappingContextTraits<T>::validate() is defined on type T.
423 template <class T
, class Context
> struct has_MappingValidateTraits
{
424 using Signature_validate
= StringRef (*)(class IO
&, T
&, Context
&);
426 template <typename U
>
427 static char test(SameType
<Signature_validate
, &U::validate
>*);
429 template <typename U
>
430 static double test(...);
432 static bool const value
=
433 (sizeof(test
<MappingContextTraits
<T
, Context
>>(nullptr)) == 1);
436 // Test if MappingTraits<T>::validate() is defined on type T.
437 template <class T
> struct has_MappingValidateTraits
<T
, EmptyContext
> {
438 using Signature_validate
= StringRef (*)(class IO
&, T
&);
440 template <typename U
>
441 static char test(SameType
<Signature_validate
, &U::validate
> *);
443 template <typename U
> static double test(...);
445 static bool const value
= (sizeof(test
<MappingTraits
<T
>>(nullptr)) == 1);
448 // Test if SequenceTraits<T> is defined on type T.
450 struct has_SequenceMethodTraits
452 using Signature_size
= size_t (*)(class IO
&, T
&);
454 template <typename U
>
455 static char test(SameType
<Signature_size
, &U::size
>*);
457 template <typename U
>
458 static double test(...);
460 static bool const value
= (sizeof(test
<SequenceTraits
<T
>>(nullptr)) == 1);
463 // Test if CustomMappingTraits<T> is defined on type T.
465 struct has_CustomMappingTraits
467 using Signature_input
= void (*)(IO
&io
, StringRef key
, T
&v
);
469 template <typename U
>
470 static char test(SameType
<Signature_input
, &U::inputOne
>*);
472 template <typename U
>
473 static double test(...);
475 static bool const value
=
476 (sizeof(test
<CustomMappingTraits
<T
>>(nullptr)) == 1);
479 // has_FlowTraits<int> will cause an error with some compilers because
480 // it subclasses int. Using this wrapper only instantiates the
481 // real has_FlowTraits only if the template type is a class.
482 template <typename T
, bool Enabled
= std::is_class
<T
>::value
>
486 static const bool value
= false;
489 // Some older gcc compilers don't support straight forward tests
490 // for members, so test for ambiguity cause by the base and derived
491 // classes both defining the member.
493 struct has_FlowTraits
<T
, true>
495 struct Fallback
{ bool flow
; };
496 struct Derived
: T
, Fallback
{ };
499 static char (&f(SameType
<bool Fallback::*, &C::flow
>*))[1];
502 static char (&f(...))[2];
504 static bool const value
= sizeof(f
<Derived
>(nullptr)) == 2;
507 // Test if SequenceTraits<T> is defined on type T
509 struct has_SequenceTraits
: public std::integral_constant
<bool,
510 has_SequenceMethodTraits
<T
>::value
> { };
512 // Test if DocumentListTraits<T> is defined on type T
514 struct has_DocumentListTraits
516 using Signature_size
= size_t (*)(class IO
&, T
&);
518 template <typename U
>
519 static char test(SameType
<Signature_size
, &U::size
>*);
521 template <typename U
>
522 static double test(...);
524 static bool const value
= (sizeof(test
<DocumentListTraits
<T
>>(nullptr))==1);
527 template <class T
> struct has_PolymorphicTraits
{
528 using Signature_getKind
= NodeKind (*)(const T
&);
530 template <typename U
>
531 static char test(SameType
<Signature_getKind
, &U::getKind
> *);
533 template <typename U
> static double test(...);
535 static bool const value
= (sizeof(test
<PolymorphicTraits
<T
>>(nullptr)) == 1);
538 inline bool isNumeric(StringRef S
) {
539 const static auto skipDigits
= [](StringRef Input
) {
540 return Input
.drop_front(
541 std::min(Input
.find_first_not_of("0123456789"), Input
.size()));
544 // Make S.front() and S.drop_front().front() (if S.front() is [+-]) calls
546 if (S
.empty() || S
.equals("+") || S
.equals("-"))
549 if (S
.equals(".nan") || S
.equals(".NaN") || S
.equals(".NAN"))
552 // Infinity and decimal numbers can be prefixed with sign.
553 StringRef Tail
= (S
.front() == '-' || S
.front() == '+') ? S
.drop_front() : S
;
555 // Check for infinity first, because checking for hex and oct numbers is more
557 if (Tail
.equals(".inf") || Tail
.equals(".Inf") || Tail
.equals(".INF"))
560 // Section 10.3.2 Tag Resolution
561 // YAML 1.2 Specification prohibits Base 8 and Base 16 numbers prefixed with
562 // [-+], so S should be used instead of Tail.
563 if (S
.startswith("0o"))
564 return S
.size() > 2 &&
565 S
.drop_front(2).find_first_not_of("01234567") == StringRef::npos
;
567 if (S
.startswith("0x"))
568 return S
.size() > 2 && S
.drop_front(2).find_first_not_of(
569 "0123456789abcdefABCDEF") == StringRef::npos
;
571 // Parse float: [-+]? (\. [0-9]+ | [0-9]+ (\. [0-9]* )?) ([eE] [-+]? [0-9]+)?
574 // Handle cases when the number starts with '.' and hence needs at least one
575 // digit after dot (as opposed by number which has digits before the dot), but
577 if (S
.startswith(".") &&
579 (S
.size() > 1 && std::strchr("0123456789", S
[1]) == nullptr)))
582 if (S
.startswith("E") || S
.startswith("e"))
590 ParseState State
= Default
;
594 // Accept decimal integer.
598 if (S
.front() == '.') {
601 } else if (S
.front() == 'e' || S
.front() == 'E') {
602 State
= FoundExponent
;
608 if (State
== FoundDot
) {
613 if (S
.front() == 'e' || S
.front() == 'E') {
614 State
= FoundExponent
;
621 assert(State
== FoundExponent
&& "Should have found exponent at this point.");
625 if (S
.front() == '+' || S
.front() == '-') {
631 return skipDigits(S
).empty();
634 inline bool isNull(StringRef S
) {
635 return S
.equals("null") || S
.equals("Null") || S
.equals("NULL") ||
639 inline bool isBool(StringRef S
) {
640 return S
.equals("true") || S
.equals("True") || S
.equals("TRUE") ||
641 S
.equals("false") || S
.equals("False") || S
.equals("FALSE");
644 // 5.1. Character Set
645 // The allowed character range explicitly excludes the C0 control block #x0-#x1F
646 // (except for TAB #x9, LF #xA, and CR #xD which are allowed), DEL #x7F, the C1
647 // control block #x80-#x9F (except for NEL #x85 which is allowed), the surrogate
648 // block #xD800-#xDFFF, #xFFFE, and #xFFFF.
649 inline QuotingType
needsQuotes(StringRef S
) {
651 return QuotingType::Single
;
652 if (isspace(S
.front()) || isspace(S
.back()))
653 return QuotingType::Single
;
655 return QuotingType::Single
;
657 return QuotingType::Single
;
659 return QuotingType::Single
;
662 // Plain scalars must not begin with most indicators, as this would cause
663 // ambiguity with other YAML constructs.
664 static constexpr char Indicators
[] = R
"(-?:\,[]{}#&*!|>'"%@`
)";
665 if (S.find_first_of(Indicators) == 0)
666 return QuotingType::Single;
668 QuotingType MaxQuotingNeeded = QuotingType::None;
669 for (unsigned char C : S) {
675 // Safe scalar characters.
682 // TAB (0x9) is allowed in unquoted strings.
685 // LF(0xA) and CR(0xD) may delimit values and so require at least single
689 MaxQuotingNeeded = QuotingType::Single;
691 // DEL (0x7F) are excluded from the allowed character range.
693 return QuotingType::Double;
694 // Forward slash is allowed to be unquoted, but we quote it anyway. We have
695 // many tests that use FileCheck against YAML output, and this output often
696 // contains paths. If we quote backslashes but not forward slashes then
697 // paths will come out either quoted or unquoted depending on which platform
698 // the test is run on, making FileCheck comparisons difficult.
701 // C0 control block (0x0 - 0x1F) is excluded from the allowed character
704 return QuotingType::Double;
706 // Always double quote UTF-8.
708 return QuotingType::Double;
710 // The character is not safe, at least simple quoting needed.
711 MaxQuotingNeeded = QuotingType::Single;
716 return MaxQuotingNeeded;
719 template <typename T, typename Context>
721 : public std::integral_constant<bool,
722 !has_ScalarEnumerationTraits<T>::value &&
723 !has_ScalarBitSetTraits<T>::value &&
724 !has_ScalarTraits<T>::value &&
725 !has_BlockScalarTraits<T>::value &&
726 !has_TaggedScalarTraits<T>::value &&
727 !has_MappingTraits<T, Context>::value &&
728 !has_SequenceTraits<T>::value &&
729 !has_CustomMappingTraits<T>::value &&
730 !has_DocumentListTraits<T>::value &&
731 !has_PolymorphicTraits<T>::value> {};
733 template <typename T, typename Context>
734 struct validatedMappingTraits
735 : public std::integral_constant<
736 bool, has_MappingTraits<T, Context>::value &&
737 has_MappingValidateTraits<T, Context>::value> {};
739 template <typename T, typename Context>
740 struct unvalidatedMappingTraits
741 : public std::integral_constant<
742 bool, has_MappingTraits<T, Context>::value &&
743 !has_MappingValidateTraits<T, Context>::value> {};
745 // Base class for Input and Output.
748 IO(void *Ctxt = nullptr);
751 virtual bool outputting() const = 0;
753 virtual unsigned beginSequence() = 0;
754 virtual bool preflightElement(unsigned, void *&) = 0;
755 virtual void postflightElement(void*) = 0;
756 virtual void endSequence() = 0;
757 virtual bool canElideEmptySequence() = 0;
759 virtual unsigned beginFlowSequence() = 0;
760 virtual bool preflightFlowElement(unsigned, void *&) = 0;
761 virtual void postflightFlowElement(void*) = 0;
762 virtual void endFlowSequence() = 0;
764 virtual bool mapTag(StringRef Tag, bool Default=false) = 0;
765 virtual void beginMapping() = 0;
766 virtual void endMapping() = 0;
767 virtual bool preflightKey(const char*, bool, bool, bool &, void *&) = 0;
768 virtual void postflightKey(void*) = 0;
769 virtual std::vector<StringRef> keys() = 0;
771 virtual void beginFlowMapping() = 0;
772 virtual void endFlowMapping() = 0;
774 virtual void beginEnumScalar() = 0;
775 virtual bool matchEnumScalar(const char*, bool) = 0;
776 virtual bool matchEnumFallback() = 0;
777 virtual void endEnumScalar() = 0;
779 virtual bool beginBitSetScalar(bool &) = 0;
780 virtual bool bitSetMatch(const char*, bool) = 0;
781 virtual void endBitSetScalar() = 0;
783 virtual void scalarString(StringRef &, QuotingType) = 0;
784 virtual void blockScalarString(StringRef &) = 0;
785 virtual void scalarTag(std::string &) = 0;
787 virtual NodeKind getNodeKind() = 0;
789 virtual void setError(const Twine &) = 0;
791 template <typename T>
792 void enumCase(T &Val, const char* Str, const T ConstVal) {
793 if ( matchEnumScalar(Str, outputting() && Val == ConstVal) ) {
798 // allow anonymous enum values to be used with LLVM_YAML_STRONG_TYPEDEF
799 template <typename T>
800 void enumCase(T &Val, const char* Str, const uint32_t ConstVal) {
801 if ( matchEnumScalar(Str, outputting() && Val == static_cast<T>(ConstVal)) ) {
806 template <typename FBT, typename T>
807 void enumFallback(T &Val) {
808 if (matchEnumFallback()) {
809 EmptyContext Context;
810 // FIXME: Force integral conversion to allow strong typedefs to convert.
811 FBT Res = static_cast<typename FBT::BaseType>(Val);
812 yamlize(*this, Res, true, Context);
813 Val = static_cast<T>(static_cast<typename FBT::BaseType>(Res));
817 template <typename T>
818 void bitSetCase(T &Val, const char* Str, const T ConstVal) {
819 if ( bitSetMatch(Str, outputting() && (Val & ConstVal) == ConstVal) ) {
820 Val = static_cast<T>(Val | ConstVal);
824 // allow anonymous enum values to be used with LLVM_YAML_STRONG_TYPEDEF
825 template <typename T>
826 void bitSetCase(T &Val, const char* Str, const uint32_t ConstVal) {
827 if ( bitSetMatch(Str, outputting() && (Val & ConstVal) == ConstVal) ) {
828 Val = static_cast<T>(Val | ConstVal);
832 template <typename T>
833 void maskedBitSetCase(T &Val, const char *Str, T ConstVal, T Mask) {
834 if (bitSetMatch(Str, outputting() && (Val & Mask) == ConstVal))
835 Val = Val | ConstVal;
838 template <typename T>
839 void maskedBitSetCase(T &Val, const char *Str, uint32_t ConstVal,
841 if (bitSetMatch(Str, outputting() && (Val & Mask) == ConstVal))
842 Val = Val | ConstVal;
845 void *getContext() const;
846 void setContext(void *);
848 template <typename T> void mapRequired(const char *Key, T &Val) {
850 this->processKey(Key, Val, true, Ctx);
853 template <typename T, typename Context>
854 void mapRequired(const char *Key, T &Val, Context &Ctx) {
855 this->processKey(Key, Val, true, Ctx);
858 template <typename T> void mapOptional(const char *Key, T &Val) {
860 mapOptionalWithContext(Key, Val, Ctx);
863 template <typename T, typename DefaultT>
864 void mapOptional(const char *Key, T &Val, const DefaultT &Default) {
866 mapOptionalWithContext(Key, Val, Default, Ctx);
869 template <typename T, typename Context>
870 typename std::enable_if<has_SequenceTraits<T>::value, void>::type
871 mapOptionalWithContext(const char *Key, T &Val, Context &Ctx) {
872 // omit key/value instead of outputting empty sequence
873 if (this->canElideEmptySequence() && !(Val.begin() != Val.end()))
875 this->processKey(Key, Val, false, Ctx);
878 template <typename T, typename Context>
879 void mapOptionalWithContext(const char *Key, Optional<T> &Val, Context &Ctx) {
880 this->processKeyWithDefault(Key, Val, Optional<T>(), /*Required=*/false,
884 template <typename T, typename Context>
885 typename std::enable_if<!has_SequenceTraits<T>::value, void>::type
886 mapOptionalWithContext(const char *Key, T &Val, Context &Ctx) {
887 this->processKey(Key, Val, false, Ctx);
890 template <typename T, typename Context, typename DefaultT>
891 void mapOptionalWithContext(const char *Key, T &Val, const DefaultT &Default,
893 static_assert(std::is_convertible<DefaultT, T>::value,
894 "Default type must be implicitly convertible to value type
!");
895 this->processKeyWithDefault(Key, Val, static_cast<const T &>(Default),
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) ) {
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 use existing scalar Traits class for the underlying
1246 // type. This way endian aware types are supported whenever the traits are
1247 // defined for the underlying type.
1248 template <typename value_type, support::endianness endian, size_t alignment>
1249 struct ScalarTraits<
1250 support::detail::packed_endian_specific_integral<value_type, endian,
1252 typename std::enable_if<has_ScalarTraits<value_type>::value>::type> {
1254 support::detail::packed_endian_specific_integral<value_type, endian,
1257 static void output(const endian_type &E, void *Ctx, raw_ostream &Stream) {
1258 ScalarTraits<value_type>::output(static_cast<value_type>(E), Ctx, Stream);
1261 static StringRef input(StringRef Str, void *Ctx, endian_type &E) {
1263 auto R = ScalarTraits<value_type>::input(Str, Ctx, V);
1264 E = static_cast<endian_type>(V);
1268 static QuotingType mustQuote(StringRef Str) {
1269 return ScalarTraits<value_type>::mustQuote(Str);
1273 template <typename value_type, support::endianness endian, size_t alignment>
1274 struct ScalarEnumerationTraits<
1275 support::detail::packed_endian_specific_integral<value_type, endian,
1277 typename std::enable_if<
1278 has_ScalarEnumerationTraits<value_type>::value>::type> {
1280 support::detail::packed_endian_specific_integral<value_type, endian,
1283 static void enumeration(IO &io, endian_type &E) {
1285 ScalarEnumerationTraits<value_type>::enumeration(io, V);
1290 template <typename value_type, support::endianness endian, size_t alignment>
1291 struct ScalarBitSetTraits<
1292 support::detail::packed_endian_specific_integral<value_type, endian,
1294 typename std::enable_if<has_ScalarBitSetTraits<value_type>::value>::type> {
1296 support::detail::packed_endian_specific_integral<value_type, endian,
1298 static void bitset(IO &io, endian_type &E) {
1300 ScalarBitSetTraits<value_type>::bitset(io, V);
1305 // Utility for use within MappingTraits<>::mapping() method
1306 // to [de]normalize an object for use with YAML conversion.
1307 template <typename TNorm, typename TFinal>
1308 struct MappingNormalization {
1309 MappingNormalization(IO &i_o, TFinal &Obj)
1310 : io(i_o), BufPtr(nullptr), Result(Obj) {
1311 if ( io.outputting() ) {
1312 BufPtr = new (&Buffer) TNorm(io, Obj);
1315 BufPtr = new (&Buffer) TNorm(io);
1319 ~MappingNormalization() {
1320 if ( ! io.outputting() ) {
1321 Result = BufPtr->denormalize(io);
1326 TNorm* operator->() { return BufPtr; }
1329 using Storage = AlignedCharArrayUnion<TNorm>;
1337 // Utility for use within MappingTraits<>::mapping() method
1338 // to [de]normalize an object for use with YAML conversion.
1339 template <typename TNorm, typename TFinal>
1340 struct MappingNormalizationHeap {
1341 MappingNormalizationHeap(IO &i_o, TFinal &Obj, BumpPtrAllocator *allocator)
1342 : io(i_o), Result(Obj) {
1343 if ( io.outputting() ) {
1344 BufPtr = new (&Buffer) TNorm(io, Obj);
1346 else if (allocator) {
1347 BufPtr = allocator->Allocate<TNorm>();
1348 new (BufPtr) TNorm(io);
1350 BufPtr = new TNorm(io);
1354 ~MappingNormalizationHeap() {
1355 if ( io.outputting() ) {
1359 Result = BufPtr->denormalize(io);
1363 TNorm* operator->() { return BufPtr; }
1366 using Storage = AlignedCharArrayUnion<TNorm>;
1370 TNorm *BufPtr = nullptr;
1375 /// The Input class is used to parse a yaml document into in-memory structs
1378 /// It works by using YAMLParser to do a syntax parse of the entire yaml
1379 /// document, then the Input class builds a graph of HNodes which wraps
1380 /// each yaml Node. The extra layer is buffering. The low level yaml
1381 /// parser only lets you look at each node once. The buffering layer lets
1382 /// you search and interate multiple times. This is necessary because
1383 /// the mapRequired() method calls may not be in the same order
1384 /// as the keys in the document.
1386 class Input : public IO {
1388 // Construct a yaml Input object from a StringRef and optional
1389 // user-data. The DiagHandler can be specified to provide
1390 // alternative error reporting.
1391 Input(StringRef InputContent,
1392 void *Ctxt = nullptr,
1393 SourceMgr::DiagHandlerTy DiagHandler = nullptr,
1394 void *DiagHandlerCtxt = nullptr);
1395 Input(MemoryBufferRef Input,
1396 void *Ctxt = nullptr,
1397 SourceMgr::DiagHandlerTy DiagHandler = nullptr,
1398 void *DiagHandlerCtxt = nullptr);
1401 // Check if there was an syntax or semantic error during parsing.
1402 std::error_code error();
1405 bool outputting() const override;
1406 bool mapTag(StringRef, bool) override;
1407 void beginMapping() override;
1408 void endMapping() override;
1409 bool preflightKey(const char *, bool, bool, bool &, void *&) override;
1410 void postflightKey(void *) override;
1411 std::vector<StringRef> keys() override;
1412 void beginFlowMapping() override;
1413 void endFlowMapping() override;
1414 unsigned beginSequence() override;
1415 void endSequence() override;
1416 bool preflightElement(unsigned index, void *&) override;
1417 void postflightElement(void *) override;
1418 unsigned beginFlowSequence() override;
1419 bool preflightFlowElement(unsigned , void *&) override;
1420 void postflightFlowElement(void *) override;
1421 void endFlowSequence() override;
1422 void beginEnumScalar() override;
1423 bool matchEnumScalar(const char*, bool) override;
1424 bool matchEnumFallback() override;
1425 void endEnumScalar() override;
1426 bool beginBitSetScalar(bool &) override;
1427 bool bitSetMatch(const char *, bool ) override;
1428 void endBitSetScalar() override;
1429 void scalarString(StringRef &, QuotingType) override;
1430 void blockScalarString(StringRef &) override;
1431 void scalarTag(std::string &) override;
1432 NodeKind getNodeKind() override;
1433 void setError(const Twine &message) override;
1434 bool canElideEmptySequence() override;
1437 virtual void anchor();
1440 HNode(Node *n) : _node(n) { }
1441 virtual ~HNode() = default;
1443 static bool classof(const HNode *) { return true; }
1448 class EmptyHNode : public HNode {
1449 void anchor() override;
1452 EmptyHNode(Node *n) : HNode(n) { }
1454 static bool classof(const HNode *n) { return NullNode::classof(n->_node); }
1456 static bool classof(const EmptyHNode *) { return true; }
1459 class ScalarHNode : public HNode {
1460 void anchor() override;
1463 ScalarHNode(Node *n, StringRef s) : HNode(n), _value(s) { }
1465 StringRef value() const { return _value; }
1467 static bool classof(const HNode *n) {
1468 return ScalarNode::classof(n->_node) ||
1469 BlockScalarNode::classof(n->_node);
1472 static bool classof(const ScalarHNode *) { return true; }
1478 class MapHNode : public HNode {
1479 void anchor() override;
1482 MapHNode(Node *n) : HNode(n) { }
1484 static bool classof(const HNode *n) {
1485 return MappingNode::classof(n->_node);
1488 static bool classof(const MapHNode *) { return true; }
1490 using NameToNode = StringMap<std::unique_ptr<HNode>>;
1493 SmallVector<std::string, 6> ValidKeys;
1496 class SequenceHNode : public HNode {
1497 void anchor() override;
1500 SequenceHNode(Node *n) : HNode(n) { }
1502 static bool classof(const HNode *n) {
1503 return SequenceNode::classof(n->_node);
1506 static bool classof(const SequenceHNode *) { return true; }
1508 std::vector<std::unique_ptr<HNode>> Entries;
1511 std::unique_ptr<Input::HNode> createHNodes(Node *node);
1512 void setError(HNode *hnode, const Twine &message);
1513 void setError(Node *node, const Twine &message);
1516 // These are only used by operator>>. They could be private
1517 // if those templated things could be made friends.
1518 bool setCurrentDocument();
1519 bool nextDocument();
1521 /// Returns the current node that's being parsed by the YAML Parser
.
1522 const Node
*getCurrentNode() const;
1525 SourceMgr SrcMgr
; // must be before Strm
1526 std::unique_ptr
<llvm::yaml::Stream
> Strm
;
1527 std::unique_ptr
<HNode
> TopNode
;
1529 BumpPtrAllocator StringAllocator
;
1530 document_iterator DocIterator
;
1531 std::vector
<bool> BitValuesUsed
;
1532 HNode
*CurrentNode
= nullptr;
1533 bool ScalarMatchFound
;
1537 /// The Output class is used to generate a yaml document from in-memory structs
1540 class Output
: public IO
{
1542 Output(raw_ostream
&, void *Ctxt
= nullptr, int WrapColumn
= 70);
1545 /// Set whether or not to output optional values which are equal
1546 /// to the default value. By default, when outputting if you attempt
1547 /// to write a value that is equal to the default, the value gets ignored.
1548 /// Sometimes, it is useful to be able to see these in the resulting YAML
1550 void setWriteDefaultValues(bool Write
) { WriteDefaultValues
= Write
; }
1552 bool outputting() const override
;
1553 bool mapTag(StringRef
, bool) override
;
1554 void beginMapping() override
;
1555 void endMapping() override
;
1556 bool preflightKey(const char *key
, bool, bool, bool &, void *&) override
;
1557 void postflightKey(void *) override
;
1558 std::vector
<StringRef
> keys() override
;
1559 void beginFlowMapping() override
;
1560 void endFlowMapping() override
;
1561 unsigned beginSequence() override
;
1562 void endSequence() override
;
1563 bool preflightElement(unsigned, void *&) override
;
1564 void postflightElement(void *) override
;
1565 unsigned beginFlowSequence() override
;
1566 bool preflightFlowElement(unsigned, void *&) override
;
1567 void postflightFlowElement(void *) override
;
1568 void endFlowSequence() override
;
1569 void beginEnumScalar() override
;
1570 bool matchEnumScalar(const char*, bool) override
;
1571 bool matchEnumFallback() override
;
1572 void endEnumScalar() override
;
1573 bool beginBitSetScalar(bool &) override
;
1574 bool bitSetMatch(const char *, bool ) override
;
1575 void endBitSetScalar() override
;
1576 void scalarString(StringRef
&, QuotingType
) override
;
1577 void blockScalarString(StringRef
&) override
;
1578 void scalarTag(std::string
&) override
;
1579 NodeKind
getNodeKind() override
;
1580 void setError(const Twine
&message
) override
;
1581 bool canElideEmptySequence() override
;
1583 // These are only used by operator<<. They could be private
1584 // if that templated operator could be made a friend.
1585 void beginDocuments();
1586 bool preflightDocument(unsigned);
1587 void postflightDocument();
1588 void endDocuments();
1591 void output(StringRef s
);
1592 void outputUpToEndOfLine(StringRef s
);
1593 void newLineCheck();
1594 void outputNewLine();
1595 void paddedKey(StringRef key
);
1596 void flowKey(StringRef Key
);
1601 inFlowSeqFirstElement
,
1602 inFlowSeqOtherElement
,
1609 static bool inSeqAnyElement(InState State
);
1610 static bool inFlowSeqAnyElement(InState State
);
1611 static bool inMapAnyKey(InState State
);
1612 static bool inFlowMapAnyKey(InState State
);
1616 SmallVector
<InState
, 8> StateStack
;
1618 int ColumnAtFlowStart
= 0;
1619 int ColumnAtMapFlowStart
= 0;
1620 bool NeedBitValueComma
= false;
1621 bool NeedFlowSequenceComma
= false;
1622 bool EnumerationMatchFound
= false;
1623 bool WriteDefaultValues
= false;
1625 StringRef PaddingBeforeContainer
;
1628 /// YAML I/O does conversion based on types. But often native data types
1629 /// are just a typedef of built in intergral types (e.g. int). But the C++
1630 /// type matching system sees through the typedef and all the typedefed types
1631 /// look like a built in type. This will cause the generic YAML I/O conversion
1632 /// to be used. To provide better control over the YAML conversion, you can
1633 /// use this macro instead of typedef. It will create a class with one field
1634 /// and automatic conversion operators to and from the base type.
1635 /// Based on BOOST_STRONG_TYPEDEF
1636 #define LLVM_YAML_STRONG_TYPEDEF(_base, _type) \
1638 _type() = default; \
1639 _type(const _base v) : value(v) {} \
1640 _type(const _type &v) = default; \
1641 _type &operator=(const _type &rhs) = default; \
1642 _type &operator=(const _base &rhs) { value = rhs; return *this; } \
1643 operator const _base & () const { return value; } \
1644 bool operator==(const _type &rhs) const { return value == rhs.value; } \
1645 bool operator==(const _base &rhs) const { return value == rhs; } \
1646 bool operator<(const _type &rhs) const { return value < rhs.value; } \
1648 using BaseType = _base; \
1652 /// Use these types instead of uintXX_t in any mapping to have
1653 /// its yaml output formatted as hexadecimal.
1655 LLVM_YAML_STRONG_TYPEDEF(uint8_t, Hex8
)
1656 LLVM_YAML_STRONG_TYPEDEF(uint16_t, Hex16
)
1657 LLVM_YAML_STRONG_TYPEDEF(uint32_t, Hex32
)
1658 LLVM_YAML_STRONG_TYPEDEF(uint64_t, Hex64
)
1661 struct ScalarTraits
<Hex8
> {
1662 static void output(const Hex8
&, void *, raw_ostream
&);
1663 static StringRef
input(StringRef
, void *, Hex8
&);
1664 static QuotingType
mustQuote(StringRef
) { return QuotingType::None
; }
1668 struct ScalarTraits
<Hex16
> {
1669 static void output(const Hex16
&, void *, raw_ostream
&);
1670 static StringRef
input(StringRef
, void *, Hex16
&);
1671 static QuotingType
mustQuote(StringRef
) { return QuotingType::None
; }
1675 struct ScalarTraits
<Hex32
> {
1676 static void output(const Hex32
&, void *, raw_ostream
&);
1677 static StringRef
input(StringRef
, void *, Hex32
&);
1678 static QuotingType
mustQuote(StringRef
) { return QuotingType::None
; }
1682 struct ScalarTraits
<Hex64
> {
1683 static void output(const Hex64
&, void *, raw_ostream
&);
1684 static StringRef
input(StringRef
, void *, Hex64
&);
1685 static QuotingType
mustQuote(StringRef
) { return QuotingType::None
; }
1688 // Define non-member operator>> so that Input can stream in a document list.
1689 template <typename T
>
1691 typename
std::enable_if
<has_DocumentListTraits
<T
>::value
, Input
&>::type
1692 operator>>(Input
&yin
, T
&docList
) {
1695 while ( yin
.setCurrentDocument() ) {
1696 yamlize(yin
, DocumentListTraits
<T
>::element(yin
, docList
, i
), true, Ctx
);
1705 // Define non-member operator>> so that Input can stream in a map as a document.
1706 template <typename T
>
1707 inline typename
std::enable_if
<has_MappingTraits
<T
, EmptyContext
>::value
,
1709 operator>>(Input
&yin
, T
&docMap
) {
1711 yin
.setCurrentDocument();
1712 yamlize(yin
, docMap
, true, Ctx
);
1716 // Define non-member operator>> so that Input can stream in a sequence as
1718 template <typename T
>
1720 typename
std::enable_if
<has_SequenceTraits
<T
>::value
, Input
&>::type
1721 operator>>(Input
&yin
, T
&docSeq
) {
1723 if (yin
.setCurrentDocument())
1724 yamlize(yin
, docSeq
, true, Ctx
);
1728 // Define non-member operator>> so that Input can stream in a block scalar.
1729 template <typename T
>
1731 typename
std::enable_if
<has_BlockScalarTraits
<T
>::value
, Input
&>::type
1732 operator>>(Input
&In
, T
&Val
) {
1734 if (In
.setCurrentDocument())
1735 yamlize(In
, Val
, true, Ctx
);
1739 // Define non-member operator>> so that Input can stream in a string map.
1740 template <typename T
>
1742 typename
std::enable_if
<has_CustomMappingTraits
<T
>::value
, Input
&>::type
1743 operator>>(Input
&In
, T
&Val
) {
1745 if (In
.setCurrentDocument())
1746 yamlize(In
, Val
, true, Ctx
);
1750 // Define non-member operator>> so that Input can stream in a polymorphic type.
1751 template <typename T
>
1752 inline typename
std::enable_if
<has_PolymorphicTraits
<T
>::value
, Input
&>::type
1753 operator>>(Input
&In
, T
&Val
) {
1755 if (In
.setCurrentDocument())
1756 yamlize(In
, Val
, true, Ctx
);
1760 // Provide better error message about types missing a trait specialization
1761 template <typename T
>
1762 inline typename
std::enable_if
<missingTraits
<T
, EmptyContext
>::value
,
1764 operator>>(Input
&yin
, T
&docSeq
) {
1765 char missing_yaml_trait_for_type
[sizeof(MissingTrait
<T
>)];
1769 // Define non-member operator<< so that Output can stream out document list.
1770 template <typename T
>
1772 typename
std::enable_if
<has_DocumentListTraits
<T
>::value
, Output
&>::type
1773 operator<<(Output
&yout
, T
&docList
) {
1775 yout
.beginDocuments();
1776 const size_t count
= DocumentListTraits
<T
>::size(yout
, docList
);
1777 for(size_t i
=0; i
< count
; ++i
) {
1778 if ( yout
.preflightDocument(i
) ) {
1779 yamlize(yout
, DocumentListTraits
<T
>::element(yout
, docList
, i
), true,
1781 yout
.postflightDocument();
1784 yout
.endDocuments();
1788 // Define non-member operator<< so that Output can stream out a map.
1789 template <typename T
>
1790 inline typename
std::enable_if
<has_MappingTraits
<T
, EmptyContext
>::value
,
1792 operator<<(Output
&yout
, T
&map
) {
1794 yout
.beginDocuments();
1795 if ( yout
.preflightDocument(0) ) {
1796 yamlize(yout
, map
, true, Ctx
);
1797 yout
.postflightDocument();
1799 yout
.endDocuments();
1803 // Define non-member operator<< so that Output can stream out a sequence.
1804 template <typename T
>
1806 typename
std::enable_if
<has_SequenceTraits
<T
>::value
, Output
&>::type
1807 operator<<(Output
&yout
, T
&seq
) {
1809 yout
.beginDocuments();
1810 if ( yout
.preflightDocument(0) ) {
1811 yamlize(yout
, seq
, true, Ctx
);
1812 yout
.postflightDocument();
1814 yout
.endDocuments();
1818 // Define non-member operator<< so that Output can stream out a block scalar.
1819 template <typename T
>
1821 typename
std::enable_if
<has_BlockScalarTraits
<T
>::value
, Output
&>::type
1822 operator<<(Output
&Out
, T
&Val
) {
1824 Out
.beginDocuments();
1825 if (Out
.preflightDocument(0)) {
1826 yamlize(Out
, Val
, true, Ctx
);
1827 Out
.postflightDocument();
1833 // Define non-member operator<< so that Output can stream out a string map.
1834 template <typename T
>
1836 typename
std::enable_if
<has_CustomMappingTraits
<T
>::value
, Output
&>::type
1837 operator<<(Output
&Out
, T
&Val
) {
1839 Out
.beginDocuments();
1840 if (Out
.preflightDocument(0)) {
1841 yamlize(Out
, Val
, true, Ctx
);
1842 Out
.postflightDocument();
1848 // Define non-member operator<< so that Output can stream out a polymorphic
1850 template <typename T
>
1851 inline typename
std::enable_if
<has_PolymorphicTraits
<T
>::value
, Output
&>::type
1852 operator<<(Output
&Out
, T
&Val
) {
1854 Out
.beginDocuments();
1855 if (Out
.preflightDocument(0)) {
1856 // FIXME: The parser does not support explicit documents terminated with a
1857 // plain scalar; the end-marker is included as part of the scalar token.
1858 assert(PolymorphicTraits
<T
>::getKind(Val
) != NodeKind::Scalar
&& "plain scalar documents are not supported");
1859 yamlize(Out
, Val
, true, Ctx
);
1860 Out
.postflightDocument();
1866 // Provide better error message about types missing a trait specialization
1867 template <typename T
>
1868 inline typename
std::enable_if
<missingTraits
<T
, EmptyContext
>::value
,
1870 operator<<(Output
&yout
, T
&seq
) {
1871 char missing_yaml_trait_for_type
[sizeof(MissingTrait
<T
>)];
1875 template <bool B
> struct IsFlowSequenceBase
{};
1876 template <> struct IsFlowSequenceBase
<true> { static const bool flow
= true; };
1878 template <typename T
, bool Flow
>
1879 struct SequenceTraitsImpl
: IsFlowSequenceBase
<Flow
> {
1881 using type
= typename
T::value_type
;
1884 static size_t size(IO
&io
, T
&seq
) { return seq
.size(); }
1886 static type
&element(IO
&io
, T
&seq
, size_t index
) {
1887 if (index
>= seq
.size())
1888 seq
.resize(index
+ 1);
1893 // Simple helper to check an expression can be used as a bool-valued template
1895 template <bool> struct CheckIsBool
{ static const bool value
= true; };
1897 // If T has SequenceElementTraits, then vector<T> and SmallVector<T, N> have
1898 // SequenceTraits that do the obvious thing.
1899 template <typename T
>
1900 struct SequenceTraits
<std::vector
<T
>,
1901 typename
std::enable_if
<CheckIsBool
<
1902 SequenceElementTraits
<T
>::flow
>::value
>::type
>
1903 : SequenceTraitsImpl
<std::vector
<T
>, SequenceElementTraits
<T
>::flow
> {};
1904 template <typename T
, unsigned N
>
1905 struct SequenceTraits
<SmallVector
<T
, N
>,
1906 typename
std::enable_if
<CheckIsBool
<
1907 SequenceElementTraits
<T
>::flow
>::value
>::type
>
1908 : SequenceTraitsImpl
<SmallVector
<T
, N
>, SequenceElementTraits
<T
>::flow
> {};
1909 template <typename T
>
1910 struct SequenceTraits
<SmallVectorImpl
<T
>,
1911 typename
std::enable_if
<CheckIsBool
<
1912 SequenceElementTraits
<T
>::flow
>::value
>::type
>
1913 : SequenceTraitsImpl
<SmallVectorImpl
<T
>, SequenceElementTraits
<T
>::flow
> {};
1915 // Sequences of fundamental types use flow formatting.
1916 template <typename T
>
1917 struct SequenceElementTraits
<
1918 T
, typename
std::enable_if
<std::is_fundamental
<T
>::value
>::type
> {
1919 static const bool flow
= true;
1922 // Sequences of strings use block formatting.
1923 template<> struct SequenceElementTraits
<std::string
> {
1924 static const bool flow
= false;
1926 template<> struct SequenceElementTraits
<StringRef
> {
1927 static const bool flow
= false;
1929 template<> struct SequenceElementTraits
<std::pair
<std::string
, std::string
>> {
1930 static const bool flow
= false;
1933 /// Implementation of CustomMappingTraits for std::map<std::string, T>.
1934 template <typename T
> struct StdMapStringCustomMappingTraitsImpl
{
1935 using map_type
= std::map
<std::string
, T
>;
1937 static void inputOne(IO
&io
, StringRef key
, map_type
&v
) {
1938 io
.mapRequired(key
.str().c_str(), v
[key
]);
1941 static void output(IO
&io
, map_type
&v
) {
1943 io
.mapRequired(p
.first
.c_str(), p
.second
);
1947 } // end namespace yaml
1948 } // end namespace llvm
1950 #define LLVM_YAML_IS_SEQUENCE_VECTOR_IMPL(TYPE, FLOW) \
1954 !std::is_fundamental<TYPE>::value && \
1955 !std::is_same<TYPE, std::string>::value && \
1956 !std::is_same<TYPE, llvm::StringRef>::value, \
1957 "only use LLVM_YAML_IS_SEQUENCE_VECTOR for types you control"); \
1958 template <> struct SequenceElementTraits<TYPE> { \
1959 static const bool flow = FLOW; \
1964 /// Utility for declaring that a std::vector of a particular type
1965 /// should be considered a YAML sequence.
1966 #define LLVM_YAML_IS_SEQUENCE_VECTOR(type) \
1967 LLVM_YAML_IS_SEQUENCE_VECTOR_IMPL(type, false)
1969 /// Utility for declaring that a std::vector of a particular type
1970 /// should be considered a YAML flow sequence.
1971 #define LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(type) \
1972 LLVM_YAML_IS_SEQUENCE_VECTOR_IMPL(type, true)
1974 #define LLVM_YAML_DECLARE_MAPPING_TRAITS(Type) \
1977 template <> struct MappingTraits<Type> { \
1978 static void mapping(IO &IO, Type &Obj); \
1983 #define LLVM_YAML_DECLARE_ENUM_TRAITS(Type) \
1986 template <> struct ScalarEnumerationTraits<Type> { \
1987 static void enumeration(IO &io, Type &Value); \
1992 #define LLVM_YAML_DECLARE_BITSET_TRAITS(Type) \
1995 template <> struct ScalarBitSetTraits<Type> { \
1996 static void bitset(IO &IO, Type &Options); \
2001 #define LLVM_YAML_DECLARE_SCALAR_TRAITS(Type, MustQuote) \
2004 template <> struct ScalarTraits<Type> { \
2005 static void output(const Type &Value, void *ctx, raw_ostream &Out); \
2006 static StringRef input(StringRef Scalar, void *ctxt, Type &Value); \
2007 static QuotingType mustQuote(StringRef) { return MustQuote; } \
2012 /// Utility for declaring that a std::vector of a particular type
2013 /// should be considered a YAML document list.
2014 #define LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(_type) \
2017 template <unsigned N> \
2018 struct DocumentListTraits<SmallVector<_type, N>> \
2019 : public SequenceTraitsImpl<SmallVector<_type, N>, false> {}; \
2021 struct DocumentListTraits<std::vector<_type>> \
2022 : public SequenceTraitsImpl<std::vector<_type>, false> {}; \
2026 /// Utility for declaring that std::map<std::string, _type> should be considered
2028 #define LLVM_YAML_IS_STRING_MAP(_type) \
2032 struct CustomMappingTraits<std::map<std::string, _type>> \
2033 : public StdMapStringCustomMappingTraitsImpl<_type> {}; \
2037 #endif // LLVM_SUPPORT_YAMLTRAITS_H