1 //===- llvm/Support/YAMLTraits.h --------------------------------*- C++ -*-===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef LLVM_SUPPORT_YAMLTRAITS_H
11 #define LLVM_SUPPORT_YAMLTRAITS_H
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/DenseMapInfo.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/Regex.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/Support/YAMLParser.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Support/system_error.h"
33 /// This class should be specialized by any type that needs to be converted
34 /// to/from a YAML mapping. For example:
36 /// struct MappingTraits<MyStruct> {
37 /// static void mapping(IO &io, MyStruct &s) {
38 /// io.mapRequired("name", s.name);
39 /// io.mapRequired("size", s.size);
40 /// io.mapOptional("age", s.age);
44 struct MappingTraits {
46 // static void mapping(IO &io, T &fields);
47 // Optionally may provide:
48 // static StringRef validate(IO &io, T &fields);
52 /// This class should be specialized by any integral type that converts
53 /// to/from a YAML scalar where there is a one-to-one mapping between
54 /// in-memory values and a string in YAML. For example:
56 /// struct ScalarEnumerationTraits<Colors> {
57 /// static void enumeration(IO &io, Colors &value) {
58 /// io.enumCase(value, "red", cRed);
59 /// io.enumCase(value, "blue", cBlue);
60 /// io.enumCase(value, "green", cGreen);
64 struct ScalarEnumerationTraits {
66 // static void enumeration(IO &io, T &value);
70 /// This class should be specialized by any integer type that is a union
71 /// of bit values and the YAML representation is a flow sequence of
72 /// strings. For example:
74 /// struct ScalarBitSetTraits<MyFlags> {
75 /// static void bitset(IO &io, MyFlags &value) {
76 /// io.bitSetCase(value, "big", flagBig);
77 /// io.bitSetCase(value, "flat", flagFlat);
78 /// io.bitSetCase(value, "round", flagRound);
82 struct ScalarBitSetTraits {
84 // static void bitset(IO &io, T &value);
88 /// This class should be specialized by type that requires custom conversion
89 /// to/from a yaml scalar. For example:
92 /// struct ScalarTraits<MyType> {
93 /// static void output(const MyType &val, void*, llvm::raw_ostream &out) {
94 /// // stream out custom formatting
95 /// out << llvm::format("%x", val);
97 /// static StringRef input(StringRef scalar, void*, MyType &value) {
98 /// // parse scalar and set `value`
99 /// // return empty string on success, or error string
100 /// return StringRef();
102 /// static bool mustQuote(StringRef) { return true; }
105 struct ScalarTraits {
108 // Function to write the value as a string:
109 //static void output(const T &value, void *ctxt, llvm::raw_ostream &out);
111 // Function to convert a string to a value. Returns the empty
112 // StringRef on success or an error string if string is malformed:
113 //static StringRef input(StringRef scalar, void *ctxt, T &value);
115 // Function to determine if the value should be quoted.
116 //static bool mustQuote(StringRef);
120 /// This class should be specialized by any type that needs to be converted
121 /// to/from a YAML sequence. For example:
124 /// struct SequenceTraits< std::vector<MyType> > {
125 /// static size_t size(IO &io, std::vector<MyType> &seq) {
126 /// return seq.size();
128 /// static MyType& element(IO &, std::vector<MyType> &seq, size_t index) {
129 /// if ( index >= seq.size() )
130 /// seq.resize(index+1);
131 /// return seq[index];
135 struct SequenceTraits {
137 // static size_t size(IO &io, T &seq);
138 // static T::value_type& element(IO &io, T &seq, size_t index);
140 // The following is option and will cause generated YAML to use
141 // a flow sequence (e.g. [a,b,c]).
142 // static const bool flow = true;
146 /// This class should be specialized by any type that needs to be converted
147 /// to/from a list of YAML documents.
149 struct DocumentListTraits {
151 // static size_t size(IO &io, T &seq);
152 // static T::value_type& element(IO &io, T &seq, size_t index);
156 // Only used by compiler if both template types are the same
157 template <typename T, T>
160 // Only used for better diagnostics of missing traits
161 template <typename T>
166 // Test if ScalarEnumerationTraits<T> is defined on type T.
168 struct has_ScalarEnumerationTraits
170 typedef void (*Signature_enumeration)(class IO&, T&);
172 template <typename U>
173 static char test(SameType<Signature_enumeration, &U::enumeration>*);
175 template <typename U>
176 static double test(...);
179 static bool const value = (sizeof(test<ScalarEnumerationTraits<T> >(0)) == 1);
183 // Test if ScalarBitSetTraits<T> is defined on type T.
185 struct has_ScalarBitSetTraits
187 typedef void (*Signature_bitset)(class IO&, T&);
189 template <typename U>
190 static char test(SameType<Signature_bitset, &U::bitset>*);
192 template <typename U>
193 static double test(...);
196 static bool const value = (sizeof(test<ScalarBitSetTraits<T> >(0)) == 1);
200 // Test if ScalarTraits<T> is defined on type T.
202 struct has_ScalarTraits
204 typedef StringRef (*Signature_input)(StringRef, void*, T&);
205 typedef void (*Signature_output)(const T&, void*, llvm::raw_ostream&);
206 typedef bool (*Signature_mustQuote)(StringRef);
208 template <typename U>
209 static char test(SameType<Signature_input, &U::input> *,
210 SameType<Signature_output, &U::output> *,
211 SameType<Signature_mustQuote, &U::mustQuote> *);
213 template <typename U>
214 static double test(...);
217 static bool const value =
218 (sizeof(test<ScalarTraits<T>>(nullptr, nullptr, nullptr)) == 1);
222 // Test if MappingTraits<T> is defined on type T.
224 struct has_MappingTraits
226 typedef void (*Signature_mapping)(class IO&, T&);
228 template <typename U>
229 static char test(SameType<Signature_mapping, &U::mapping>*);
231 template <typename U>
232 static double test(...);
235 static bool const value = (sizeof(test<MappingTraits<T> >(0)) == 1);
238 // Test if MappingTraits<T>::validate() is defined on type T.
240 struct has_MappingValidateTraits
242 typedef StringRef (*Signature_validate)(class IO&, T&);
244 template <typename U>
245 static char test(SameType<Signature_validate, &U::validate>*);
247 template <typename U>
248 static double test(...);
251 static bool const value = (sizeof(test<MappingTraits<T> >(0)) == 1);
256 // Test if SequenceTraits<T> is defined on type T.
258 struct has_SequenceMethodTraits
260 typedef size_t (*Signature_size)(class IO&, T&);
262 template <typename U>
263 static char test(SameType<Signature_size, &U::size>*);
265 template <typename U>
266 static double test(...);
269 static bool const value = (sizeof(test<SequenceTraits<T> >(0)) == 1);
273 // has_FlowTraits<int> will cause an error with some compilers because
274 // it subclasses int. Using this wrapper only instantiates the
275 // real has_FlowTraits only if the template type is a class.
276 template <typename T, bool Enabled = std::is_class<T>::value>
280 static const bool value = false;
283 // Some older gcc compilers don't support straight forward tests
284 // for members, so test for ambiguity cause by the base and derived
285 // classes both defining the member.
287 struct has_FlowTraits<T, true>
289 struct Fallback { bool flow; };
290 struct Derived : T, Fallback { };
293 static char (&f(SameType<bool Fallback::*, &C::flow>*))[1];
296 static char (&f(...))[2];
299 static bool const value = sizeof(f<Derived>(0)) == 2;
304 // Test if SequenceTraits<T> is defined on type T
306 struct has_SequenceTraits : public std::integral_constant<bool,
307 has_SequenceMethodTraits<T>::value > { };
310 // Test if DocumentListTraits<T> is defined on type T
312 struct has_DocumentListTraits
314 typedef size_t (*Signature_size)(class IO&, T&);
316 template <typename U>
317 static char test(SameType<Signature_size, &U::size>*);
319 template <typename U>
320 static double test(...);
323 static bool const value = (sizeof(test<DocumentListTraits<T> >(0)) == 1);
326 inline bool isNumber(StringRef S) {
327 static const char OctalChars[] = "01234567";
328 if (S.startswith("0") &&
329 S.drop_front().find_first_not_of(OctalChars) == StringRef::npos)
332 if (S.startswith("0o") &&
333 S.drop_front(2).find_first_not_of(OctalChars) == StringRef::npos)
336 static const char HexChars[] = "0123456789abcdefABCDEF";
337 if (S.startswith("0x") &&
338 S.drop_front(2).find_first_not_of(HexChars) == StringRef::npos)
341 static const char DecChars[] = "0123456789";
342 if (S.find_first_not_of(DecChars) == StringRef::npos)
345 if (S.equals(".inf") || S.equals(".Inf") || S.equals(".INF"))
348 Regex FloatMatcher("^(\\.[0-9]+|[0-9]+(\\.[0-9]*)?)([eE][-+]?[0-9]+)?$");
349 if (FloatMatcher.match(S))
355 inline bool isNumeric(StringRef S) {
356 if ((S.front() == '-' || S.front() == '+') && isNumber(S.drop_front()))
362 if (S.equals(".nan") || S.equals(".NaN") || S.equals(".NAN"))
368 inline bool isNull(StringRef S) {
369 return S.equals("null") || S.equals("Null") || S.equals("NULL") ||
373 inline bool isBool(StringRef S) {
374 return S.equals("true") || S.equals("True") || S.equals("TRUE") ||
375 S.equals("false") || S.equals("False") || S.equals("FALSE");
378 inline bool needsQuotes(StringRef S) {
381 if (isspace(S.front()) || isspace(S.back()))
383 if (S.front() == ',')
386 static const char ScalarSafeChars[] =
387 "abcdefghijklmnopqrstuvwxyz"
388 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-/^., \t";
389 if (S.find_first_not_of(ScalarSafeChars) != StringRef::npos)
404 struct missingTraits : public std::integral_constant<bool,
405 !has_ScalarEnumerationTraits<T>::value
406 && !has_ScalarBitSetTraits<T>::value
407 && !has_ScalarTraits<T>::value
408 && !has_MappingTraits<T>::value
409 && !has_SequenceTraits<T>::value
410 && !has_DocumentListTraits<T>::value > {};
413 struct validatedMappingTraits : public std::integral_constant<bool,
414 has_MappingTraits<T>::value
415 && has_MappingValidateTraits<T>::value> {};
418 struct unvalidatedMappingTraits : public std::integral_constant<bool,
419 has_MappingTraits<T>::value
420 && !has_MappingValidateTraits<T>::value> {};
421 // Base class for Input and Output.
425 IO(void *Ctxt=nullptr);
428 virtual bool outputting() = 0;
430 virtual unsigned beginSequence() = 0;
431 virtual bool preflightElement(unsigned, void *&) = 0;
432 virtual void postflightElement(void*) = 0;
433 virtual void endSequence() = 0;
434 virtual bool canElideEmptySequence() = 0;
436 virtual unsigned beginFlowSequence() = 0;
437 virtual bool preflightFlowElement(unsigned, void *&) = 0;
438 virtual void postflightFlowElement(void*) = 0;
439 virtual void endFlowSequence() = 0;
441 virtual bool mapTag(StringRef Tag, bool Default=false) = 0;
442 virtual void beginMapping() = 0;
443 virtual void endMapping() = 0;
444 virtual bool preflightKey(const char*, bool, bool, bool &, void *&) = 0;
445 virtual void postflightKey(void*) = 0;
447 virtual void beginEnumScalar() = 0;
448 virtual bool matchEnumScalar(const char*, bool) = 0;
449 virtual void endEnumScalar() = 0;
451 virtual bool beginBitSetScalar(bool &) = 0;
452 virtual bool bitSetMatch(const char*, bool) = 0;
453 virtual void endBitSetScalar() = 0;
455 virtual void scalarString(StringRef &, bool) = 0;
457 virtual void setError(const Twine &) = 0;
459 template <typename T>
460 void enumCase(T &Val, const char* Str, const T ConstVal) {
461 if ( matchEnumScalar(Str, outputting() && Val == ConstVal) ) {
466 // allow anonymous enum values to be used with LLVM_YAML_STRONG_TYPEDEF
467 template <typename T>
468 void enumCase(T &Val, const char* Str, const uint32_t ConstVal) {
469 if ( matchEnumScalar(Str, outputting() && Val == static_cast<T>(ConstVal)) ) {
474 template <typename T>
475 void bitSetCase(T &Val, const char* Str, const T ConstVal) {
476 if ( bitSetMatch(Str, outputting() && (Val & ConstVal) == ConstVal) ) {
477 Val = Val | ConstVal;
481 // allow anonymous enum values to be used with LLVM_YAML_STRONG_TYPEDEF
482 template <typename T>
483 void bitSetCase(T &Val, const char* Str, const uint32_t ConstVal) {
484 if ( bitSetMatch(Str, outputting() && (Val & ConstVal) == ConstVal) ) {
485 Val = Val | ConstVal;
490 void setContext(void *);
492 template <typename T>
493 void mapRequired(const char* Key, T& Val) {
494 this->processKey(Key, Val, true);
497 template <typename T>
498 typename std::enable_if<has_SequenceTraits<T>::value,void>::type
499 mapOptional(const char* Key, T& Val) {
500 // omit key/value instead of outputting empty sequence
501 if ( this->canElideEmptySequence() && !(Val.begin() != Val.end()) )
503 this->processKey(Key, Val, false);
506 template <typename T>
507 void mapOptional(const char* Key, Optional<T> &Val) {
508 processKeyWithDefault(Key, Val, Optional<T>(), /*Required=*/false);
511 template <typename T>
512 typename std::enable_if<!has_SequenceTraits<T>::value,void>::type
513 mapOptional(const char* Key, T& Val) {
514 this->processKey(Key, Val, false);
517 template <typename T>
518 void mapOptional(const char* Key, T& Val, const T& Default) {
519 this->processKeyWithDefault(Key, Val, Default, false);
523 template <typename T>
524 void processKeyWithDefault(const char *Key, Optional<T> &Val,
525 const Optional<T> &DefaultValue, bool Required) {
526 assert(DefaultValue.hasValue() == false &&
527 "Optional<T> shouldn't have a value!");
530 const bool sameAsDefault = outputting() && !Val.hasValue();
531 if (!outputting() && !Val.hasValue())
533 if (this->preflightKey(Key, Required, sameAsDefault, UseDefault,
535 yamlize(*this, Val.getValue(), Required);
536 this->postflightKey(SaveInfo);
543 template <typename T>
544 void processKeyWithDefault(const char *Key, T &Val, const T& DefaultValue,
548 const bool sameAsDefault = outputting() && Val == DefaultValue;
549 if ( this->preflightKey(Key, Required, sameAsDefault, UseDefault,
551 yamlize(*this, Val, Required);
552 this->postflightKey(SaveInfo);
560 template <typename T>
561 void processKey(const char *Key, T &Val, bool Required) {
564 if ( this->preflightKey(Key, Required, false, UseDefault, SaveInfo) ) {
565 yamlize(*this, Val, Required);
566 this->postflightKey(SaveInfo);
577 typename std::enable_if<has_ScalarEnumerationTraits<T>::value,void>::type
578 yamlize(IO &io, T &Val, bool) {
579 io.beginEnumScalar();
580 ScalarEnumerationTraits<T>::enumeration(io, Val);
585 typename std::enable_if<has_ScalarBitSetTraits<T>::value,void>::type
586 yamlize(IO &io, T &Val, bool) {
588 if ( io.beginBitSetScalar(DoClear) ) {
590 Val = static_cast<T>(0);
591 ScalarBitSetTraits<T>::bitset(io, Val);
592 io.endBitSetScalar();
598 typename std::enable_if<has_ScalarTraits<T>::value,void>::type
599 yamlize(IO &io, T &Val, bool) {
600 if ( io.outputting() ) {
602 llvm::raw_string_ostream Buffer(Storage);
603 ScalarTraits<T>::output(Val, io.getContext(), Buffer);
604 StringRef Str = Buffer.str();
605 io.scalarString(Str, ScalarTraits<T>::mustQuote(Str));
609 io.scalarString(Str, ScalarTraits<T>::mustQuote(Str));
610 StringRef Result = ScalarTraits<T>::input(Str, io.getContext(), Val);
611 if ( !Result.empty() ) {
612 io.setError(llvm::Twine(Result));
619 typename std::enable_if<validatedMappingTraits<T>::value, void>::type
620 yamlize(IO &io, T &Val, bool) {
622 if (io.outputting()) {
623 StringRef Err = MappingTraits<T>::validate(io, Val);
625 llvm::errs() << Err << "\n";
626 assert(Err.empty() && "invalid struct trying to be written as yaml");
629 MappingTraits<T>::mapping(io, Val);
630 if (!io.outputting()) {
631 StringRef Err = MappingTraits<T>::validate(io, Val);
639 typename std::enable_if<unvalidatedMappingTraits<T>::value, void>::type
640 yamlize(IO &io, T &Val, bool) {
642 MappingTraits<T>::mapping(io, Val);
647 typename std::enable_if<missingTraits<T>::value, void>::type
648 yamlize(IO &io, T &Val, bool) {
649 char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
653 typename std::enable_if<has_SequenceTraits<T>::value,void>::type
654 yamlize(IO &io, T &Seq, bool) {
655 if ( has_FlowTraits< SequenceTraits<T> >::value ) {
656 unsigned incnt = io.beginFlowSequence();
657 unsigned count = io.outputting() ? SequenceTraits<T>::size(io, Seq) : incnt;
658 for(unsigned i=0; i < count; ++i) {
660 if ( io.preflightFlowElement(i, SaveInfo) ) {
661 yamlize(io, SequenceTraits<T>::element(io, Seq, i), true);
662 io.postflightFlowElement(SaveInfo);
665 io.endFlowSequence();
668 unsigned incnt = io.beginSequence();
669 unsigned count = io.outputting() ? SequenceTraits<T>::size(io, Seq) : incnt;
670 for(unsigned i=0; i < count; ++i) {
672 if ( io.preflightElement(i, SaveInfo) ) {
673 yamlize(io, SequenceTraits<T>::element(io, Seq, i), true);
674 io.postflightElement(SaveInfo);
683 struct ScalarTraits<bool> {
684 static void output(const bool &, void*, llvm::raw_ostream &);
685 static StringRef input(StringRef, void*, bool &);
686 static bool mustQuote(StringRef) { return false; }
690 struct ScalarTraits<StringRef> {
691 static void output(const StringRef &, void*, llvm::raw_ostream &);
692 static StringRef input(StringRef, void*, StringRef &);
693 static bool mustQuote(StringRef S) { return needsQuotes(S); }
697 struct ScalarTraits<std::string> {
698 static void output(const std::string &, void*, llvm::raw_ostream &);
699 static StringRef input(StringRef, void*, std::string &);
700 static bool mustQuote(StringRef S) { return needsQuotes(S); }
704 struct ScalarTraits<uint8_t> {
705 static void output(const uint8_t &, void*, llvm::raw_ostream &);
706 static StringRef input(StringRef, void*, uint8_t &);
707 static bool mustQuote(StringRef) { return false; }
711 struct ScalarTraits<uint16_t> {
712 static void output(const uint16_t &, void*, llvm::raw_ostream &);
713 static StringRef input(StringRef, void*, uint16_t &);
714 static bool mustQuote(StringRef) { return false; }
718 struct ScalarTraits<uint32_t> {
719 static void output(const uint32_t &, void*, llvm::raw_ostream &);
720 static StringRef input(StringRef, void*, uint32_t &);
721 static bool mustQuote(StringRef) { return false; }
725 struct ScalarTraits<uint64_t> {
726 static void output(const uint64_t &, void*, llvm::raw_ostream &);
727 static StringRef input(StringRef, void*, uint64_t &);
728 static bool mustQuote(StringRef) { return false; }
732 struct ScalarTraits<int8_t> {
733 static void output(const int8_t &, void*, llvm::raw_ostream &);
734 static StringRef input(StringRef, void*, int8_t &);
735 static bool mustQuote(StringRef) { return false; }
739 struct ScalarTraits<int16_t> {
740 static void output(const int16_t &, void*, llvm::raw_ostream &);
741 static StringRef input(StringRef, void*, int16_t &);
742 static bool mustQuote(StringRef) { return false; }
746 struct ScalarTraits<int32_t> {
747 static void output(const int32_t &, void*, llvm::raw_ostream &);
748 static StringRef input(StringRef, void*, int32_t &);
749 static bool mustQuote(StringRef) { return false; }
753 struct ScalarTraits<int64_t> {
754 static void output(const int64_t &, void*, llvm::raw_ostream &);
755 static StringRef input(StringRef, void*, int64_t &);
756 static bool mustQuote(StringRef) { return false; }
760 struct ScalarTraits<float> {
761 static void output(const float &, void*, llvm::raw_ostream &);
762 static StringRef input(StringRef, void*, float &);
763 static bool mustQuote(StringRef) { return false; }
767 struct ScalarTraits<double> {
768 static void output(const double &, void*, llvm::raw_ostream &);
769 static StringRef input(StringRef, void*, double &);
770 static bool mustQuote(StringRef) { return false; }
775 // Utility for use within MappingTraits<>::mapping() method
776 // to [de]normalize an object for use with YAML conversion.
777 template <typename TNorm, typename TFinal>
778 struct MappingNormalization {
779 MappingNormalization(IO &i_o, TFinal &Obj)
780 : io(i_o), BufPtr(NULL), Result(Obj) {
781 if ( io.outputting() ) {
782 BufPtr = new (&Buffer) TNorm(io, Obj);
785 BufPtr = new (&Buffer) TNorm(io);
789 ~MappingNormalization() {
790 if ( ! io.outputting() ) {
791 Result = BufPtr->denormalize(io);
796 TNorm* operator->() { return BufPtr; }
799 typedef llvm::AlignedCharArrayUnion<TNorm> Storage;
809 // Utility for use within MappingTraits<>::mapping() method
810 // to [de]normalize an object for use with YAML conversion.
811 template <typename TNorm, typename TFinal>
812 struct MappingNormalizationHeap {
813 MappingNormalizationHeap(IO &i_o, TFinal &Obj)
814 : io(i_o), BufPtr(NULL), Result(Obj) {
815 if ( io.outputting() ) {
816 BufPtr = new (&Buffer) TNorm(io, Obj);
819 BufPtr = new TNorm(io);
823 ~MappingNormalizationHeap() {
824 if ( io.outputting() ) {
828 Result = BufPtr->denormalize(io);
832 TNorm* operator->() { return BufPtr; }
835 typedef llvm::AlignedCharArrayUnion<TNorm> Storage;
846 /// The Input class is used to parse a yaml document into in-memory structs
849 /// It works by using YAMLParser to do a syntax parse of the entire yaml
850 /// document, then the Input class builds a graph of HNodes which wraps
851 /// each yaml Node. The extra layer is buffering. The low level yaml
852 /// parser only lets you look at each node once. The buffering layer lets
853 /// you search and interate multiple times. This is necessary because
854 /// the mapRequired() method calls may not be in the same order
855 /// as the keys in the document.
857 class Input : public IO {
859 // Construct a yaml Input object from a StringRef and optional
860 // user-data. The DiagHandler can be specified to provide
861 // alternative error reporting.
862 Input(StringRef InputContent,
863 void *Ctxt = nullptr,
864 SourceMgr::DiagHandlerTy DiagHandler = nullptr,
865 void *DiagHandlerCtxt = nullptr);
868 // Check if there was an syntax or semantic error during parsing.
869 llvm::error_code error();
872 bool outputting() override;
873 bool mapTag(StringRef, bool) override;
874 void beginMapping() override;
875 void endMapping() override;
876 bool preflightKey(const char *, bool, bool, bool &, void *&) override;
877 void postflightKey(void *) override;
878 unsigned beginSequence() override;
879 void endSequence() override;
880 bool preflightElement(unsigned index, void *&) override;
881 void postflightElement(void *) override;
882 unsigned beginFlowSequence() override;
883 bool preflightFlowElement(unsigned , void *&) override;
884 void postflightFlowElement(void *) override;
885 void endFlowSequence() override;
886 void beginEnumScalar() override;
887 bool matchEnumScalar(const char*, bool) override;
888 void endEnumScalar() override;
889 bool beginBitSetScalar(bool &) override;
890 bool bitSetMatch(const char *, bool ) override;
891 void endBitSetScalar() override;
892 void scalarString(StringRef &, bool) override;
893 void setError(const Twine &message) override;
894 bool canElideEmptySequence() override;
897 virtual void anchor();
899 HNode(Node *n) : _node(n) { }
901 static inline bool classof(const HNode *) { return true; }
906 class EmptyHNode : public HNode {
907 void anchor() override;
909 EmptyHNode(Node *n) : HNode(n) { }
910 static inline bool classof(const HNode *n) {
911 return NullNode::classof(n->_node);
913 static inline bool classof(const EmptyHNode *) { return true; }
916 class ScalarHNode : public HNode {
917 void anchor() override;
919 ScalarHNode(Node *n, StringRef s) : HNode(n), _value(s) { }
921 StringRef value() const { return _value; }
923 static inline bool classof(const HNode *n) {
924 return ScalarNode::classof(n->_node);
926 static inline bool classof(const ScalarHNode *) { return true; }
931 class MapHNode : public HNode {
933 MapHNode(Node *n) : HNode(n) { }
936 static inline bool classof(const HNode *n) {
937 return MappingNode::classof(n->_node);
939 static inline bool classof(const MapHNode *) { return true; }
941 typedef llvm::StringMap<HNode*> NameToNode;
943 bool isValidKey(StringRef key);
946 llvm::SmallVector<const char*, 6> ValidKeys;
949 class SequenceHNode : public HNode {
951 SequenceHNode(Node *n) : HNode(n) { }
952 virtual ~SequenceHNode();
954 static inline bool classof(const HNode *n) {
955 return SequenceNode::classof(n->_node);
957 static inline bool classof(const SequenceHNode *) { return true; }
959 std::vector<HNode*> Entries;
962 Input::HNode *createHNodes(Node *node);
963 void setError(HNode *hnode, const Twine &message);
964 void setError(Node *node, const Twine &message);
968 // These are only used by operator>>. They could be private
969 // if those templated things could be made friends.
970 bool setCurrentDocument();
974 llvm::SourceMgr SrcMgr; // must be before Strm
975 std::unique_ptr<llvm::yaml::Stream> Strm;
976 std::unique_ptr<HNode> TopNode;
978 llvm::BumpPtrAllocator StringAllocator;
979 llvm::yaml::document_iterator DocIterator;
980 std::vector<bool> BitValuesUsed;
982 bool ScalarMatchFound;
989 /// The Output class is used to generate a yaml document from in-memory structs
992 class Output : public IO {
994 Output(llvm::raw_ostream &, void *Ctxt=nullptr);
997 bool outputting() override;
998 bool mapTag(StringRef, bool) override;
999 void beginMapping() override;
1000 void endMapping() override;
1001 bool preflightKey(const char *key, bool, bool, bool &, void *&) override;
1002 void postflightKey(void *) override;
1003 unsigned beginSequence() override;
1004 void endSequence() override;
1005 bool preflightElement(unsigned, void *&) override;
1006 void postflightElement(void *) override;
1007 unsigned beginFlowSequence() override;
1008 bool preflightFlowElement(unsigned, void *&) override;
1009 void postflightFlowElement(void *) override;
1010 void endFlowSequence() override;
1011 void beginEnumScalar() override;
1012 bool matchEnumScalar(const char*, bool) override;
1013 void endEnumScalar() override;
1014 bool beginBitSetScalar(bool &) override;
1015 bool bitSetMatch(const char *, bool ) override;
1016 void endBitSetScalar() override;
1017 void scalarString(StringRef &, bool) override;
1018 void setError(const Twine &message) override;
1019 bool canElideEmptySequence() override;
1021 // These are only used by operator<<. They could be private
1022 // if that templated operator could be made a friend.
1023 void beginDocuments();
1024 bool preflightDocument(unsigned);
1025 void postflightDocument();
1026 void endDocuments();
1029 void output(StringRef s);
1030 void outputUpToEndOfLine(StringRef s);
1031 void newLineCheck();
1032 void outputNewLine();
1033 void paddedKey(StringRef key);
1035 enum InState { inSeq, inFlowSeq, inMapFirstKey, inMapOtherKey };
1037 llvm::raw_ostream &Out;
1038 SmallVector<InState, 8> StateStack;
1040 int ColumnAtFlowStart;
1041 bool NeedBitValueComma;
1042 bool NeedFlowSequenceComma;
1043 bool EnumerationMatchFound;
1050 /// YAML I/O does conversion based on types. But often native data types
1051 /// are just a typedef of built in intergral types (e.g. int). But the C++
1052 /// type matching system sees through the typedef and all the typedefed types
1053 /// look like a built in type. This will cause the generic YAML I/O conversion
1054 /// to be used. To provide better control over the YAML conversion, you can
1055 /// use this macro instead of typedef. It will create a class with one field
1056 /// and automatic conversion operators to and from the base type.
1057 /// Based on BOOST_STRONG_TYPEDEF
1058 #define LLVM_YAML_STRONG_TYPEDEF(_base, _type) \
1061 _type(const _base v) : value(v) { } \
1062 _type(const _type &v) : value(v.value) {} \
1063 _type &operator=(const _type &rhs) { value = rhs.value; return *this; }\
1064 _type &operator=(const _base &rhs) { value = rhs; return *this; } \
1065 operator const _base & () const { return value; } \
1066 bool operator==(const _type &rhs) const { return value == rhs.value; } \
1067 bool operator==(const _base &rhs) const { return value == rhs; } \
1068 bool operator<(const _type &rhs) const { return value < rhs.value; } \
1075 /// Use these types instead of uintXX_t in any mapping to have
1076 /// its yaml output formatted as hexadecimal.
1078 LLVM_YAML_STRONG_TYPEDEF(uint8_t, Hex8)
1079 LLVM_YAML_STRONG_TYPEDEF(uint16_t, Hex16)
1080 LLVM_YAML_STRONG_TYPEDEF(uint32_t, Hex32)
1081 LLVM_YAML_STRONG_TYPEDEF(uint64_t, Hex64)
1085 struct ScalarTraits<Hex8> {
1086 static void output(const Hex8 &, void*, llvm::raw_ostream &);
1087 static StringRef input(StringRef, void*, Hex8 &);
1088 static bool mustQuote(StringRef) { return false; }
1092 struct ScalarTraits<Hex16> {
1093 static void output(const Hex16 &, void*, llvm::raw_ostream &);
1094 static StringRef input(StringRef, void*, Hex16 &);
1095 static bool mustQuote(StringRef) { return false; }
1099 struct ScalarTraits<Hex32> {
1100 static void output(const Hex32 &, void*, llvm::raw_ostream &);
1101 static StringRef input(StringRef, void*, Hex32 &);
1102 static bool mustQuote(StringRef) { return false; }
1106 struct ScalarTraits<Hex64> {
1107 static void output(const Hex64 &, void*, llvm::raw_ostream &);
1108 static StringRef input(StringRef, void*, Hex64 &);
1109 static bool mustQuote(StringRef) { return false; }
1113 // Define non-member operator>> so that Input can stream in a document list.
1114 template <typename T>
1116 typename std::enable_if<has_DocumentListTraits<T>::value, Input &>::type
1117 operator>>(Input &yin, T &docList) {
1119 while ( yin.setCurrentDocument() ) {
1120 yamlize(yin, DocumentListTraits<T>::element(yin, docList, i), true);
1129 // Define non-member operator>> so that Input can stream in a map as a document.
1130 template <typename T>
1132 typename std::enable_if<has_MappingTraits<T>::value, Input &>::type
1133 operator>>(Input &yin, T &docMap) {
1134 yin.setCurrentDocument();
1135 yamlize(yin, docMap, true);
1139 // Define non-member operator>> so that Input can stream in a sequence as
1141 template <typename T>
1143 typename std::enable_if<has_SequenceTraits<T>::value, Input &>::type
1144 operator>>(Input &yin, T &docSeq) {
1145 if (yin.setCurrentDocument())
1146 yamlize(yin, docSeq, true);
1150 // Provide better error message about types missing a trait specialization
1151 template <typename T>
1153 typename std::enable_if<missingTraits<T>::value, Input &>::type
1154 operator>>(Input &yin, T &docSeq) {
1155 char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
1160 // Define non-member operator<< so that Output can stream out document list.
1161 template <typename T>
1163 typename std::enable_if<has_DocumentListTraits<T>::value, Output &>::type
1164 operator<<(Output &yout, T &docList) {
1165 yout.beginDocuments();
1166 const size_t count = DocumentListTraits<T>::size(yout, docList);
1167 for(size_t i=0; i < count; ++i) {
1168 if ( yout.preflightDocument(i) ) {
1169 yamlize(yout, DocumentListTraits<T>::element(yout, docList, i), true);
1170 yout.postflightDocument();
1173 yout.endDocuments();
1177 // Define non-member operator<< so that Output can stream out a map.
1178 template <typename T>
1180 typename std::enable_if<has_MappingTraits<T>::value, Output &>::type
1181 operator<<(Output &yout, T &map) {
1182 yout.beginDocuments();
1183 if ( yout.preflightDocument(0) ) {
1184 yamlize(yout, map, true);
1185 yout.postflightDocument();
1187 yout.endDocuments();
1191 // Define non-member operator<< so that Output can stream out a sequence.
1192 template <typename T>
1194 typename std::enable_if<has_SequenceTraits<T>::value, Output &>::type
1195 operator<<(Output &yout, T &seq) {
1196 yout.beginDocuments();
1197 if ( yout.preflightDocument(0) ) {
1198 yamlize(yout, seq, true);
1199 yout.postflightDocument();
1201 yout.endDocuments();
1205 // Provide better error message about types missing a trait specialization
1206 template <typename T>
1208 typename std::enable_if<missingTraits<T>::value, Output &>::type
1209 operator<<(Output &yout, T &seq) {
1210 char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
1219 /// Utility for declaring that a std::vector of a particular type
1220 /// should be considered a YAML sequence.
1221 #define LLVM_YAML_IS_SEQUENCE_VECTOR(_type) \
1225 struct SequenceTraits< std::vector<_type> > { \
1226 static size_t size(IO &io, std::vector<_type> &seq) { \
1227 return seq.size(); \
1229 static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\
1230 if ( index >= seq.size() ) \
1231 seq.resize(index+1); \
1232 return seq[index]; \
1238 /// Utility for declaring that a std::vector of a particular type
1239 /// should be considered a YAML flow sequence.
1240 #define LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(_type) \
1244 struct SequenceTraits< std::vector<_type> > { \
1245 static size_t size(IO &io, std::vector<_type> &seq) { \
1246 return seq.size(); \
1248 static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\
1249 (void)flow; /* Remove this workaround after PR17897 is fixed */ \
1250 if ( index >= seq.size() ) \
1251 seq.resize(index+1); \
1252 return seq[index]; \
1254 static const bool flow = true; \
1259 /// Utility for declaring that a std::vector of a particular type
1260 /// should be considered a YAML document list.
1261 #define LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(_type) \
1265 struct DocumentListTraits< std::vector<_type> > { \
1266 static size_t size(IO &io, std::vector<_type> &seq) { \
1267 return seq.size(); \
1269 static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\
1270 if ( index >= seq.size() ) \
1271 seq.resize(index+1); \
1272 return seq[index]; \
1280 #endif // LLVM_SUPPORT_YAMLTRAITS_H