14ca2db9326e3a95224ad9aea5a9221fcfef4c7f
[oota-llvm.git] / include / llvm / Support / YAMLTraits.h
1 //===- llvm/Support/YAMLTraits.h --------------------------------*- C++ -*-===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #ifndef LLVM_SUPPORT_YAMLTRAITS_H
11 #define LLVM_SUPPORT_YAMLTRAITS_H
12
13
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 <system_error>
28
29 namespace llvm {
30 namespace yaml {
31
32
33 /// This class should be specialized by any type that needs to be converted
34 /// to/from a YAML mapping.  For example:
35 ///
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);
41 ///       }
42 ///     };
43 template<class T>
44 struct MappingTraits {
45   // Must provide:
46   // static void mapping(IO &io, T &fields);
47   // Optionally may provide:
48   // static StringRef validate(IO &io, T &fields);
49 };
50
51
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:
55 ///
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);
61 ///         }
62 ///       };
63 template<typename T>
64 struct ScalarEnumerationTraits {
65   // Must provide:
66   // static void enumeration(IO &io, T &value);
67 };
68
69
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:
73 ///
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);
79 ///        }
80 ///      };
81 template<typename T>
82 struct ScalarBitSetTraits {
83   // Must provide:
84   // static void bitset(IO &io, T &value);
85 };
86
87
88 /// This class should be specialized by type that requires custom conversion
89 /// to/from a yaml scalar.  For example:
90 ///
91 ///    template<>
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);
96 ///      }
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();
101 ///      }
102 ///      static bool mustQuote(StringRef) { return true; }
103 ///    };
104 template<typename T>
105 struct ScalarTraits {
106   // Must provide:
107   //
108   // Function to write the value as a string:
109   //static void output(const T &value, void *ctxt, llvm::raw_ostream &out);
110   //
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);
114   //
115   // Function to determine if the value should be quoted.
116   //static bool mustQuote(StringRef);
117 };
118
119
120 /// This class should be specialized by any type that needs to be converted
121 /// to/from a YAML sequence.  For example:
122 ///
123 ///    template<>
124 ///    struct SequenceTraits< std::vector<MyType> > {
125 ///      static size_t size(IO &io, std::vector<MyType> &seq) {
126 ///        return seq.size();
127 ///      }
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];
132 ///      }
133 ///    };
134 template<typename T>
135 struct SequenceTraits {
136   // Must provide:
137   // static size_t size(IO &io, T &seq);
138   // static T::value_type& element(IO &io, T &seq, size_t index);
139   //
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;
143 };
144
145
146 /// This class should be specialized by any type that needs to be converted
147 /// to/from a list of YAML documents.
148 template<typename T>
149 struct DocumentListTraits {
150   // Must provide:
151   // static size_t size(IO &io, T &seq);
152   // static T::value_type& element(IO &io, T &seq, size_t index);
153 };
154
155
156 // Only used by compiler if both template types are the same
157 template <typename T, T>
158 struct SameType;
159
160 // Only used for better diagnostics of missing traits
161 template <typename T>
162 struct MissingTrait;
163
164
165
166 // Test if ScalarEnumerationTraits<T> is defined on type T.
167 template <class T>
168 struct has_ScalarEnumerationTraits
169 {
170   typedef void (*Signature_enumeration)(class IO&, T&);
171
172   template <typename U>
173   static char test(SameType<Signature_enumeration, &U::enumeration>*);
174
175   template <typename U>
176   static double test(...);
177
178 public:
179   static bool const value =
180     (sizeof(test<ScalarEnumerationTraits<T> >(nullptr)) == 1);
181 };
182
183
184 // Test if ScalarBitSetTraits<T> is defined on type T.
185 template <class T>
186 struct has_ScalarBitSetTraits
187 {
188   typedef void (*Signature_bitset)(class IO&, T&);
189
190   template <typename U>
191   static char test(SameType<Signature_bitset, &U::bitset>*);
192
193   template <typename U>
194   static double test(...);
195
196 public:
197   static bool const value = (sizeof(test<ScalarBitSetTraits<T> >(nullptr)) == 1);
198 };
199
200
201 // Test if ScalarTraits<T> is defined on type T.
202 template <class T>
203 struct has_ScalarTraits
204 {
205   typedef StringRef (*Signature_input)(StringRef, void*, T&);
206   typedef void (*Signature_output)(const T&, void*, llvm::raw_ostream&);
207   typedef bool (*Signature_mustQuote)(StringRef);
208
209   template <typename U>
210   static char test(SameType<Signature_input, &U::input> *,
211                    SameType<Signature_output, &U::output> *,
212                    SameType<Signature_mustQuote, &U::mustQuote> *);
213
214   template <typename U>
215   static double test(...);
216
217 public:
218   static bool const value =
219       (sizeof(test<ScalarTraits<T>>(nullptr, nullptr, nullptr)) == 1);
220 };
221
222
223 // Test if MappingTraits<T> is defined on type T.
224 template <class T>
225 struct has_MappingTraits
226 {
227   typedef void (*Signature_mapping)(class IO&, T&);
228
229   template <typename U>
230   static char test(SameType<Signature_mapping, &U::mapping>*);
231
232   template <typename U>
233   static double test(...);
234
235 public:
236   static bool const value = (sizeof(test<MappingTraits<T> >(nullptr)) == 1);
237 };
238
239 // Test if MappingTraits<T>::validate() is defined on type T.
240 template <class T>
241 struct has_MappingValidateTraits
242 {
243   typedef StringRef (*Signature_validate)(class IO&, T&);
244
245   template <typename U>
246   static char test(SameType<Signature_validate, &U::validate>*);
247
248   template <typename U>
249   static double test(...);
250
251 public:
252   static bool const value = (sizeof(test<MappingTraits<T> >(nullptr)) == 1);
253 };
254
255
256
257 // Test if SequenceTraits<T> is defined on type T.
258 template <class T>
259 struct has_SequenceMethodTraits
260 {
261   typedef size_t (*Signature_size)(class IO&, T&);
262
263   template <typename U>
264   static char test(SameType<Signature_size, &U::size>*);
265
266   template <typename U>
267   static double test(...);
268
269 public:
270   static bool const value =  (sizeof(test<SequenceTraits<T> >(nullptr)) == 1);
271 };
272
273
274 // has_FlowTraits<int> will cause an error with some compilers because
275 // it subclasses int.  Using this wrapper only instantiates the
276 // real has_FlowTraits only if the template type is a class.
277 template <typename T, bool Enabled = std::is_class<T>::value>
278 class has_FlowTraits
279 {
280 public:
281    static const bool value = false;
282 };
283
284 // Some older gcc compilers don't support straight forward tests
285 // for members, so test for ambiguity cause by the base and derived
286 // classes both defining the member.
287 template <class T>
288 struct has_FlowTraits<T, true>
289 {
290   struct Fallback { bool flow; };
291   struct Derived : T, Fallback { };
292
293   template<typename C>
294   static char (&f(SameType<bool Fallback::*, &C::flow>*))[1];
295
296   template<typename C>
297   static char (&f(...))[2];
298
299 public:
300   static bool const value = sizeof(f<Derived>(nullptr)) == 2;
301 };
302
303
304
305 // Test if SequenceTraits<T> is defined on type T
306 template<typename T>
307 struct has_SequenceTraits : public std::integral_constant<bool,
308                                       has_SequenceMethodTraits<T>::value > { };
309
310
311 // Test if DocumentListTraits<T> is defined on type T
312 template <class T>
313 struct has_DocumentListTraits
314 {
315   typedef size_t (*Signature_size)(class IO&, T&);
316
317   template <typename U>
318   static char test(SameType<Signature_size, &U::size>*);
319
320   template <typename U>
321   static double test(...);
322
323 public:
324   static bool const value = (sizeof(test<DocumentListTraits<T> >(nullptr))==1);
325 };
326
327 inline bool isNumber(StringRef S) {
328   static const char OctalChars[] = "01234567";
329   if (S.startswith("0") &&
330       S.drop_front().find_first_not_of(OctalChars) == StringRef::npos)
331     return true;
332
333   if (S.startswith("0o") &&
334       S.drop_front(2).find_first_not_of(OctalChars) == StringRef::npos)
335     return true;
336
337   static const char HexChars[] = "0123456789abcdefABCDEF";
338   if (S.startswith("0x") &&
339       S.drop_front(2).find_first_not_of(HexChars) == StringRef::npos)
340     return true;
341
342   static const char DecChars[] = "0123456789";
343   if (S.find_first_not_of(DecChars) == StringRef::npos)
344     return true;
345
346   if (S.equals(".inf") || S.equals(".Inf") || S.equals(".INF"))
347     return true;
348
349   Regex FloatMatcher("^(\\.[0-9]+|[0-9]+(\\.[0-9]*)?)([eE][-+]?[0-9]+)?$");
350   if (FloatMatcher.match(S))
351     return true;
352
353   return false;
354 }
355
356 inline bool isNumeric(StringRef S) {
357   if ((S.front() == '-' || S.front() == '+') && isNumber(S.drop_front()))
358     return true;
359
360   if (isNumber(S))
361     return true;
362
363   if (S.equals(".nan") || S.equals(".NaN") || S.equals(".NAN"))
364     return true;
365
366   return false;
367 }
368
369 inline bool isNull(StringRef S) {
370   return S.equals("null") || S.equals("Null") || S.equals("NULL") ||
371          S.equals("~");
372 }
373
374 inline bool isBool(StringRef S) {
375   return S.equals("true") || S.equals("True") || S.equals("TRUE") ||
376          S.equals("false") || S.equals("False") || S.equals("FALSE");
377 }
378
379 inline bool needsQuotes(StringRef S) {
380   if (S.empty())
381     return true;
382   if (isspace(S.front()) || isspace(S.back()))
383     return true;
384   if (S.front() == ',')
385     return true;
386
387   static const char ScalarSafeChars[] =
388       "abcdefghijklmnopqrstuvwxyz"
389       "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-/^., \t";
390   if (S.find_first_not_of(ScalarSafeChars) != StringRef::npos)
391     return true;
392
393   if (isNull(S))
394     return true;
395   if (isBool(S))
396     return true;
397   if (isNumeric(S))
398     return true;
399
400   return false;
401 }
402
403
404 template<typename T>
405 struct missingTraits : public std::integral_constant<bool,
406                                          !has_ScalarEnumerationTraits<T>::value
407                                       && !has_ScalarBitSetTraits<T>::value
408                                       && !has_ScalarTraits<T>::value
409                                       && !has_MappingTraits<T>::value
410                                       && !has_SequenceTraits<T>::value
411                                       && !has_DocumentListTraits<T>::value >  {};
412
413 template<typename T>
414 struct validatedMappingTraits : public std::integral_constant<bool,
415                                        has_MappingTraits<T>::value
416                                     && has_MappingValidateTraits<T>::value> {};
417
418 template<typename T>
419 struct unvalidatedMappingTraits : public std::integral_constant<bool,
420                                         has_MappingTraits<T>::value
421                                     && !has_MappingValidateTraits<T>::value> {};
422 // Base class for Input and Output.
423 class IO {
424 public:
425
426   IO(void *Ctxt=nullptr);
427   virtual ~IO();
428
429   virtual bool outputting() = 0;
430
431   virtual unsigned beginSequence() = 0;
432   virtual bool preflightElement(unsigned, void *&) = 0;
433   virtual void postflightElement(void*) = 0;
434   virtual void endSequence() = 0;
435   virtual bool canElideEmptySequence() = 0;
436
437   virtual unsigned beginFlowSequence() = 0;
438   virtual bool preflightFlowElement(unsigned, void *&) = 0;
439   virtual void postflightFlowElement(void*) = 0;
440   virtual void endFlowSequence() = 0;
441
442   virtual bool mapTag(StringRef Tag, bool Default=false) = 0;
443   virtual void beginMapping() = 0;
444   virtual void endMapping() = 0;
445   virtual bool preflightKey(const char*, bool, bool, bool &, void *&) = 0;
446   virtual void postflightKey(void*) = 0;
447
448   virtual void beginEnumScalar() = 0;
449   virtual bool matchEnumScalar(const char*, bool) = 0;
450   virtual void endEnumScalar() = 0;
451
452   virtual bool beginBitSetScalar(bool &) = 0;
453   virtual bool bitSetMatch(const char*, bool) = 0;
454   virtual void endBitSetScalar() = 0;
455
456   virtual void scalarString(StringRef &, bool) = 0;
457
458   virtual void setError(const Twine &) = 0;
459
460   template <typename T>
461   void enumCase(T &Val, const char* Str, const T ConstVal) {
462     if ( matchEnumScalar(Str, outputting() && Val == ConstVal) ) {
463       Val = ConstVal;
464     }
465   }
466
467   // allow anonymous enum values to be used with LLVM_YAML_STRONG_TYPEDEF
468   template <typename T>
469   void enumCase(T &Val, const char* Str, const uint32_t ConstVal) {
470     if ( matchEnumScalar(Str, outputting() && Val == static_cast<T>(ConstVal)) ) {
471       Val = ConstVal;
472     }
473   }
474
475   template <typename T>
476   void bitSetCase(T &Val, const char* Str, const T ConstVal) {
477     if ( bitSetMatch(Str, outputting() && (Val & ConstVal) == ConstVal) ) {
478       Val = Val | ConstVal;
479     }
480   }
481
482   // allow anonymous enum values to be used with LLVM_YAML_STRONG_TYPEDEF
483   template <typename T>
484   void bitSetCase(T &Val, const char* Str, const uint32_t ConstVal) {
485     if ( bitSetMatch(Str, outputting() && (Val & ConstVal) == ConstVal) ) {
486       Val = Val | ConstVal;
487     }
488   }
489
490   template <typename T>
491   void maskedBitSetCase(T &Val, const char *Str, T ConstVal, T Mask) {
492     if (bitSetMatch(Str, outputting() && (Val & Mask) == ConstVal))
493       Val = Val | ConstVal;
494   }
495
496   template <typename T>
497   void maskedBitSetCase(T &Val, const char *Str, uint32_t ConstVal,
498                         uint32_t Mask) {
499     if (bitSetMatch(Str, outputting() && (Val & Mask) == ConstVal))
500       Val = Val | ConstVal;
501   }
502
503   void *getContext();
504   void setContext(void *);
505
506   template <typename T>
507   void mapRequired(const char* Key, T& Val) {
508     this->processKey(Key, Val, true);
509   }
510
511   template <typename T>
512   typename std::enable_if<has_SequenceTraits<T>::value,void>::type
513   mapOptional(const char* Key, T& Val) {
514     // omit key/value instead of outputting empty sequence
515     if ( this->canElideEmptySequence() && !(Val.begin() != Val.end()) )
516       return;
517     this->processKey(Key, Val, false);
518   }
519
520   template <typename T>
521   void mapOptional(const char* Key, Optional<T> &Val) {
522     processKeyWithDefault(Key, Val, Optional<T>(), /*Required=*/false);
523   }
524
525   template <typename T>
526   typename std::enable_if<!has_SequenceTraits<T>::value,void>::type
527   mapOptional(const char* Key, T& Val) {
528     this->processKey(Key, Val, false);
529   }
530
531   template <typename T>
532   void mapOptional(const char* Key, T& Val, const T& Default) {
533     this->processKeyWithDefault(Key, Val, Default, false);
534   }
535   
536 private:
537   template <typename T>
538   void processKeyWithDefault(const char *Key, Optional<T> &Val,
539                              const Optional<T> &DefaultValue, bool Required) {
540     assert(DefaultValue.hasValue() == false &&
541            "Optional<T> shouldn't have a value!");
542     void *SaveInfo;
543     bool UseDefault;
544     const bool sameAsDefault = outputting() && !Val.hasValue();
545     if (!outputting() && !Val.hasValue())
546       Val = T();
547     if (this->preflightKey(Key, Required, sameAsDefault, UseDefault,
548                            SaveInfo)) {
549       yamlize(*this, Val.getValue(), Required);
550       this->postflightKey(SaveInfo);
551     } else {
552       if (UseDefault)
553         Val = DefaultValue;
554     }
555   }
556
557   template <typename T>
558   void processKeyWithDefault(const char *Key, T &Val, const T& DefaultValue,
559                                                                 bool Required) {
560     void *SaveInfo;
561     bool UseDefault;
562     const bool sameAsDefault = outputting() && Val == DefaultValue;
563     if ( this->preflightKey(Key, Required, sameAsDefault, UseDefault,
564                                                                   SaveInfo) ) {
565       yamlize(*this, Val, Required);
566       this->postflightKey(SaveInfo);
567     }
568     else {
569       if ( UseDefault )
570         Val = DefaultValue;
571     }
572   }
573
574   template <typename T>
575   void processKey(const char *Key, T &Val, bool Required) {
576     void *SaveInfo;
577     bool UseDefault;
578     if ( this->preflightKey(Key, Required, false, UseDefault, SaveInfo) ) {
579       yamlize(*this, Val, Required);
580       this->postflightKey(SaveInfo);
581     }
582   }
583
584 private:
585   void  *Ctxt;
586 };
587
588
589
590 template<typename T>
591 typename std::enable_if<has_ScalarEnumerationTraits<T>::value,void>::type
592 yamlize(IO &io, T &Val, bool) {
593   io.beginEnumScalar();
594   ScalarEnumerationTraits<T>::enumeration(io, Val);
595   io.endEnumScalar();
596 }
597
598 template<typename T>
599 typename std::enable_if<has_ScalarBitSetTraits<T>::value,void>::type
600 yamlize(IO &io, T &Val, bool) {
601   bool DoClear;
602   if ( io.beginBitSetScalar(DoClear) ) {
603     if ( DoClear )
604       Val = static_cast<T>(0);
605     ScalarBitSetTraits<T>::bitset(io, Val);
606     io.endBitSetScalar();
607   }
608 }
609
610
611 template<typename T>
612 typename std::enable_if<has_ScalarTraits<T>::value,void>::type
613 yamlize(IO &io, T &Val, bool) {
614   if ( io.outputting() ) {
615     llvm::string_ostream Buffer;
616     ScalarTraits<T>::output(Val, io.getContext(), Buffer);
617     StringRef Str = Buffer.str();
618     io.scalarString(Str, ScalarTraits<T>::mustQuote(Str));
619   }
620   else {
621     StringRef Str;
622     io.scalarString(Str, ScalarTraits<T>::mustQuote(Str));
623     StringRef Result = ScalarTraits<T>::input(Str, io.getContext(), Val);
624     if ( !Result.empty() ) {
625       io.setError(llvm::Twine(Result));
626     }
627   }
628 }
629
630
631 template<typename T>
632 typename std::enable_if<validatedMappingTraits<T>::value, void>::type
633 yamlize(IO &io, T &Val, bool) {
634   io.beginMapping();
635   if (io.outputting()) {
636     StringRef Err = MappingTraits<T>::validate(io, Val);
637     if (!Err.empty()) {
638       llvm::errs() << Err << "\n";
639       assert(Err.empty() && "invalid struct trying to be written as yaml");
640     }
641   }
642   MappingTraits<T>::mapping(io, Val);
643   if (!io.outputting()) {
644     StringRef Err = MappingTraits<T>::validate(io, Val);
645     if (!Err.empty())
646       io.setError(Err);
647   }
648   io.endMapping();
649 }
650
651 template<typename T>
652 typename std::enable_if<unvalidatedMappingTraits<T>::value, void>::type
653 yamlize(IO &io, T &Val, bool) {
654   io.beginMapping();
655   MappingTraits<T>::mapping(io, Val);
656   io.endMapping();
657 }
658
659 template<typename T>
660 typename std::enable_if<missingTraits<T>::value, void>::type
661 yamlize(IO &io, T &Val, bool) {
662   char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
663 }
664
665 template<typename T>
666 typename std::enable_if<has_SequenceTraits<T>::value,void>::type
667 yamlize(IO &io, T &Seq, bool) {
668   if ( has_FlowTraits< SequenceTraits<T> >::value ) {
669     unsigned incnt = io.beginFlowSequence();
670     unsigned count = io.outputting() ? SequenceTraits<T>::size(io, Seq) : incnt;
671     for(unsigned i=0; i < count; ++i) {
672       void *SaveInfo;
673       if ( io.preflightFlowElement(i, SaveInfo) ) {
674         yamlize(io, SequenceTraits<T>::element(io, Seq, i), true);
675         io.postflightFlowElement(SaveInfo);
676       }
677     }
678     io.endFlowSequence();
679   }
680   else {
681     unsigned incnt = io.beginSequence();
682     unsigned count = io.outputting() ? SequenceTraits<T>::size(io, Seq) : incnt;
683     for(unsigned i=0; i < count; ++i) {
684       void *SaveInfo;
685       if ( io.preflightElement(i, SaveInfo) ) {
686         yamlize(io, SequenceTraits<T>::element(io, Seq, i), true);
687         io.postflightElement(SaveInfo);
688       }
689     }
690     io.endSequence();
691   }
692 }
693
694
695 template<>
696 struct ScalarTraits<bool> {
697   static void output(const bool &, void*, llvm::raw_ostream &);
698   static StringRef input(StringRef, void*, bool &);
699   static bool mustQuote(StringRef) { return false; }
700 };
701
702 template<>
703 struct ScalarTraits<StringRef> {
704   static void output(const StringRef &, void*, llvm::raw_ostream &);
705   static StringRef input(StringRef, void*, StringRef &);
706   static bool mustQuote(StringRef S) { return needsQuotes(S); }
707 };
708  
709 template<>
710 struct ScalarTraits<std::string> {
711   static void output(const std::string &, void*, llvm::raw_ostream &);
712   static StringRef input(StringRef, void*, std::string &);
713   static bool mustQuote(StringRef S) { return needsQuotes(S); }
714 };
715
716 template<>
717 struct ScalarTraits<uint8_t> {
718   static void output(const uint8_t &, void*, llvm::raw_ostream &);
719   static StringRef input(StringRef, void*, uint8_t &);
720   static bool mustQuote(StringRef) { return false; }
721 };
722
723 template<>
724 struct ScalarTraits<uint16_t> {
725   static void output(const uint16_t &, void*, llvm::raw_ostream &);
726   static StringRef input(StringRef, void*, uint16_t &);
727   static bool mustQuote(StringRef) { return false; }
728 };
729
730 template<>
731 struct ScalarTraits<uint32_t> {
732   static void output(const uint32_t &, void*, llvm::raw_ostream &);
733   static StringRef input(StringRef, void*, uint32_t &);
734   static bool mustQuote(StringRef) { return false; }
735 };
736
737 template<>
738 struct ScalarTraits<uint64_t> {
739   static void output(const uint64_t &, void*, llvm::raw_ostream &);
740   static StringRef input(StringRef, void*, uint64_t &);
741   static bool mustQuote(StringRef) { return false; }
742 };
743
744 template<>
745 struct ScalarTraits<int8_t> {
746   static void output(const int8_t &, void*, llvm::raw_ostream &);
747   static StringRef input(StringRef, void*, int8_t &);
748   static bool mustQuote(StringRef) { return false; }
749 };
750
751 template<>
752 struct ScalarTraits<int16_t> {
753   static void output(const int16_t &, void*, llvm::raw_ostream &);
754   static StringRef input(StringRef, void*, int16_t &);
755   static bool mustQuote(StringRef) { return false; }
756 };
757
758 template<>
759 struct ScalarTraits<int32_t> {
760   static void output(const int32_t &, void*, llvm::raw_ostream &);
761   static StringRef input(StringRef, void*, int32_t &);
762   static bool mustQuote(StringRef) { return false; }
763 };
764
765 template<>
766 struct ScalarTraits<int64_t> {
767   static void output(const int64_t &, void*, llvm::raw_ostream &);
768   static StringRef input(StringRef, void*, int64_t &);
769   static bool mustQuote(StringRef) { return false; }
770 };
771
772 template<>
773 struct ScalarTraits<float> {
774   static void output(const float &, void*, llvm::raw_ostream &);
775   static StringRef input(StringRef, void*, float &);
776   static bool mustQuote(StringRef) { return false; }
777 };
778
779 template<>
780 struct ScalarTraits<double> {
781   static void output(const double &, void*, llvm::raw_ostream &);
782   static StringRef input(StringRef, void*, double &);
783   static bool mustQuote(StringRef) { return false; }
784 };
785
786
787
788 // Utility for use within MappingTraits<>::mapping() method
789 // to [de]normalize an object for use with YAML conversion.
790 template <typename TNorm, typename TFinal>
791 struct MappingNormalization {
792   MappingNormalization(IO &i_o, TFinal &Obj)
793       : io(i_o), BufPtr(nullptr), Result(Obj) {
794     if ( io.outputting() ) {
795       BufPtr = new (&Buffer) TNorm(io, Obj);
796     }
797     else {
798       BufPtr = new (&Buffer) TNorm(io);
799     }
800   }
801
802   ~MappingNormalization() {
803     if ( ! io.outputting() ) {
804       Result = BufPtr->denormalize(io);
805     }
806     BufPtr->~TNorm();
807   }
808
809   TNorm* operator->() { return BufPtr; }
810
811 private:
812   typedef llvm::AlignedCharArrayUnion<TNorm> Storage;
813
814   Storage       Buffer;
815   IO           &io;
816   TNorm        *BufPtr;
817   TFinal       &Result;
818 };
819
820
821
822 // Utility for use within MappingTraits<>::mapping() method
823 // to [de]normalize an object for use with YAML conversion.
824 template <typename TNorm, typename TFinal>
825 struct MappingNormalizationHeap {
826   MappingNormalizationHeap(IO &i_o, TFinal &Obj)
827     : io(i_o), BufPtr(NULL), Result(Obj) {
828     if ( io.outputting() ) {
829       BufPtr = new (&Buffer) TNorm(io, Obj);
830     }
831     else {
832       BufPtr = new TNorm(io);
833     }
834   }
835
836   ~MappingNormalizationHeap() {
837     if ( io.outputting() ) {
838       BufPtr->~TNorm();
839     }
840     else {
841       Result = BufPtr->denormalize(io);
842     }
843   }
844
845   TNorm* operator->() { return BufPtr; }
846
847 private:
848   typedef llvm::AlignedCharArrayUnion<TNorm> Storage;
849
850   Storage       Buffer;
851   IO           &io;
852   TNorm        *BufPtr;
853   TFinal       &Result;
854 };
855
856
857
858 ///
859 /// The Input class is used to parse a yaml document into in-memory structs
860 /// and vectors.
861 ///
862 /// It works by using YAMLParser to do a syntax parse of the entire yaml
863 /// document, then the Input class builds a graph of HNodes which wraps
864 /// each yaml Node.  The extra layer is buffering.  The low level yaml
865 /// parser only lets you look at each node once.  The buffering layer lets
866 /// you search and interate multiple times.  This is necessary because
867 /// the mapRequired() method calls may not be in the same order
868 /// as the keys in the document.
869 ///
870 class Input : public IO {
871 public:
872   // Construct a yaml Input object from a StringRef and optional
873   // user-data. The DiagHandler can be specified to provide
874   // alternative error reporting.
875   Input(StringRef InputContent,
876         void *Ctxt = nullptr,
877         SourceMgr::DiagHandlerTy DiagHandler = nullptr,
878         void *DiagHandlerCtxt = nullptr);
879   ~Input();
880
881   // Check if there was an syntax or semantic error during parsing.
882   std::error_code error();
883
884 private:
885   bool outputting() override;
886   bool mapTag(StringRef, bool) override;
887   void beginMapping() override;
888   void endMapping() override;
889   bool preflightKey(const char *, bool, bool, bool &, void *&) override;
890   void postflightKey(void *) override;
891   unsigned beginSequence() override;
892   void endSequence() override;
893   bool preflightElement(unsigned index, void *&) override;
894   void postflightElement(void *) override;
895   unsigned beginFlowSequence() override;
896   bool preflightFlowElement(unsigned , void *&) override;
897   void postflightFlowElement(void *) override;
898   void endFlowSequence() override;
899   void beginEnumScalar() override;
900   bool matchEnumScalar(const char*, bool) override;
901   void endEnumScalar() override;
902   bool beginBitSetScalar(bool &) override;
903   bool bitSetMatch(const char *, bool ) override;
904   void endBitSetScalar() override;
905   void scalarString(StringRef &, bool) override;
906   void setError(const Twine &message) override;
907   bool canElideEmptySequence() override;
908
909   class HNode {
910     virtual void anchor();
911   public:
912     HNode(Node *n) : _node(n) { }
913     virtual ~HNode() { }
914     static inline bool classof(const HNode *) { return true; }
915
916     Node *_node;
917   };
918
919   class EmptyHNode : public HNode {
920     void anchor() override;
921   public:
922     EmptyHNode(Node *n) : HNode(n) { }
923     static inline bool classof(const HNode *n) {
924       return NullNode::classof(n->_node);
925     }
926     static inline bool classof(const EmptyHNode *) { return true; }
927   };
928
929   class ScalarHNode : public HNode {
930     void anchor() override;
931   public:
932     ScalarHNode(Node *n, StringRef s) : HNode(n), _value(s) { }
933
934     StringRef value() const { return _value; }
935
936     static inline bool classof(const HNode *n) {
937       return ScalarNode::classof(n->_node);
938     }
939     static inline bool classof(const ScalarHNode *) { return true; }
940   protected:
941     StringRef _value;
942   };
943
944   class MapHNode : public HNode {
945   public:
946     MapHNode(Node *n) : HNode(n) { }
947     virtual ~MapHNode();
948
949     static inline bool classof(const HNode *n) {
950       return MappingNode::classof(n->_node);
951     }
952     static inline bool classof(const MapHNode *) { return true; }
953
954     typedef llvm::StringMap<HNode*> NameToNode;
955
956     bool isValidKey(StringRef key);
957
958     NameToNode                        Mapping;
959     llvm::SmallVector<const char*, 6> ValidKeys;
960   };
961
962   class SequenceHNode : public HNode {
963   public:
964     SequenceHNode(Node *n) : HNode(n) { }
965     virtual ~SequenceHNode();
966
967     static inline bool classof(const HNode *n) {
968       return SequenceNode::classof(n->_node);
969     }
970     static inline bool classof(const SequenceHNode *) { return true; }
971
972     std::vector<HNode*> Entries;
973   };
974
975   Input::HNode *createHNodes(Node *node);
976   void setError(HNode *hnode, const Twine &message);
977   void setError(Node *node, const Twine &message);
978
979
980 public:
981   // These are only used by operator>>. They could be private
982   // if those templated things could be made friends.
983   bool setCurrentDocument();
984   bool nextDocument();
985
986 private:
987   llvm::SourceMgr                     SrcMgr; // must be before Strm
988   std::unique_ptr<llvm::yaml::Stream> Strm;
989   std::unique_ptr<HNode>              TopNode;
990   std::error_code                     EC;
991   llvm::BumpPtrAllocator              StringAllocator;
992   llvm::yaml::document_iterator       DocIterator;
993   std::vector<bool>                   BitValuesUsed;
994   HNode                              *CurrentNode;
995   bool                                ScalarMatchFound;
996 };
997
998
999
1000
1001 ///
1002 /// The Output class is used to generate a yaml document from in-memory structs
1003 /// and vectors.
1004 ///
1005 class Output : public IO {
1006 public:
1007   Output(llvm::raw_ostream &, void *Ctxt=nullptr);
1008   virtual ~Output();
1009
1010   bool outputting() override;
1011   bool mapTag(StringRef, bool) override;
1012   void beginMapping() override;
1013   void endMapping() override;
1014   bool preflightKey(const char *key, bool, bool, bool &, void *&) override;
1015   void postflightKey(void *) override;
1016   unsigned beginSequence() override;
1017   void endSequence() override;
1018   bool preflightElement(unsigned, void *&) override;
1019   void postflightElement(void *) override;
1020   unsigned beginFlowSequence() override;
1021   bool preflightFlowElement(unsigned, void *&) override;
1022   void postflightFlowElement(void *) override;
1023   void endFlowSequence() override;
1024   void beginEnumScalar() override;
1025   bool matchEnumScalar(const char*, bool) override;
1026   void endEnumScalar() override;
1027   bool beginBitSetScalar(bool &) override;
1028   bool bitSetMatch(const char *, bool ) override;
1029   void endBitSetScalar() override;
1030   void scalarString(StringRef &, bool) override;
1031   void setError(const Twine &message) override;
1032   bool canElideEmptySequence() override;
1033 public:
1034   // These are only used by operator<<. They could be private
1035   // if that templated operator could be made a friend.
1036   void beginDocuments();
1037   bool preflightDocument(unsigned);
1038   void postflightDocument();
1039   void endDocuments();
1040
1041 private:
1042   void output(StringRef s);
1043   void outputUpToEndOfLine(StringRef s);
1044   void newLineCheck();
1045   void outputNewLine();
1046   void paddedKey(StringRef key);
1047
1048   enum InState { inSeq, inFlowSeq, inMapFirstKey, inMapOtherKey };
1049
1050   llvm::raw_ostream       &Out;
1051   SmallVector<InState, 8>  StateStack;
1052   int                      Column;
1053   int                      ColumnAtFlowStart;
1054   bool                     NeedBitValueComma;
1055   bool                     NeedFlowSequenceComma;
1056   bool                     EnumerationMatchFound;
1057   bool                     NeedsNewLine;
1058 };
1059
1060
1061
1062
1063 /// YAML I/O does conversion based on types. But often native data types
1064 /// are just a typedef of built in intergral types (e.g. int).  But the C++
1065 /// type matching system sees through the typedef and all the typedefed types
1066 /// look like a built in type. This will cause the generic YAML I/O conversion
1067 /// to be used. To provide better control over the YAML conversion, you can
1068 /// use this macro instead of typedef.  It will create a class with one field
1069 /// and automatic conversion operators to and from the base type.
1070 /// Based on BOOST_STRONG_TYPEDEF
1071 #define LLVM_YAML_STRONG_TYPEDEF(_base, _type)                                 \
1072     struct _type {                                                             \
1073         _type() { }                                                            \
1074         _type(const _base v) : value(v) { }                                    \
1075         _type(const _type &v) : value(v.value) {}                              \
1076         _type &operator=(const _type &rhs) { value = rhs.value; return *this; }\
1077         _type &operator=(const _base &rhs) { value = rhs; return *this; }      \
1078         operator const _base & () const { return value; }                      \
1079         bool operator==(const _type &rhs) const { return value == rhs.value; } \
1080         bool operator==(const _base &rhs) const { return value == rhs; }       \
1081         bool operator<(const _type &rhs) const { return value < rhs.value; }   \
1082         _base value;                                                           \
1083     };
1084
1085
1086
1087 ///
1088 /// Use these types instead of uintXX_t in any mapping to have
1089 /// its yaml output formatted as hexadecimal.
1090 ///
1091 LLVM_YAML_STRONG_TYPEDEF(uint8_t, Hex8)
1092 LLVM_YAML_STRONG_TYPEDEF(uint16_t, Hex16)
1093 LLVM_YAML_STRONG_TYPEDEF(uint32_t, Hex32)
1094 LLVM_YAML_STRONG_TYPEDEF(uint64_t, Hex64)
1095
1096
1097 template<>
1098 struct ScalarTraits<Hex8> {
1099   static void output(const Hex8 &, void*, llvm::raw_ostream &);
1100   static StringRef input(StringRef, void*, Hex8 &);
1101   static bool mustQuote(StringRef) { return false; }
1102 };
1103
1104 template<>
1105 struct ScalarTraits<Hex16> {
1106   static void output(const Hex16 &, void*, llvm::raw_ostream &);
1107   static StringRef input(StringRef, void*, Hex16 &);
1108   static bool mustQuote(StringRef) { return false; }
1109 };
1110
1111 template<>
1112 struct ScalarTraits<Hex32> {
1113   static void output(const Hex32 &, void*, llvm::raw_ostream &);
1114   static StringRef input(StringRef, void*, Hex32 &);
1115   static bool mustQuote(StringRef) { return false; }
1116 };
1117
1118 template<>
1119 struct ScalarTraits<Hex64> {
1120   static void output(const Hex64 &, void*, llvm::raw_ostream &);
1121   static StringRef input(StringRef, void*, Hex64 &);
1122   static bool mustQuote(StringRef) { return false; }
1123 };
1124
1125
1126 // Define non-member operator>> so that Input can stream in a document list.
1127 template <typename T>
1128 inline
1129 typename std::enable_if<has_DocumentListTraits<T>::value, Input &>::type
1130 operator>>(Input &yin, T &docList) {
1131   int i = 0;
1132   while ( yin.setCurrentDocument() ) {
1133     yamlize(yin, DocumentListTraits<T>::element(yin, docList, i), true);
1134     if ( yin.error() )
1135       return yin;
1136     yin.nextDocument();
1137     ++i;
1138   }
1139   return yin;
1140 }
1141
1142 // Define non-member operator>> so that Input can stream in a map as a document.
1143 template <typename T>
1144 inline
1145 typename std::enable_if<has_MappingTraits<T>::value, Input &>::type
1146 operator>>(Input &yin, T &docMap) {
1147   yin.setCurrentDocument();
1148   yamlize(yin, docMap, true);
1149   return yin;
1150 }
1151
1152 // Define non-member operator>> so that Input can stream in a sequence as
1153 // a document.
1154 template <typename T>
1155 inline
1156 typename std::enable_if<has_SequenceTraits<T>::value, Input &>::type
1157 operator>>(Input &yin, T &docSeq) {
1158   if (yin.setCurrentDocument())
1159     yamlize(yin, docSeq, true);
1160   return yin;
1161 }
1162
1163 // Provide better error message about types missing a trait specialization
1164 template <typename T>
1165 inline
1166 typename std::enable_if<missingTraits<T>::value, Input &>::type
1167 operator>>(Input &yin, T &docSeq) {
1168   char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
1169   return yin;
1170 }
1171
1172
1173 // Define non-member operator<< so that Output can stream out document list.
1174 template <typename T>
1175 inline
1176 typename std::enable_if<has_DocumentListTraits<T>::value, Output &>::type
1177 operator<<(Output &yout, T &docList) {
1178   yout.beginDocuments();
1179   const size_t count = DocumentListTraits<T>::size(yout, docList);
1180   for(size_t i=0; i < count; ++i) {
1181     if ( yout.preflightDocument(i) ) {
1182       yamlize(yout, DocumentListTraits<T>::element(yout, docList, i), true);
1183       yout.postflightDocument();
1184     }
1185   }
1186   yout.endDocuments();
1187   return yout;
1188 }
1189
1190 // Define non-member operator<< so that Output can stream out a map.
1191 template <typename T>
1192 inline
1193 typename std::enable_if<has_MappingTraits<T>::value, Output &>::type
1194 operator<<(Output &yout, T &map) {
1195   yout.beginDocuments();
1196   if ( yout.preflightDocument(0) ) {
1197     yamlize(yout, map, true);
1198     yout.postflightDocument();
1199   }
1200   yout.endDocuments();
1201   return yout;
1202 }
1203
1204 // Define non-member operator<< so that Output can stream out a sequence.
1205 template <typename T>
1206 inline
1207 typename std::enable_if<has_SequenceTraits<T>::value, Output &>::type
1208 operator<<(Output &yout, T &seq) {
1209   yout.beginDocuments();
1210   if ( yout.preflightDocument(0) ) {
1211     yamlize(yout, seq, true);
1212     yout.postflightDocument();
1213   }
1214   yout.endDocuments();
1215   return yout;
1216 }
1217
1218 // Provide better error message about types missing a trait specialization
1219 template <typename T>
1220 inline
1221 typename std::enable_if<missingTraits<T>::value, Output &>::type
1222 operator<<(Output &yout, T &seq) {
1223   char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
1224   return yout;
1225 }
1226
1227
1228 } // namespace yaml
1229 } // namespace llvm
1230
1231
1232 /// Utility for declaring that a std::vector of a particular type
1233 /// should be considered a YAML sequence.
1234 #define LLVM_YAML_IS_SEQUENCE_VECTOR(_type)                                 \
1235   namespace llvm {                                                          \
1236   namespace yaml {                                                          \
1237     template<>                                                              \
1238     struct SequenceTraits< std::vector<_type> > {                           \
1239       static size_t size(IO &io, std::vector<_type> &seq) {                 \
1240         return seq.size();                                                  \
1241       }                                                                     \
1242       static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\
1243         if ( index >= seq.size() )                                          \
1244           seq.resize(index+1);                                              \
1245         return seq[index];                                                  \
1246       }                                                                     \
1247     };                                                                      \
1248   }                                                                         \
1249   }
1250
1251 /// Utility for declaring that a std::vector of a particular type
1252 /// should be considered a YAML flow sequence.
1253 #define LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(_type)                            \
1254   namespace llvm {                                                          \
1255   namespace yaml {                                                          \
1256     template<>                                                              \
1257     struct SequenceTraits< std::vector<_type> > {                           \
1258       static size_t size(IO &io, std::vector<_type> &seq) {                 \
1259         return seq.size();                                                  \
1260       }                                                                     \
1261       static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\
1262         (void)flow; /* Remove this workaround after PR17897 is fixed */     \
1263         if ( index >= seq.size() )                                          \
1264           seq.resize(index+1);                                              \
1265         return seq[index];                                                  \
1266       }                                                                     \
1267       static const bool flow = true;                                        \
1268     };                                                                      \
1269   }                                                                         \
1270   }
1271
1272 /// Utility for declaring that a std::vector of a particular type
1273 /// should be considered a YAML document list.
1274 #define LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(_type)                            \
1275   namespace llvm {                                                          \
1276   namespace yaml {                                                          \
1277     template<>                                                              \
1278     struct DocumentListTraits< std::vector<_type> > {                       \
1279       static size_t size(IO &io, std::vector<_type> &seq) {                 \
1280         return seq.size();                                                  \
1281       }                                                                     \
1282       static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\
1283         if ( index >= seq.size() )                                          \
1284           seq.resize(index+1);                                              \
1285         return seq[index];                                                  \
1286       }                                                                     \
1287     };                                                                      \
1288   }                                                                         \
1289   }
1290
1291
1292
1293 #endif // LLVM_SUPPORT_YAMLTRAITS_H