Move all of the header files which are involved in modelling the LLVM IR
[oota-llvm.git] / include / llvm / Support / YAMLTraits.h
1 //===- llvm/Supporrt/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_YAML_TRAITS_H_
11 #define LLVM_YAML_TRAITS_H_
12
13
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/DenseMapInfo.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/SourceMgr.h"
23 #include "llvm/Support/YAMLParser.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Support/system_error.h"
26 #include "llvm/Support/type_traits.h"
27
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 ScalarBitSetTraits<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 };
48
49
50 /// This class should be specialized by any integral type that converts
51 /// to/from a YAML scalar where there is a one-to-one mapping between
52 /// in-memory values and a string in YAML.  For example:
53 ///
54 ///     struct ScalarEnumerationTraits<Colors> {
55 ///         static void enumeration(IO &io, Colors &value) {
56 ///           io.enumCase(value, "red",   cRed);
57 ///           io.enumCase(value, "blue",  cBlue);
58 ///           io.enumCase(value, "green", cGreen);
59 ///         }
60 ///       };
61 template<typename T>
62 struct ScalarEnumerationTraits {
63   // Must provide:
64   // static void enumeration(IO &io, T &value);
65 };
66
67
68 /// This class should be specialized by any integer type that is a union
69 /// of bit values and the YAML representation is a flow sequence of
70 /// strings.  For example:
71 ///
72 ///      struct ScalarBitSetTraits<MyFlags> {
73 ///        static void bitset(IO &io, MyFlags &value) {
74 ///          io.bitSetCase(value, "big",   flagBig);
75 ///          io.bitSetCase(value, "flat",  flagFlat);
76 ///          io.bitSetCase(value, "round", flagRound);
77 ///        }
78 ///      };
79 template<typename T>
80 struct ScalarBitSetTraits {
81   // Must provide:
82   // static void bitset(IO &io, T &value);
83 };
84
85
86 /// This class should be specialized by type that requires custom conversion
87 /// to/from a yaml scalar.  For example:
88 ///
89 ///    template<>
90 ///    struct ScalarTraits<MyType> {
91 ///      static void output(const MyType &val, void*, llvm::raw_ostream &out) {
92 ///        // stream out custom formatting
93 ///        out << llvm::format("%x", val);
94 ///      }
95 ///      static StringRef input(StringRef scalar, void*, MyType &value) {
96 ///        // parse scalar and set `value`
97 ///        // return empty string on success, or error string
98 ///        return StringRef();
99 ///      }
100 ///    };
101 template<typename T>
102 struct ScalarTraits {
103   // Must provide:
104   //
105   // Function to write the value as a string:
106   //static void output(const T &value, void *ctxt, llvm::raw_ostream &out);
107   //
108   // Function to convert a string to a value.  Returns the empty
109   // StringRef on success or an error string if string is malformed:
110   //static StringRef input(StringRef scalar, void *ctxt, T &value);
111 };
112
113
114 /// This class should be specialized by any type that needs to be converted
115 /// to/from a YAML sequence.  For example:
116 ///
117 ///    template<>
118 ///    struct SequenceTraits< std::vector<MyType> > {
119 ///      static size_t size(IO &io, std::vector<MyType> &seq) {
120 ///        return seq.size();
121 ///      }
122 ///      static MyType& element(IO &, std::vector<MyType> &seq, size_t index) {
123 ///        if ( index >= seq.size() )
124 ///          seq.resize(index+1);
125 ///        return seq[index];
126 ///      }
127 ///    };
128 template<typename T>
129 struct SequenceTraits {
130   // Must provide:
131   // static size_t size(IO &io, T &seq);
132   // static T::value_type& element(IO &io, T &seq, size_t index);
133   //
134   // The following is option and will cause generated YAML to use
135   // a flow sequence (e.g. [a,b,c]).
136   // static const bool flow = true;
137 };
138
139
140 /// This class should be specialized by any type that needs to be converted
141 /// to/from a list of YAML documents.
142 template<typename T>
143 struct DocumentListTraits {
144   // Must provide:
145   // static size_t size(IO &io, T &seq);
146   // static T::value_type& element(IO &io, T &seq, size_t index);
147 };
148
149
150 // Only used by compiler if both template types are the same
151 template <typename T, T>
152 struct SameType;
153
154 // Only used for better diagnostics of missing traits
155 template <typename T>
156 struct MissingTrait;
157
158
159
160 // Test if ScalarEnumerationTraits<T> is defined on type T.
161 template <class T>
162 struct has_ScalarEnumerationTraits
163 {
164   typedef void (*Signature_enumeration)(class IO&, T&);
165
166   template <typename U>
167   static char test(SameType<Signature_enumeration, &U::enumeration>*);
168
169   template <typename U>
170   static double test(...);
171
172 public:
173   static bool const value = (sizeof(test<ScalarEnumerationTraits<T> >(0)) == 1);
174 };
175
176
177 // Test if ScalarBitSetTraits<T> is defined on type T.
178 template <class T>
179 struct has_ScalarBitSetTraits
180 {
181   typedef void (*Signature_bitset)(class IO&, T&);
182
183   template <typename U>
184   static char test(SameType<Signature_bitset, &U::bitset>*);
185
186   template <typename U>
187   static double test(...);
188
189 public:
190   static bool const value = (sizeof(test<ScalarBitSetTraits<T> >(0)) == 1);
191 };
192
193
194 // Test if ScalarTraits<T> is defined on type T.
195 template <class T>
196 struct has_ScalarTraits
197 {
198   typedef llvm::StringRef (*Signature_input)(llvm::StringRef, void*, T&);
199   typedef void (*Signature_output)(const T&, void*, llvm::raw_ostream&);
200
201   template <typename U>
202   static char test(SameType<Signature_input, &U::input>*,
203                    SameType<Signature_output, &U::output>*);
204
205   template <typename U>
206   static double test(...);
207
208 public:
209   static bool const value = (sizeof(test<ScalarTraits<T> >(0,0)) == 1);
210 };
211
212
213 // Test if MappingTraits<T> is defined on type T.
214 template <class T>
215 struct has_MappingTraits
216 {
217   typedef void (*Signature_mapping)(class IO&, T&);
218
219   template <typename U>
220   static char test(SameType<Signature_mapping, &U::mapping>*);
221
222   template <typename U>
223   static double test(...);
224
225 public:
226   static bool const value = (sizeof(test<MappingTraits<T> >(0)) == 1);
227 };
228
229
230 // Test if SequenceTraits<T> is defined on type T.
231 template <class T>
232 struct has_SequenceMethodTraits
233 {
234   typedef size_t (*Signature_size)(class IO&, T&);
235
236   template <typename U>
237   static char test(SameType<Signature_size, &U::size>*);
238
239   template <typename U>
240   static double test(...);
241
242 public:
243   static bool const value =  (sizeof(test<SequenceTraits<T> >(0)) == 1);
244 };
245
246
247 // has_FlowTraits<int> will cause an error with some compilers because
248 // it subclasses int.  Using this wrapper only instantiates the
249 // real has_FlowTraits only if the template type is a class.
250 template <typename T, bool Enabled = llvm::is_class<T>::value>
251 class has_FlowTraits
252 {
253 public:
254    static const bool value = false;
255 };
256
257 // Some older gcc compilers don't support straight forward tests
258 // for members, so test for ambiguity cause by the base and derived
259 // classes both defining the member.
260 template <class T>
261 struct has_FlowTraits<T, true>
262 {
263   struct Fallback { bool flow; };
264   struct Derived : T, Fallback { };
265
266   template<typename C>
267   static char (&f(SameType<bool Fallback::*, &C::flow>*))[1];
268
269   template<typename C>
270   static char (&f(...))[2];
271
272 public:
273   static bool const value = sizeof(f<Derived>(0)) == 2;
274 };
275
276
277
278 // Test if SequenceTraits<T> is defined on type T
279 // and SequenceTraits<T>::flow is *not* defined.
280 template<typename T>
281 struct has_SequenceTraits : public  llvm::integral_constant<bool,
282                                          has_SequenceMethodTraits<T>::value
283                                       && !has_FlowTraits<T>::value > { };
284
285
286 // Test if SequenceTraits<T> is defined on type T
287 // and SequenceTraits<T>::flow is defined.
288 template<typename T>
289 struct has_FlowSequenceTraits : public llvm::integral_constant<bool,
290                                          has_SequenceMethodTraits<T>::value
291                                       && has_FlowTraits<T>::value > { };
292
293
294
295 // Test if DocumentListTraits<T> is defined on type T
296 template <class T>
297 struct has_DocumentListTraits
298 {
299   typedef size_t (*Signature_size)(class IO&, T&);
300
301   template <typename U>
302   static char test(SameType<Signature_size, &U::size>*);
303
304   template <typename U>
305   static double test(...);
306
307 public:
308   static bool const value =  (sizeof(test<DocumentListTraits<T> >(0)) == 1);
309 };
310
311
312
313
314 template<typename T>
315 struct missingTraits : public  llvm::integral_constant<bool,
316                                          !has_ScalarEnumerationTraits<T>::value
317                                       && !has_ScalarBitSetTraits<T>::value
318                                       && !has_ScalarTraits<T>::value
319                                       && !has_MappingTraits<T>::value
320                                       && !has_SequenceTraits<T>::value
321                                       && !has_FlowSequenceTraits<T>::value
322                                       && !has_DocumentListTraits<T>::value >  {};
323
324
325 // Base class for Input and Output.
326 class IO {
327 public:
328
329   IO(void *Ctxt=NULL);
330   virtual ~IO();
331
332   virtual bool outputting() = 0;
333
334   virtual unsigned beginSequence() = 0;
335   virtual bool preflightElement(unsigned, void *&) = 0;
336   virtual void postflightElement(void*) = 0;
337   virtual void endSequence() = 0;
338
339   virtual unsigned beginFlowSequence() = 0;
340   virtual bool preflightFlowElement(unsigned, void *&) = 0;
341   virtual void postflightFlowElement(void*) = 0;
342   virtual void endFlowSequence() = 0;
343
344   virtual void beginMapping() = 0;
345   virtual void endMapping() = 0;
346   virtual bool preflightKey(const char*, bool, bool, bool &, void *&) = 0;
347   virtual void postflightKey(void*) = 0;
348
349   virtual void beginEnumScalar() = 0;
350   virtual bool matchEnumScalar(const char*, bool) = 0;
351   virtual void endEnumScalar() = 0;
352
353   virtual bool beginBitSetScalar(bool &) = 0;
354   virtual bool bitSetMatch(const char*, bool) = 0;
355   virtual void endBitSetScalar() = 0;
356
357   virtual void scalarString(StringRef &) = 0;
358
359   virtual void setError(const Twine &) = 0;
360
361   template <typename T>
362   void enumCase(T &Val, const char* Str, const T ConstVal) {
363     if ( matchEnumScalar(Str, outputting() && Val == ConstVal) ) {
364       Val = ConstVal;
365     }
366   }
367
368   // allow anonymous enum values to be used with LLVM_YAML_STRONG_TYPEDEF
369   template <typename T>
370   void enumCase(T &Val, const char* Str, const uint32_t ConstVal) {
371     if ( matchEnumScalar(Str, outputting() && Val == static_cast<T>(ConstVal)) ) {
372       Val = ConstVal;
373     }
374   }
375
376   template <typename T>
377   void bitSetCase(T &Val, const char* Str, const T ConstVal) {
378     if ( bitSetMatch(Str, outputting() && (Val & ConstVal) == ConstVal) ) {
379       Val = Val | ConstVal;
380     }
381   }
382
383   // allow anonymous enum values to be used with LLVM_YAML_STRONG_TYPEDEF
384   template <typename T>
385   void bitSetCase(T &Val, const char* Str, const uint32_t ConstVal) {
386     if ( bitSetMatch(Str, outputting() && (Val & ConstVal) == ConstVal) ) {
387       Val = Val | ConstVal;
388     }
389   }
390
391   void *getContext();
392   void setContext(void *);
393
394   template <typename T>
395   void mapRequired(const char* Key, T& Val) {
396     this->processKey(Key, Val, true);
397   }
398
399   template <typename T>
400   typename llvm::enable_if_c<has_SequenceTraits<T>::value,void>::type
401   mapOptional(const char* Key, T& Val) {
402     // omit key/value instead of outputting empty sequence
403     if ( this->outputting() && !(Val.begin() != Val.end()) )
404       return;
405     this->processKey(Key, Val, false);
406   }
407
408   template <typename T>
409   typename llvm::enable_if_c<!has_SequenceTraits<T>::value,void>::type
410   mapOptional(const char* Key, T& Val) {
411     this->processKey(Key, Val, false);
412   }
413
414   template <typename T>
415   void mapOptional(const char* Key, T& Val, const T& Default) {
416     this->processKeyWithDefault(Key, Val, Default, false);
417   }
418
419
420 private:
421   template <typename T>
422   void processKeyWithDefault(const char *Key, T &Val, const T& DefaultValue,
423                                                                 bool Required) {
424     void *SaveInfo;
425     bool UseDefault;
426     const bool sameAsDefault = outputting() && Val == DefaultValue;
427     if ( this->preflightKey(Key, Required, sameAsDefault, UseDefault,
428                                                                   SaveInfo) ) {
429       yamlize(*this, Val, Required);
430       this->postflightKey(SaveInfo);
431     }
432     else {
433       if ( UseDefault )
434         Val = DefaultValue;
435     }
436   }
437
438   template <typename T>
439   void processKey(const char *Key, T &Val, bool Required) {
440     void *SaveInfo;
441     bool UseDefault;
442     if ( this->preflightKey(Key, Required, false, UseDefault, SaveInfo) ) {
443       yamlize(*this, Val, Required);
444       this->postflightKey(SaveInfo);
445     }
446   }
447
448 private:
449   void  *Ctxt;
450 };
451
452
453
454 template<typename T>
455 typename llvm::enable_if_c<has_ScalarEnumerationTraits<T>::value,void>::type
456 yamlize(IO &io, T &Val, bool) {
457   io.beginEnumScalar();
458   ScalarEnumerationTraits<T>::enumeration(io, Val);
459   io.endEnumScalar();
460 }
461
462 template<typename T>
463 typename llvm::enable_if_c<has_ScalarBitSetTraits<T>::value,void>::type
464 yamlize(IO &io, T &Val, bool) {
465   bool DoClear;
466   if ( io.beginBitSetScalar(DoClear) ) {
467     if ( DoClear )
468       Val = static_cast<T>(0);
469     ScalarBitSetTraits<T>::bitset(io, Val);
470     io.endBitSetScalar();
471   }
472 }
473
474
475 template<typename T>
476 typename llvm::enable_if_c<has_ScalarTraits<T>::value,void>::type
477 yamlize(IO &io, T &Val, bool) {
478   if ( io.outputting() ) {
479     std::string Storage;
480     llvm::raw_string_ostream Buffer(Storage);
481     ScalarTraits<T>::output(Val, io.getContext(), Buffer);
482     StringRef Str = Buffer.str();
483     io.scalarString(Str);
484   }
485   else {
486     StringRef Str;
487     io.scalarString(Str);
488     StringRef Result = ScalarTraits<T>::input(Str, io.getContext(), Val);
489     if ( !Result.empty() ) {
490       io.setError(llvm::Twine(Result));
491     }
492   }
493 }
494
495
496 template<typename T>
497 typename llvm::enable_if_c<has_MappingTraits<T>::value, void>::type
498 yamlize(IO &io, T &Val, bool) {
499   io.beginMapping();
500   MappingTraits<T>::mapping(io, Val);
501   io.endMapping();
502 }
503
504 template<typename T>
505 typename llvm::enable_if_c<missingTraits<T>::value, void>::type
506 yamlize(IO &io, T &Val, bool) {
507   char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
508 }
509
510 template<typename T>
511 typename llvm::enable_if_c<has_SequenceTraits<T>::value,void>::type
512 yamlize(IO &io, T &Seq, bool) {
513   unsigned incount = io.beginSequence();
514   unsigned count = io.outputting() ? SequenceTraits<T>::size(io, Seq) : incount;
515   for(unsigned i=0; i < count; ++i) {
516     void *SaveInfo;
517     if ( io.preflightElement(i, SaveInfo) ) {
518       yamlize(io, SequenceTraits<T>::element(io, Seq, i), true);
519       io.postflightElement(SaveInfo);
520     }
521   }
522   io.endSequence();
523 }
524
525 template<typename T>
526 typename llvm::enable_if_c<has_FlowSequenceTraits<T>::value,void>::type
527 yamlize(IO &io, T &Seq, bool) {
528   unsigned incount = io.beginFlowSequence();
529   unsigned count = io.outputting() ? SequenceTraits<T>::size(io, Seq) : incount;
530   for(unsigned i=0; i < count; ++i) {
531     void *SaveInfo;
532     if ( io.preflightFlowElement(i, SaveInfo) ) {
533       yamlize(io, SequenceTraits<T>::element(io, Seq, i), true);
534       io.postflightFlowElement(SaveInfo);
535     }
536   }
537   io.endFlowSequence();
538 }
539
540
541
542 template<>
543 struct ScalarTraits<bool> {
544   static void output(const bool &, void*, llvm::raw_ostream &);
545   static llvm::StringRef input(llvm::StringRef , void*, bool &);
546 };
547
548 template<>
549 struct ScalarTraits<StringRef> {
550   static void output(const StringRef &, void*, llvm::raw_ostream &);
551   static llvm::StringRef input(llvm::StringRef , void*, StringRef &);
552 };
553
554 template<>
555 struct ScalarTraits<uint8_t> {
556   static void output(const uint8_t &, void*, llvm::raw_ostream &);
557   static llvm::StringRef input(llvm::StringRef , void*, uint8_t &);
558 };
559
560 template<>
561 struct ScalarTraits<uint16_t> {
562   static void output(const uint16_t &, void*, llvm::raw_ostream &);
563   static llvm::StringRef input(llvm::StringRef , void*, uint16_t &);
564 };
565
566 template<>
567 struct ScalarTraits<uint32_t> {
568   static void output(const uint32_t &, void*, llvm::raw_ostream &);
569   static llvm::StringRef input(llvm::StringRef , void*, uint32_t &);
570 };
571
572 template<>
573 struct ScalarTraits<uint64_t> {
574   static void output(const uint64_t &, void*, llvm::raw_ostream &);
575   static llvm::StringRef input(llvm::StringRef , void*, uint64_t &);
576 };
577
578 template<>
579 struct ScalarTraits<int8_t> {
580   static void output(const int8_t &, void*, llvm::raw_ostream &);
581   static llvm::StringRef input(llvm::StringRef , void*, int8_t &);
582 };
583
584 template<>
585 struct ScalarTraits<int16_t> {
586   static void output(const int16_t &, void*, llvm::raw_ostream &);
587   static llvm::StringRef input(llvm::StringRef , void*, int16_t &);
588 };
589
590 template<>
591 struct ScalarTraits<int32_t> {
592   static void output(const int32_t &, void*, llvm::raw_ostream &);
593   static llvm::StringRef input(llvm::StringRef , void*, int32_t &);
594 };
595
596 template<>
597 struct ScalarTraits<int64_t> {
598   static void output(const int64_t &, void*, llvm::raw_ostream &);
599   static llvm::StringRef input(llvm::StringRef , void*, int64_t &);
600 };
601
602 template<>
603 struct ScalarTraits<float> {
604   static void output(const float &, void*, llvm::raw_ostream &);
605   static llvm::StringRef input(llvm::StringRef , void*, float &);
606 };
607
608 template<>
609 struct ScalarTraits<double> {
610   static void output(const double &, void*, llvm::raw_ostream &);
611   static llvm::StringRef input(llvm::StringRef , void*, double &);
612 };
613
614
615
616 // Utility for use within MappingTraits<>::mapping() method
617 // to [de]normalize an object for use with YAML conversion.
618 template <typename TNorm, typename TFinal>
619 struct MappingNormalization {
620   MappingNormalization(IO &i_o, TFinal &Obj)
621       : io(i_o), BufPtr(NULL), Result(Obj) {
622     if ( io.outputting() ) {
623       BufPtr = new (&Buffer) TNorm(io, Obj);
624     }
625     else {
626       BufPtr = new (&Buffer) TNorm(io);
627     }
628   }
629
630   ~MappingNormalization() {
631     if ( ! io.outputting() ) {
632       Result = BufPtr->denormalize(io);
633     }
634     BufPtr->~TNorm();
635   }
636
637   TNorm* operator->() { return BufPtr; }
638
639 private:
640   typedef llvm::AlignedCharArrayUnion<TNorm> Storage;
641
642   Storage       Buffer;
643   IO           &io;
644   TNorm        *BufPtr;
645   TFinal       &Result;
646 };
647
648
649
650 // Utility for use within MappingTraits<>::mapping() method
651 // to [de]normalize an object for use with YAML conversion.
652 template <typename TNorm, typename TFinal>
653 struct MappingNormalizationHeap {
654   MappingNormalizationHeap(IO &i_o, TFinal &Obj)
655     : io(i_o), BufPtr(NULL), Result(Obj) {
656     if ( io.outputting() ) {
657       BufPtr = new (&Buffer) TNorm(io, Obj);
658     }
659     else {
660       BufPtr = new TNorm(io);
661     }
662   }
663
664   ~MappingNormalizationHeap() {
665     if ( io.outputting() ) {
666       BufPtr->~TNorm();
667     }
668     else {
669       Result = BufPtr->denormalize(io);
670     }
671   }
672
673   TNorm* operator->() { return BufPtr; }
674
675 private:
676   typedef llvm::AlignedCharArrayUnion<TNorm> Storage;
677
678   Storage       Buffer;
679   IO           &io;
680   TNorm        *BufPtr;
681   TFinal       &Result;
682 };
683
684
685
686 ///
687 /// The Input class is used to parse a yaml document into in-memory structs
688 /// and vectors.
689 ///
690 /// It works by using YAMLParser to do a syntax parse of the entire yaml
691 /// document, then the Input class builds a graph of HNodes which wraps
692 /// each yaml Node.  The extra layer is buffering.  The low level yaml
693 /// parser only lets you look at each node once.  The buffering layer lets
694 /// you search and interate multiple times.  This is necessary because
695 /// the mapRequired() method calls may not be in the same order
696 /// as the keys in the document.
697 ///
698 class Input : public IO {
699 public:
700   // Construct a yaml Input object from a StringRef and optional user-data.
701   Input(StringRef InputContent, void *Ctxt=NULL);
702
703   // Check if there was an syntax or semantic error during parsing.
704   llvm::error_code error();
705
706   // To set alternate error reporting.
707   void setDiagHandler(llvm::SourceMgr::DiagHandlerTy Handler, void *Ctxt = 0);
708
709 private:
710   virtual bool outputting();
711   virtual void beginMapping();
712   virtual void endMapping();
713   virtual bool preflightKey(const char *, bool, bool, bool &, void *&);
714   virtual void postflightKey(void *);
715   virtual unsigned beginSequence();
716   virtual void endSequence();
717   virtual bool preflightElement(unsigned index, void *&);
718   virtual void postflightElement(void *);
719   virtual unsigned beginFlowSequence();
720   virtual bool preflightFlowElement(unsigned , void *&);
721   virtual void postflightFlowElement(void *);
722   virtual void endFlowSequence();
723   virtual void beginEnumScalar();
724   virtual bool matchEnumScalar(const char*, bool);
725   virtual void endEnumScalar();
726   virtual bool beginBitSetScalar(bool &);
727   virtual bool bitSetMatch(const char *, bool );
728   virtual void endBitSetScalar();
729   virtual void scalarString(StringRef &);
730   virtual void setError(const Twine &message);
731
732   class HNode {
733   public:
734     HNode(Node *n) : _node(n) { }
735     static inline bool classof(const HNode *) { return true; }
736
737     Node *_node;
738   };
739
740   class EmptyHNode : public HNode {
741   public:
742     EmptyHNode(Node *n) : HNode(n) { }
743     static inline bool classof(const HNode *n) {
744       return NullNode::classof(n->_node);
745     }
746     static inline bool classof(const EmptyHNode *) { return true; }
747   };
748
749   class ScalarHNode : public HNode {
750   public:
751     ScalarHNode(Node *n, StringRef s) : HNode(n), _value(s) { }
752
753     StringRef value() const { return _value; }
754
755     static inline bool classof(const HNode *n) {
756       return ScalarNode::classof(n->_node);
757     }
758     static inline bool classof(const ScalarHNode *) { return true; }
759   protected:
760     StringRef _value;
761   };
762
763   class MapHNode : public HNode {
764   public:
765     MapHNode(Node *n) : HNode(n) { }
766
767     static inline bool classof(const HNode *n) {
768       return MappingNode::classof(n->_node);
769     }
770     static inline bool classof(const MapHNode *) { return true; }
771
772     struct StrMappingInfo {
773       static StringRef getEmptyKey() { return StringRef(); }
774       static StringRef getTombstoneKey() { return StringRef(" ", 0); }
775       static unsigned getHashValue(StringRef const val) {
776                                                 return llvm::HashString(val); }
777       static bool isEqual(StringRef const lhs,
778                           StringRef const rhs) { return lhs.equals(rhs); }
779     };
780     typedef llvm::DenseMap<StringRef, HNode*, StrMappingInfo> NameToNode;
781
782     bool isValidKey(StringRef key);
783
784     NameToNode                        Mapping;
785     llvm::SmallVector<const char*, 6> ValidKeys;
786   };
787
788   class SequenceHNode : public HNode {
789   public:
790     SequenceHNode(Node *n) : HNode(n) { }
791
792     static inline bool classof(const HNode *n) {
793       return SequenceNode::classof(n->_node);
794     }
795     static inline bool classof(const SequenceHNode *) { return true; }
796
797     std::vector<HNode*> Entries;
798   };
799
800   Input::HNode *createHNodes(Node *node);
801   void setError(HNode *hnode, const Twine &message);
802   void setError(Node *node, const Twine &message);
803
804
805 public:
806   // These are only used by operator>>. They could be private
807   // if those templated things could be made friends.
808   bool setCurrentDocument();
809   void nextDocument();
810
811 private:
812   llvm::yaml::Stream              *Strm;
813   llvm::SourceMgr                  SrcMgr;
814   llvm::error_code                 EC;
815   llvm::BumpPtrAllocator           Allocator;
816   llvm::yaml::document_iterator    DocIterator;
817   std::vector<bool>                BitValuesUsed;
818   HNode                           *CurrentNode;
819   bool                             ScalarMatchFound;
820 };
821
822
823
824
825 ///
826 /// The Output class is used to generate a yaml document from in-memory structs
827 /// and vectors.
828 ///
829 class Output : public IO {
830 public:
831   Output(llvm::raw_ostream &, void *Ctxt=NULL);
832   virtual ~Output();
833
834   virtual bool outputting();
835   virtual void beginMapping();
836   virtual void endMapping();
837   virtual bool preflightKey(const char *key, bool, bool, bool &, void *&);
838   virtual void postflightKey(void *);
839   virtual unsigned beginSequence();
840   virtual void endSequence();
841   virtual bool preflightElement(unsigned, void *&);
842   virtual void postflightElement(void *);
843   virtual unsigned beginFlowSequence();
844   virtual bool preflightFlowElement(unsigned, void *&);
845   virtual void postflightFlowElement(void *);
846   virtual void endFlowSequence();
847   virtual void beginEnumScalar();
848   virtual bool matchEnumScalar(const char*, bool);
849   virtual void endEnumScalar();
850   virtual bool beginBitSetScalar(bool &);
851   virtual bool bitSetMatch(const char *, bool );
852   virtual void endBitSetScalar();
853   virtual void scalarString(StringRef &);
854   virtual void setError(const Twine &message);
855
856 public:
857   // These are only used by operator<<. They could be private
858   // if that templated operator could be made a friend.
859   void beginDocuments();
860   bool preflightDocument(unsigned);
861   void postflightDocument();
862   void endDocuments();
863
864 private:
865   void output(StringRef s);
866   void outputUpToEndOfLine(StringRef s);
867   void newLineCheck();
868   void outputNewLine();
869   void paddedKey(StringRef key);
870
871   enum InState { inSeq, inFlowSeq, inMapFirstKey, inMapOtherKey };
872
873   llvm::raw_ostream       &Out;
874   SmallVector<InState, 8>  StateStack;
875   int                      Column;
876   int                      ColumnAtFlowStart;
877   bool                     NeedBitValueComma;
878   bool                     NeedFlowSequenceComma;
879   bool                     EnumerationMatchFound;
880   bool                     NeedsNewLine;
881 };
882
883
884
885
886 /// YAML I/O does conversion based on types. But often native data types
887 /// are just a typedef of built in intergral types (e.g. int).  But the C++
888 /// type matching system sees through the typedef and all the typedefed types
889 /// look like a built in type. This will cause the generic YAML I/O conversion
890 /// to be used. To provide better control over the YAML conversion, you can
891 /// use this macro instead of typedef.  It will create a class with one field
892 /// and automatic conversion operators to and from the base type.
893 /// Based on BOOST_STRONG_TYPEDEF
894 #define LLVM_YAML_STRONG_TYPEDEF(_base, _type)                                 \
895     struct _type {                                                             \
896         _type() { }                                                            \
897         _type(const _base v) : value(v) { }                                    \
898         _type(const _type &v) : value(v.value) {}                              \
899         _type &operator=(const _type &rhs) { value = rhs.value; return *this; }\
900         _type &operator=(const _base &rhs) { value = rhs; return *this; }      \
901         operator const _base & () const { return value; }                      \
902         bool operator==(const _type &rhs) const { return value == rhs.value; } \
903         bool operator==(const _base &rhs) const { return value == rhs; }       \
904         bool operator<(const _type &rhs) const { return value < rhs.value; }   \
905         _base value;                                                           \
906     };
907
908
909
910 ///
911 /// Use these types instead of uintXX_t in any mapping to have
912 /// its yaml output formatted as hexadecimal.
913 ///
914 LLVM_YAML_STRONG_TYPEDEF(uint8_t, Hex8)
915 LLVM_YAML_STRONG_TYPEDEF(uint16_t, Hex16)
916 LLVM_YAML_STRONG_TYPEDEF(uint32_t, Hex32)
917 LLVM_YAML_STRONG_TYPEDEF(uint64_t, Hex64)
918
919
920 template<>
921 struct ScalarTraits<Hex8> {
922   static void output(const Hex8 &, void*, llvm::raw_ostream &);
923   static llvm::StringRef input(llvm::StringRef , void*, Hex8 &);
924 };
925
926 template<>
927 struct ScalarTraits<Hex16> {
928   static void output(const Hex16 &, void*, llvm::raw_ostream &);
929   static llvm::StringRef input(llvm::StringRef , void*, Hex16 &);
930 };
931
932 template<>
933 struct ScalarTraits<Hex32> {
934   static void output(const Hex32 &, void*, llvm::raw_ostream &);
935   static llvm::StringRef input(llvm::StringRef , void*, Hex32 &);
936 };
937
938 template<>
939 struct ScalarTraits<Hex64> {
940   static void output(const Hex64 &, void*, llvm::raw_ostream &);
941   static llvm::StringRef input(llvm::StringRef , void*, Hex64 &);
942 };
943
944
945 // Define non-member operator>> so that Input can stream in a document list.
946 template <typename T>
947 inline
948 typename llvm::enable_if_c<has_DocumentListTraits<T>::value,Input &>::type
949 operator>>(Input &yin, T &docList) {
950   int i = 0;
951   while ( yin.setCurrentDocument() ) {
952     yamlize(yin, DocumentListTraits<T>::element(yin, docList, i), true);
953     if ( yin.error() )
954       return yin;
955     yin.nextDocument();
956     ++i;
957   }
958   return yin;
959 }
960
961 // Define non-member operator>> so that Input can stream in a map as a document.
962 template <typename T>
963 inline
964 typename llvm::enable_if_c<has_MappingTraits<T>::value,Input &>::type
965 operator>>(Input &yin, T &docMap) {
966   yin.setCurrentDocument();
967   yamlize(yin, docMap, true);
968   return yin;
969 }
970
971 // Define non-member operator>> so that Input can stream in a sequence as
972 // a document.
973 template <typename T>
974 inline
975 typename llvm::enable_if_c<has_SequenceTraits<T>::value,Input &>::type
976 operator>>(Input &yin, T &docSeq) {
977   yin.setCurrentDocument();
978   yamlize(yin, docSeq, true);
979   return yin;
980 }
981
982 // Provide better error message about types missing a trait specialization
983 template <typename T>
984 inline
985 typename llvm::enable_if_c<missingTraits<T>::value,Input &>::type
986 operator>>(Input &yin, T &docSeq) {
987   char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
988   return yin;
989 }
990
991
992 // Define non-member operator<< so that Output can stream out document list.
993 template <typename T>
994 inline
995 typename llvm::enable_if_c<has_DocumentListTraits<T>::value,Output &>::type
996 operator<<(Output &yout, T &docList) {
997   yout.beginDocuments();
998   const size_t count = DocumentListTraits<T>::size(yout, docList);
999   for(size_t i=0; i < count; ++i) {
1000     if ( yout.preflightDocument(i) ) {
1001       yamlize(yout, DocumentListTraits<T>::element(yout, docList, i), true);
1002       yout.postflightDocument();
1003     }
1004   }
1005   yout.endDocuments();
1006   return yout;
1007 }
1008
1009 // Define non-member operator<< so that Output can stream out a map.
1010 template <typename T>
1011 inline
1012 typename llvm::enable_if_c<has_MappingTraits<T>::value,Output &>::type
1013 operator<<(Output &yout, T &map) {
1014   yout.beginDocuments();
1015   if ( yout.preflightDocument(0) ) {
1016     yamlize(yout, map, true);
1017     yout.postflightDocument();
1018   }
1019   yout.endDocuments();
1020   return yout;
1021 }
1022
1023 // Define non-member operator<< so that Output can stream out a sequence.
1024 template <typename T>
1025 inline
1026 typename llvm::enable_if_c<has_SequenceTraits<T>::value,Output &>::type
1027 operator<<(Output &yout, T &seq) {
1028   yout.beginDocuments();
1029   if ( yout.preflightDocument(0) ) {
1030     yamlize(yout, seq, true);
1031     yout.postflightDocument();
1032   }
1033   yout.endDocuments();
1034   return yout;
1035 }
1036
1037 // Provide better error message about types missing a trait specialization
1038 template <typename T>
1039 inline
1040 typename llvm::enable_if_c<missingTraits<T>::value,Output &>::type
1041 operator<<(Output &yout, T &seq) {
1042   char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
1043   return yout;
1044 }
1045
1046
1047 } // namespace yaml
1048 } // namespace llvm
1049
1050
1051 /// Utility for declaring that a std::vector of a particular type
1052 /// should be considered a YAML sequence.
1053 #define LLVM_YAML_IS_SEQUENCE_VECTOR(_type)                                 \
1054   namespace llvm {                                                          \
1055   namespace yaml {                                                          \
1056     template<>                                                              \
1057     struct SequenceTraits< std::vector<_type> > {                           \
1058       static size_t size(IO &io, std::vector<_type> &seq) {                 \
1059         return seq.size();                                                  \
1060       }                                                                     \
1061       static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\
1062         if ( index >= seq.size() )                                          \
1063           seq.resize(index+1);                                              \
1064         return seq[index];                                                  \
1065       }                                                                     \
1066     };                                                                      \
1067   }                                                                         \
1068   }
1069
1070 /// Utility for declaring that a std::vector of a particular type
1071 /// should be considered a YAML flow sequence.
1072 #define LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(_type)                            \
1073   namespace llvm {                                                          \
1074   namespace yaml {                                                          \
1075     template<>                                                              \
1076     struct SequenceTraits< std::vector<_type> > {                           \
1077       static size_t size(IO &io, std::vector<_type> &seq) {                 \
1078         return seq.size();                                                  \
1079       }                                                                     \
1080       static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\
1081         if ( index >= seq.size() )                                          \
1082           seq.resize(index+1);                                              \
1083         return seq[index];                                                  \
1084       }                                                                     \
1085       static const bool flow = true;                                        \
1086     };                                                                      \
1087   }                                                                         \
1088   }
1089
1090 /// Utility for declaring that a std::vector of a particular type
1091 /// should be considered a YAML document list.
1092 #define LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(_type)                            \
1093   namespace llvm {                                                          \
1094   namespace yaml {                                                          \
1095     template<>                                                              \
1096     struct DocumentListTraits< std::vector<_type> > {                       \
1097       static size_t size(IO &io, std::vector<_type> &seq) {                 \
1098         return seq.size();                                                  \
1099       }                                                                     \
1100       static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\
1101         if ( index >= seq.size() )                                          \
1102           seq.resize(index+1);                                              \
1103         return seq[index];                                                  \
1104       }                                                                     \
1105     };                                                                      \
1106   }                                                                         \
1107   }
1108
1109
1110
1111 #endif // LLVM_YAML_TRAITS_H_